code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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 the lwIP TCP/IP stack. * * Author: Erik Ekman <erik@kryo.se> * */ #include "lwip/init.h" #include "lwip/netif.h" #include "netif/etharp.h" #if LWIP_IPV6 #include "lwip/ethip6.h" #include "lwip/nd6.h" #endif #include <string.h> #include <stdio.h> /* no-op send function */ static err_t lwip_tx_func(struct netif *netif, struct pbuf *p) { LWIP_UNUSED_ARG(netif); LWIP_UNUSED_ARG(p); return ERR_OK; } static err_t testif_init(struct netif *netif) { netif->name[0] = 'f'; netif->name[1] = 'z'; netif->output = etharp_output; netif->linkoutput = lwip_tx_func; netif->mtu = 1500; netif->hwaddr_len = 6; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; netif->hwaddr[0] = 0x00; netif->hwaddr[1] = 0x23; netif->hwaddr[2] = 0xC1; netif->hwaddr[3] = 0xDE; netif->hwaddr[4] = 0xD0; netif->hwaddr[5] = 0x0D; #if LWIP_IPV6 netif->output_ip6 = ethip6_output; netif->ip6_autoconfig_enabled = 1; netif_create_ip6_linklocal_address(netif, 1); netif->flags |= NETIF_FLAG_MLD6; #endif return ERR_OK; } static void input_pkt(struct netif *netif, const u8_t *data, size_t len) { struct pbuf *p, *q; err_t err; LWIP_ASSERT("pkt too big", len <= 0xFFFF); p = pbuf_alloc(PBUF_RAW, (u16_t)len, PBUF_POOL); LWIP_ASSERT("alloc failed", p); for(q = p; q != NULL; q = q->next) { MEMCPY(q->payload, data, q->len); data += q->len; } err = netif->input(p, netif); if (err != ERR_OK) { pbuf_free(p); } } int main(int argc, char** argv) { struct netif net_test; ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; u8_t pktbuf[2000]; size_t len; lwip_init(); IP4_ADDR(&addr, 172, 30, 115, 84); IP4_ADDR(&netmask, 255, 255, 255, 0); IP4_ADDR(&gw, 172, 30, 115, 1); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); #if LWIP_IPV6 nd6_tmr(); /* tick nd to join multicast groups */ #endif if(argc > 1) { FILE* f; const char* filename; printf("reading input from file... "); fflush(stdout); filename = argv[1]; LWIP_ASSERT("invalid filename", filename != NULL); f = fopen(filename, "rb"); LWIP_ASSERT("open failed", f != NULL); len = fread(pktbuf, 1, sizeof(pktbuf), f); fclose(f); printf("testing file: \"%s\"...\r\n", filename); } else { len = fread(pktbuf, 1, sizeof(pktbuf), stdin); } input_pkt(&net_test, pktbuf, len); return 0; }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/fuzz/fuzz.c
C
unknown
4,112
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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 the lwIP TCP/IP stack. * * Author: Simon Goldschmidt * */ #ifndef LWIP_HDR_LWIPOPTS_H__ #define LWIP_HDR_LWIPOPTS_H__ /* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */ #define NO_SYS 1 #define LWIP_NETCONN 0 #define LWIP_SOCKET 0 #define SYS_LIGHTWEIGHT_PROT 0 #define LWIP_IPV6 1 #define IPV6_FRAG_COPYHEADER 1 #define LWIP_IPV6_DUP_DETECT_ATTEMPTS 0 /* Enable DHCP to test it */ #define LWIP_DHCP 1 /* Turn off checksum verification of fuzzed data */ #define CHECKSUM_CHECK_IP 0 #define CHECKSUM_CHECK_UDP 0 #define CHECKSUM_CHECK_TCP 0 #define CHECKSUM_CHECK_ICMP 0 #define CHECKSUM_CHECK_ICMP6 0 /* Minimal changes to opt.h required for tcp unit tests: */ #define MEM_SIZE 16000 #define TCP_SND_QUEUELEN 40 #define MEMP_NUM_TCP_SEG TCP_SND_QUEUELEN #define TCP_SND_BUF (12 * TCP_MSS) #define TCP_WND (10 * TCP_MSS) #define LWIP_WND_SCALE 1 #define TCP_RCV_SCALE 0 #define PBUF_POOL_SIZE 400 /* pbuf tests need ~200KByte */ /* Minimal changes to opt.h required for etharp unit tests: */ #define ETHARP_SUPPORT_STATIC_ENTRIES 1 #endif /* LWIP_HDR_LWIPOPTS_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/test/fuzz/lwipopts.h
C
unknown
3,061
#!/bin/bash if [ -z "$1" ] then echo "This script will make pcap files from the afl-fuzz crash/hang files" echo "It needs hexdump and text2pcap" echo "Please give output directory as argument" exit 2 fi for i in `ls $1/crashes/id*` do PCAPNAME=`echo $i | grep pcap` if [ -z "$PCAPNAME" ]; then hexdump -C $i > $1/$$.tmp text2pcap $1/$$.tmp ${i}.pcap fi done for i in `ls $1/hangs/id*` do PCAPNAME=`echo $i | grep pcap` if [ -z "$PCAPNAME" ]; then hexdump -C $i > $1/$$.tmp text2pcap $1/$$.tmp ${i}.pcap fi done rm -f $1/$$.tmp echo echo "Created pcap files:" ls $1/*/*.pcap
2301_81045437/classic-platform
communication/lwip-2.0.3/test/fuzz/output_to_pcap.sh
Shell
unknown
626
#include "test_mem.h" #include "lwip/mem.h" #include "lwip/stats.h" #if !LWIP_STATS || !MEM_STATS #error "This tests needs MEM-statistics enabled" #endif #if LWIP_DNS #error "This test needs DNS turned off (as it mallocs on init)" #endif /* Setups/teardown functions */ static void mem_setup(void) { } static void mem_teardown(void) { } /* Test functions */ /** Call mem_malloc, mem_free and mem_trim and check stats */ START_TEST(test_mem_one) { #define SIZE1 16 #define SIZE1_2 12 #define SIZE2 16 void *p1, *p2; mem_size_t s1, s2; LWIP_UNUSED_ARG(_i); fail_unless(lwip_stats.mem.used == 0); p1 = mem_malloc(SIZE1); fail_unless(p1 != NULL); fail_unless(lwip_stats.mem.used >= SIZE1); s1 = lwip_stats.mem.used; p2 = mem_malloc(SIZE2); fail_unless(p2 != NULL); fail_unless(lwip_stats.mem.used >= SIZE2 + s1); s2 = lwip_stats.mem.used; mem_trim(p1, SIZE1_2); mem_free(p2); fail_unless(lwip_stats.mem.used <= s2 - SIZE2); mem_free(p1); fail_unless(lwip_stats.mem.used == 0); } END_TEST static void malloc_keep_x(int x, int num, int size, int freestep) { int i; void* p[16]; LWIP_ASSERT("invalid size", size >= 0 && size < (mem_size_t)-1); memset(p, 0, sizeof(p)); for(i = 0; i < num && i < 16; i++) { p[i] = mem_malloc((mem_size_t)size); fail_unless(p[i] != NULL); } for(i = 0; i < num && i < 16; i += freestep) { if (i == x) { continue; } mem_free(p[i]); p[i] = NULL; } for(i = 0; i < num && i < 16; i++) { if (i == x) { continue; } if (p[i] != NULL) { mem_free(p[i]); p[i] = NULL; } } fail_unless(p[x] != NULL); mem_free(p[x]); } START_TEST(test_mem_random) { const int num = 16; int x; int size; int freestep; LWIP_UNUSED_ARG(_i); fail_unless(lwip_stats.mem.used == 0); for (x = 0; x < num; x++) { for (size = 1; size < 32; size++) { for (freestep = 1; freestep <= 3; freestep++) { fail_unless(lwip_stats.mem.used == 0); malloc_keep_x(x, num, size, freestep); fail_unless(lwip_stats.mem.used == 0); } } } } END_TEST /** Create the suite including all tests for this module */ Suite * mem_suite(void) { testfunc tests[] = { TESTFUNC(test_mem_one), TESTFUNC(test_mem_random) }; return create_suite("MEM", tests, sizeof(tests)/sizeof(testfunc), mem_setup, mem_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/core/test_mem.c
C
unknown
2,567
#ifndef LWIP_HDR_TEST_MEM_H #define LWIP_HDR_TEST_MEM_H #include "../lwip_check.h" Suite *mem_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/core/test_mem.h
C
unknown
125
#include "test_pbuf.h" #include "lwip/pbuf.h" #include "lwip/stats.h" #if !LWIP_STATS || !MEM_STATS ||!MEMP_STATS #error "This tests needs MEM- and MEMP-statistics enabled" #endif #if LWIP_DNS #error "This test needs DNS turned off (as it mallocs on init)" #endif #if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !LWIP_WND_SCALE #error "This test needs TCP OOSEQ queueing and window scaling enabled" #endif /* Setups/teardown functions */ static void pbuf_setup(void) { } static void pbuf_teardown(void) { } #define TESTBUFSIZE_1 65535 #define TESTBUFSIZE_2 65530 #define TESTBUFSIZE_3 50050 static u8_t testbuf_1[TESTBUFSIZE_1]; static u8_t testbuf_1a[TESTBUFSIZE_1]; static u8_t testbuf_2[TESTBUFSIZE_2]; static u8_t testbuf_2a[TESTBUFSIZE_2]; static u8_t testbuf_3[TESTBUFSIZE_3]; static u8_t testbuf_3a[TESTBUFSIZE_3]; /* Test functions */ /** Call pbuf_copy on a pbuf with zero length */ START_TEST(test_pbuf_copy_zero_pbuf) { struct pbuf *p1, *p2, *p3; err_t err; LWIP_UNUSED_ARG(_i); fail_unless(lwip_stats.mem.used == 0); fail_unless(MEMP_STATS_GET(used, MEMP_PBUF_POOL) == 0); p1 = pbuf_alloc(PBUF_RAW, 1024, PBUF_RAM); fail_unless(p1 != NULL); fail_unless(p1->ref == 1); p2 = pbuf_alloc(PBUF_RAW, 2, PBUF_POOL); fail_unless(p2 != NULL); fail_unless(p2->ref == 1); p2->len = p2->tot_len = 0; pbuf_cat(p1, p2); fail_unless(p1->ref == 1); fail_unless(p2->ref == 1); p3 = pbuf_alloc(PBUF_RAW, p1->tot_len, PBUF_POOL); err = pbuf_copy(p3, p1); fail_unless(err == ERR_VAL); pbuf_free(p1); pbuf_free(p3); fail_unless(lwip_stats.mem.used == 0); fail_unless(lwip_stats.mem.used == 0); fail_unless(MEMP_STATS_GET(used, MEMP_PBUF_POOL) == 0); } END_TEST START_TEST(test_pbuf_split_64k_on_small_pbufs) { struct pbuf *p, *rest=NULL; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, 1, PBUF_POOL); pbuf_split_64k(p, &rest); fail_unless(p->tot_len == 1); pbuf_free(p); } END_TEST START_TEST(test_pbuf_queueing_bigger_than_64k) { int i; err_t err; struct pbuf *p1, *p2, *p3, *rest2=NULL, *rest3=NULL; LWIP_UNUSED_ARG(_i); for(i = 0; i < TESTBUFSIZE_1; i++) { testbuf_1[i] = (u8_t)rand(); } for(i = 0; i < TESTBUFSIZE_2; i++) { testbuf_2[i] = (u8_t)rand(); } for(i = 0; i < TESTBUFSIZE_3; i++) { testbuf_3[i] = (u8_t)rand(); } p1 = pbuf_alloc(PBUF_RAW, TESTBUFSIZE_1, PBUF_POOL); fail_unless(p1 != NULL); p2 = pbuf_alloc(PBUF_RAW, TESTBUFSIZE_2, PBUF_POOL); fail_unless(p2 != NULL); p3 = pbuf_alloc(PBUF_RAW, TESTBUFSIZE_3, PBUF_POOL); fail_unless(p3 != NULL); err = pbuf_take(p1, testbuf_1, TESTBUFSIZE_1); fail_unless(err == ERR_OK); err = pbuf_take(p2, testbuf_2, TESTBUFSIZE_2); fail_unless(err == ERR_OK); err = pbuf_take(p3, testbuf_3, TESTBUFSIZE_3); fail_unless(err == ERR_OK); pbuf_cat(p1, p2); pbuf_cat(p1, p3); pbuf_split_64k(p1, &rest2); fail_unless(p1->tot_len == TESTBUFSIZE_1); fail_unless(rest2->tot_len == (u16_t)((TESTBUFSIZE_2+TESTBUFSIZE_3) & 0xFFFF)); pbuf_split_64k(rest2, &rest3); fail_unless(rest2->tot_len == TESTBUFSIZE_2); fail_unless(rest3->tot_len == TESTBUFSIZE_3); pbuf_copy_partial(p1, testbuf_1a, TESTBUFSIZE_1, 0); pbuf_copy_partial(rest2, testbuf_2a, TESTBUFSIZE_2, 0); pbuf_copy_partial(rest3, testbuf_3a, TESTBUFSIZE_3, 0); for(i = 0; i < TESTBUFSIZE_1; i++) fail_unless(testbuf_1[i] == testbuf_1a[i]); for(i = 0; i < TESTBUFSIZE_2; i++) fail_unless(testbuf_2[i] == testbuf_2a[i]); for(i = 0; i < TESTBUFSIZE_3; i++) fail_unless(testbuf_3[i] == testbuf_3a[i]); pbuf_free(p1); pbuf_free(rest2); pbuf_free(rest3); } END_TEST /* Test for bug that writing with pbuf_take_at() did nothing * and returned ERR_OK when writing at beginning of a pbuf * in the chain. */ START_TEST(test_pbuf_take_at_edge) { err_t res; u8_t *out; int i; u8_t testdata[] = { 0x01, 0x08, 0x82, 0x02 }; struct pbuf *p = pbuf_alloc(PBUF_RAW, 1024, PBUF_POOL); struct pbuf *q = p->next; LWIP_UNUSED_ARG(_i); /* alloc big enough to get a chain of pbufs */ fail_if(p->tot_len == p->len); memset(p->payload, 0, p->len); memset(q->payload, 0, q->len); /* copy data to the beginning of first pbuf */ res = pbuf_take_at(p, &testdata, sizeof(testdata), 0); fail_unless(res == ERR_OK); out = (u8_t*)p->payload; for (i = 0; i < (int)sizeof(testdata); i++) { fail_unless(out[i] == testdata[i], "Bad data at pos %d, was %02X, expected %02X", i, out[i], testdata[i]); } /* copy data to the just before end of first pbuf */ res = pbuf_take_at(p, &testdata, sizeof(testdata), p->len - 1); fail_unless(res == ERR_OK); out = (u8_t*)p->payload; fail_unless(out[p->len - 1] == testdata[0], "Bad data at pos %d, was %02X, expected %02X", p->len - 1, out[p->len - 1], testdata[0]); out = (u8_t*)q->payload; for (i = 1; i < (int)sizeof(testdata); i++) { fail_unless(out[i-1] == testdata[i], "Bad data at pos %d, was %02X, expected %02X", p->len - 1 + i, out[i-1], testdata[i]); } /* copy data to the beginning of second pbuf */ res = pbuf_take_at(p, &testdata, sizeof(testdata), p->len); fail_unless(res == ERR_OK); out = (u8_t*)p->payload; for (i = 0; i < (int)sizeof(testdata); i++) { fail_unless(out[i] == testdata[i], "Bad data at pos %d, was %02X, expected %02X", p->len+i, out[i], testdata[i]); } } END_TEST /* Verify pbuf_put_at()/pbuf_get_at() when using * offsets equal to beginning of new pbuf in chain */ START_TEST(test_pbuf_get_put_at_edge) { u8_t *out; u8_t testdata = 0x01; u8_t getdata; struct pbuf *p = pbuf_alloc(PBUF_RAW, 1024, PBUF_POOL); struct pbuf *q = p->next; LWIP_UNUSED_ARG(_i); /* alloc big enough to get a chain of pbufs */ fail_if(p->tot_len == p->len); memset(p->payload, 0, p->len); memset(q->payload, 0, q->len); /* put byte at the beginning of second pbuf */ pbuf_put_at(p, p->len, testdata); out = (u8_t*)q->payload; fail_unless(*out == testdata, "Bad data at pos %d, was %02X, expected %02X", p->len, *out, testdata); getdata = pbuf_get_at(p, p->len); fail_unless(*out == getdata, "pbuf_get_at() returned bad data at pos %d, was %02X, expected %02X", p->len, getdata, *out); } END_TEST /** Create the suite including all tests for this module */ Suite * pbuf_suite(void) { testfunc tests[] = { TESTFUNC(test_pbuf_copy_zero_pbuf), TESTFUNC(test_pbuf_split_64k_on_small_pbufs), TESTFUNC(test_pbuf_queueing_bigger_than_64k), TESTFUNC(test_pbuf_take_at_edge), TESTFUNC(test_pbuf_get_put_at_edge) }; return create_suite("PBUF", tests, sizeof(tests)/sizeof(testfunc), pbuf_setup, pbuf_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/core/test_pbuf.c
C
unknown
6,893
#ifndef LWIP_HDR_TEST_PBUF_H #define LWIP_HDR_TEST_PBUF_H #include "../lwip_check.h" Suite *pbuf_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/core/test_pbuf.h
C
unknown
128
#include "test_dhcp.h" #include "lwip/netif.h" #include "lwip/dhcp.h" #include "lwip/prot/dhcp.h" #include "lwip/etharp.h" #include "netif/ethernet.h" struct netif net_test; static const u8_t broadcast[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static const u8_t magic_cookie[] = { 0x63, 0x82, 0x53, 0x63 }; static u8_t dhcp_offer[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */ 0x00, 0x0F, 0xEE, 0x30, 0xAB, 0x22, /* From Remote host */ 0x08, 0x00, /* Protocol: IP */ 0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */ 0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */ 0x02, /* Type == Boot reply */ 0x01, 0x06, /* Hw Ethernet, 6 bytes addrlen */ 0x00, /* 0 hops */ 0xAA, 0xAA, 0xAA, 0xAA, /* Transaction id, will be overwritten */ 0x00, 0x00, /* 0 seconds elapsed */ 0x00, 0x00, /* Flags (unicast) */ 0x00, 0x00, 0x00, 0x00, /* Client ip */ 0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */ 0xc3, 0xaa, 0xbd, 0xab, /* DHCP server ip */ 0x00, 0x00, 0x00, 0x00, /* relay agent */ 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* MAC addr + padding */ /* Empty server name and boot file name */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, /* Magic cookie */ 0x35, 0x01, 0x02, /* Message type: Offer */ 0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Server identifier (IP) */ 0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */ 0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */ 0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Subnet mask */ 0xff, /* End option */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */ }; static u8_t dhcp_ack[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */ 0x00, 0x0f, 0xEE, 0x30, 0xAB, 0x22, /* From remote host */ 0x08, 0x00, /* Proto IP */ 0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */ 0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */ 0x02, /* Bootp reply */ 0x01, 0x06, /* Hw type Eth, len 6 */ 0x00, /* 0 hops */ 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, /* 0 seconds elapsed */ 0x00, 0x00, /* Flags (unicast) */ 0x00, 0x00, 0x00, 0x00, /* Client IP */ 0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */ 0xc3, 0xaa, 0xbd, 0xab, /* DHCP server IP */ 0x00, 0x00, 0x00, 0x00, /* Relay agent */ 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Macaddr + padding */ /* Empty server name and boot file name */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, /* Magic cookie */ 0x35, 0x01, 0x05, /* Dhcp message type ack */ 0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* DHCP server identifier */ 0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */ 0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */ 0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Netmask */ 0xff, /* End marker */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */ }; static const u8_t arpreply[] = { 0x00, 0x23, 0xC1, 0xDE, 0xD0, 0x0D, /* dst mac */ 0x00, 0x32, 0x44, 0x20, 0x01, 0x02, /* src mac */ 0x08, 0x06, /* proto arp */ 0x00, 0x01, /* hw eth */ 0x08, 0x00, /* proto ip */ 0x06, /* hw addr len 6 */ 0x04, /* proto addr len 4 */ 0x00, 0x02, /* arp reply */ 0x00, 0x32, 0x44, 0x20, 0x01, 0x02, /* sender mac */ 0xc3, 0xaa, 0xbd, 0xc8, /* sender ip */ 0x00, 0x23, 0xC1, 0xDE, 0xD0, 0x0D, /* target mac */ 0x00, 0x00, 0x00, 0x00, /* target ip */ }; static int txpacket; static enum tcase { TEST_LWIP_DHCP, TEST_LWIP_DHCP_NAK, TEST_LWIP_DHCP_RELAY, TEST_LWIP_DHCP_NAK_NO_ENDMARKER, TEST_LWIP_DHCP_INVALID_OVERLOAD } tcase; static int debug = 0; static void setdebug(int a) {debug = a;} static int tick = 0; static void tick_lwip(void) { tick++; if (tick % 5 == 0) { dhcp_fine_tmr(); } if (tick % 600 == 0) { dhcp_coarse_tmr(); } } static void send_pkt(struct netif *netif, const u8_t *data, size_t len) { struct pbuf *p, *q; LWIP_ASSERT("pkt too big", len <= 0xFFFF); p = pbuf_alloc(PBUF_RAW, (u16_t)len, PBUF_POOL); if (debug) { /* Dump data */ u32_t i; printf("RX data (len %d)", p->tot_len); for (i = 0; i < len; i++) { printf(" %02X", data[i]); } printf("\n"); } fail_unless(p != NULL); for(q = p; q != NULL; q = q->next) { memcpy(q->payload, data, q->len); data += q->len; } netif->input(p, netif); } static err_t lwip_tx_func(struct netif *netif, struct pbuf *p); static err_t testif_init(struct netif *netif) { netif->name[0] = 'c'; netif->name[1] = 'h'; netif->output = etharp_output; netif->linkoutput = lwip_tx_func; netif->mtu = 1500; netif->hwaddr_len = 6; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; netif->hwaddr[0] = 0x00; netif->hwaddr[1] = 0x23; netif->hwaddr[2] = 0xC1; netif->hwaddr[3] = 0xDE; netif->hwaddr[4] = 0xD0; netif->hwaddr[5] = 0x0D; return ERR_OK; } static void dhcp_setup(void) { txpacket = 0; } static void dhcp_teardown(void) { } static void check_pkt(struct pbuf *p, u32_t pos, const u8_t *mem, u32_t len) { u8_t *data; fail_if((pos + len) > p->tot_len); while (pos > p->len && p->next) { pos -= p->len; p = p->next; } fail_if(p == NULL); fail_unless(pos + len <= p->len); /* All data we seek within same pbuf */ data = (u8_t*)p->payload; fail_if(memcmp(&data[pos], mem, len), "data at pos %d, len %d in packet %d did not match", pos, len, txpacket); } static void check_pkt_fuzzy(struct pbuf *p, u32_t startpos, const u8_t *mem, u32_t len) { int found; u32_t i; u8_t *data; fail_if((startpos + len) > p->tot_len); while (startpos > p->len && p->next) { startpos -= p->len; p = p->next; } fail_if(p == NULL); fail_unless(startpos + len <= p->len); /* All data we seek within same pbuf */ found = 0; data = (u8_t*)p->payload; for (i = startpos; i <= (p->len - len); i++) { if (memcmp(&data[i], mem, len) == 0) { found = 1; break; } } fail_unless(found); } static err_t lwip_tx_func(struct netif *netif, struct pbuf *p) { fail_unless(netif == &net_test); txpacket++; if (debug) { struct pbuf *pp = p; /* Dump data */ printf("TX data (pkt %d, len %d, tick %d)", txpacket, p->tot_len, tick); do { int i; for (i = 0; i < pp->len; i++) { printf(" %02X", ((u8_t *) pp->payload)[i]); } if (pp->next) { pp = pp->next; } } while (pp->next); printf("\n"); } switch (tcase) { case TEST_LWIP_DHCP: switch (txpacket) { case 1: case 2: { const u8_t ipproto[] = { 0x08, 0x00 }; const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */ const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */ check_pkt(p, 42, bootp_start, sizeof(bootp_start)); check_pkt(p, 53, ipaddrs, sizeof(ipaddrs)); check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */ check_pkt(p, 278, magic_cookie, sizeof(magic_cookie)); /* Check dchp message type, can be at different positions */ if (txpacket == 1) { u8_t dhcp_discover_opt[] = { 0x35, 0x01, 0x01 }; check_pkt_fuzzy(p, 282, dhcp_discover_opt, sizeof(dhcp_discover_opt)); } else if (txpacket == 2) { u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 }; u8_t requested_ipaddr[] = { 0x32, 0x04, 0xc3, 0xaa, 0xbd, 0xc8 }; /* Ask for offered IP */ check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt)); check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr)); } break; } case 3: case 4: case 5: { const u8_t arpproto[] = { 0x08, 0x06 }; check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, arpproto, sizeof(arpproto)); /* eth level proto: ip */ break; } default: fail(); break; } break; case TEST_LWIP_DHCP_NAK: { const u8_t ipproto[] = { 0x08, 0x00 }; const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */ const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const u8_t dhcp_nak_opt[] = { 0x35, 0x01, 0x04 }; const u8_t requested_ipaddr[] = { 0x32, 0x04, 0xc3, 0xaa, 0xbd, 0xc8 }; /* offered IP */ fail_unless(txpacket == 4); check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */ check_pkt(p, 42, bootp_start, sizeof(bootp_start)); check_pkt(p, 53, ipaddrs, sizeof(ipaddrs)); check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */ check_pkt(p, 278, magic_cookie, sizeof(magic_cookie)); check_pkt_fuzzy(p, 282, dhcp_nak_opt, sizeof(dhcp_nak_opt)); /* NAK the ack */ check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr)); break; } case TEST_LWIP_DHCP_RELAY: switch (txpacket) { case 1: case 2: { const u8_t ipproto[] = { 0x08, 0x00 }; const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */ const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */ check_pkt(p, 42, bootp_start, sizeof(bootp_start)); check_pkt(p, 53, ipaddrs, sizeof(ipaddrs)); check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */ check_pkt(p, 278, magic_cookie, sizeof(magic_cookie)); /* Check dchp message type, can be at different positions */ if (txpacket == 1) { u8_t dhcp_discover_opt[] = { 0x35, 0x01, 0x01 }; check_pkt_fuzzy(p, 282, dhcp_discover_opt, sizeof(dhcp_discover_opt)); } else if (txpacket == 2) { u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 }; u8_t requested_ipaddr[] = { 0x32, 0x04, 0x4f, 0x8a, 0x33, 0x05 }; /* Ask for offered IP */ check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt)); check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr)); } break; } case 3: case 4: case 5: case 6: { const u8_t arpproto[] = { 0x08, 0x06 }; check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, arpproto, sizeof(arpproto)); /* eth level proto: ip */ break; } case 7: { const u8_t fake_arp[6] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xab }; const u8_t ipproto[] = { 0x08, 0x00 }; const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */ const u8_t ipaddrs[] = { 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 }; check_pkt(p, 0, fake_arp, 6); /* eth level dest: broadcast */ check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */ check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */ check_pkt(p, 42, bootp_start, sizeof(bootp_start)); check_pkt(p, 53, ipaddrs, sizeof(ipaddrs)); check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */ check_pkt(p, 278, magic_cookie, sizeof(magic_cookie)); /* Check dchp message type, can be at different positions */ check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt)); break; } default: fail(); break; } break; default: break; } return ERR_OK; } /* * Test basic happy flow DHCP session. * Validate that xid is checked. */ START_TEST(test_dhcp) { ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; int i; u32_t xid; LWIP_UNUSED_ARG(_i); tcase = TEST_LWIP_DHCP; setdebug(0); IP4_ADDR(&addr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); dhcp_start(&net_test); fail_unless(txpacket == 1); /* DHCP discover sent */ xid = netif_dhcp_data(&net_test)->xid; /* Write bad xid, not using htonl! */ memcpy(&dhcp_offer[46], &xid, 4); send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1, "TX %d packets, expected 1", txpacket); /* Nothing more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */ send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); fail_unless(txpacket == 2, "TX %d packets, expected 2", txpacket); /* DHCP request sent */ xid = netif_dhcp_data(&net_test)->xid; /* Write bad xid, not using htonl! */ memcpy(&dhcp_ack[46], &xid, 4); send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack)); fail_unless(txpacket == 2, "TX %d packets, still expected 2", txpacket); /* No more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ memcpy(&dhcp_ack[46], &xid, 4); /* insert transaction id */ send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack)); for (i = 0; i < 20; i++) { tick_lwip(); } fail_unless(txpacket == 5, "TX %d packets, expected 5", txpacket); /* ARP requests sent */ /* Interface up */ fail_unless(netif_is_up(&net_test)); /* Now it should have taken the IP */ IP4_ADDR(&addr, 195, 170, 189, 200); IP4_ADDR(&netmask, 255, 255, 255, 0); IP4_ADDR(&gw, 195, 170, 189, 171); fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); netif_remove(&net_test); } END_TEST /* * Test that IP address is not taken and NAK is sent if someone * replies to ARP requests for the offered address. */ START_TEST(test_dhcp_nak) { ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; u32_t xid; LWIP_UNUSED_ARG(_i); tcase = TEST_LWIP_DHCP; setdebug(0); IP4_ADDR(&addr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); dhcp_start(&net_test); fail_unless(txpacket == 1); /* DHCP discover sent */ xid = netif_dhcp_data(&net_test)->xid; /* Write bad xid, not using htonl! */ memcpy(&dhcp_offer[46], &xid, 4); send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */ send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); fail_unless(txpacket == 2); /* DHCP request sent */ xid = netif_dhcp_data(&net_test)->xid; /* Write bad xid, not using htonl! */ memcpy(&dhcp_ack[46], &xid, 4); send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack)); fail_unless(txpacket == 2); /* No more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ memcpy(&dhcp_ack[46], &xid, 4); /* insert transaction id */ send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack)); fail_unless(txpacket == 3); /* ARP request sent */ tcase = TEST_LWIP_DHCP_NAK; /* Switch testcase */ /* Send arp reply, mark offered IP as taken */ send_pkt(&net_test, arpreply, sizeof(arpreply)); fail_unless(txpacket == 4); /* DHCP nak sent */ netif_remove(&net_test); } END_TEST /* * Test case based on captured data where * replies are sent from a different IP than the * one the client unicasted to. */ START_TEST(test_dhcp_relayed) { u8_t relay_offer[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60, 0x08, 0x00, 0x45, 0x00, 0x01, 0x38, 0xfd, 0x53, 0x00, 0x00, 0x40, 0x11, 0x78, 0x46, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24, 0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x51, 0x35, 0xb6, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00, 0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08, 0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1, 0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04, 0x00, 0x00, 0x54, 0x49, 0x35, 0x01, 0x02, 0x36, 0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff }; u8_t relay_ack1[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60, 0x08, 0x00, 0x45, 0x00, 0x01, 0x38, 0xfd, 0x55, 0x00, 0x00, 0x40, 0x11, 0x78, 0x44, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24, 0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x51, 0x35, 0xb6, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00, 0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08, 0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1, 0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04, 0x00, 0x00, 0x54, 0x49, 0x35, 0x01, 0x05, 0x36, 0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff }; u8_t relay_ack2[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60, 0x08, 0x00, 0x45, 0x00, 0x01, 0x38, 0xfa, 0x18, 0x00, 0x00, 0x40, 0x11, 0x7b, 0x81, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24, 0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x49, 0x8b, 0x6e, 0xab, 0x00, 0x00, 0x00, 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00, 0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08, 0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1, 0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04, 0x00, 0x00, 0x54, 0x60, 0x35, 0x01, 0x05, 0x36, 0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff }; const u8_t arp_resp[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* DEST */ 0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60, /* SRC */ 0x08, 0x06, /* Type: ARP */ 0x00, 0x01, /* HW: Ethernet */ 0x08, 0x00, /* PROTO: IP */ 0x06, /* HW size */ 0x04, /* PROTO size */ 0x00, 0x02, /* OPCODE: Reply */ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xab, /* Target MAC */ 0x4f, 0x8a, 0x32, 0x01, /* Target IP */ 0x00, 0x23, 0xc1, 0x00, 0x06, 0x50, /* src mac */ 0x4f, 0x8a, 0x33, 0x05, /* src ip */ /* Padding follows.. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; int i; u32_t xid; LWIP_UNUSED_ARG(_i); tcase = TEST_LWIP_DHCP_RELAY; setdebug(0); IP4_ADDR(&addr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); dhcp_start(&net_test); fail_unless(txpacket == 1); /* DHCP discover sent */ /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); memcpy(&relay_offer[46], &xid, 4); /* insert correct transaction id */ send_pkt(&net_test, relay_offer, sizeof(relay_offer)); /* request sent? */ fail_unless(txpacket == 2, "txpkt = %d, should be 2", txpacket); xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ memcpy(&relay_ack1[46], &xid, 4); /* insert transaction id */ send_pkt(&net_test, relay_ack1, sizeof(relay_ack1)); for (i = 0; i < 25; i++) { tick_lwip(); } fail_unless(txpacket == 5, "txpkt should be 5, is %d", txpacket); /* ARP requests sent */ /* Interface up */ fail_unless(netif_is_up(&net_test)); /* Now it should have taken the IP */ IP4_ADDR(&addr, 79, 138, 51, 5); IP4_ADDR(&netmask, 255, 255, 254, 0); IP4_ADDR(&gw, 79, 138, 50, 1); fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 5, "txpacket = %d", txpacket); for (i = 0; i < 108000 - 25; i++) { tick_lwip(); } fail_unless(netif_is_up(&net_test)); fail_unless(txpacket == 6, "txpacket = %d", txpacket); /* We need to send arp response here.. */ send_pkt(&net_test, arp_resp, sizeof(arp_resp)); fail_unless(txpacket == 7, "txpacket = %d", txpacket); fail_unless(netif_is_up(&net_test)); xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ memcpy(&relay_ack2[46], &xid, 4); /* insert transaction id */ send_pkt(&net_test, relay_ack2, sizeof(relay_ack2)); for (i = 0; i < 100000; i++) { tick_lwip(); } fail_unless(txpacket == 7, "txpacket = %d", txpacket); netif_remove(&net_test); } END_TEST START_TEST(test_dhcp_nak_no_endmarker) { ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; u8_t dhcp_nack_no_endmarker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x54, 0x75, 0xd0, 0x26, 0xd0, 0x0d, 0x08, 0x00, 0x45, 0x00, 0x01, 0x15, 0x38, 0x86, 0x00, 0x00, 0xff, 0x11, 0xc0, 0xa8, 0xc0, 0xa8, 0x01, 0x01, 0xff, 0xff, 0xff, 0xff, 0x00, 0x43, 0x00, 0x44, 0x01, 0x01, 0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x7a, 0xcb, 0xba, 0xf2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x35, 0x01, 0x06, 0x36, 0x04, 0xc0, 0xa8, 0x01, 0x01, 0x31, 0xef, 0xad, 0x72, 0x31, 0x43, 0x4e, 0x44, 0x30, 0x32, 0x35, 0x30, 0x43, 0x52, 0x47, 0x44, 0x38, 0x35, 0x36, 0x3c, 0x08, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30, 0x37, 0x0d, 0x01, 0x0f, 0x03, 0x06, 0x2c, 0x2e, 0x2f, 0x1f, 0x21, 0x79, 0xf9, 0x2b, 0xfc, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe2, 0x71, 0xf3, 0x5b, 0xe2, 0x71, 0x2e, 0x01, 0x08, 0x03, 0x04, 0xc0, 0xa8, 0x01, 0x01, 0xff, 0xeb, 0x1e, 0x44, 0xec, 0xeb, 0x1e, 0x30, 0x37, 0x0c, 0x01, 0x0f, 0x03, 0x06, 0x2c, 0x2e, 0x2f, 0x1f, 0x21, 0x79, 0xf9, 0x2b, 0xff, 0x25, 0xc0, 0x09, 0xd6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; u32_t xid; LWIP_UNUSED_ARG(_i); tcase = TEST_LWIP_DHCP_NAK_NO_ENDMARKER; setdebug(0); IP4_ADDR(&addr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); dhcp_start(&net_test); fail_unless(txpacket == 1); /* DHCP discover sent */ xid = netif_dhcp_data(&net_test)->xid; /* Write bad xid, not using htonl! */ memcpy(&dhcp_offer[46], &xid, 4); send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */ send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer)); fail_unless(netif_dhcp_data(&net_test)->state == DHCP_STATE_REQUESTING); fail_unless(txpacket == 2); /* No more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ memcpy(&dhcp_nack_no_endmarker[46], &xid, 4); /* insert transaction id */ send_pkt(&net_test, dhcp_nack_no_endmarker, sizeof(dhcp_nack_no_endmarker)); /* NAK should put us in another state for a while, no other way detecting it */ fail_unless(netif_dhcp_data(&net_test)->state != DHCP_STATE_REQUESTING); netif_remove(&net_test); } END_TEST START_TEST(test_dhcp_invalid_overload) { u8_t dhcp_offer_invalid_overload[] = { 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */ 0x00, 0x0F, 0xEE, 0x30, 0xAB, 0x22, /* From Remote host */ 0x08, 0x00, /* Protocol: IP */ 0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */ 0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */ 0x02, /* Type == Boot reply */ 0x01, 0x06, /* Hw Ethernet, 6 bytes addrlen */ 0x00, /* 0 hops */ 0xAA, 0xAA, 0xAA, 0xAA, /* Transaction id, will be overwritten */ 0x00, 0x00, /* 0 seconds elapsed */ 0x00, 0x00, /* Flags (unicast) */ 0x00, 0x00, 0x00, 0x00, /* Client ip */ 0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */ 0xc3, 0xaa, 0xbd, 0xab, /* DHCP server ip */ 0x00, 0x00, 0x00, 0x00, /* relay agent */ 0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* MAC addr + padding */ /* Empty server name */ 0x34, 0x01, 0x02, 0xff, /* Overload: SNAME + END */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Empty boot file name */ 0x34, 0x01, 0x01, 0xff, /* Overload FILE + END */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, /* Magic cookie */ 0x35, 0x01, 0x02, /* Message type: Offer */ 0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Server identifier (IP) */ 0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */ 0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */ 0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Subnet mask */ 0x34, 0x01, 0x03, /* Overload: FILE + SNAME */ 0xff, /* End option */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */ }; ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; u32_t xid; LWIP_UNUSED_ARG(_i); tcase = TEST_LWIP_DHCP_INVALID_OVERLOAD; setdebug(0); IP4_ADDR(&addr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); dhcp_start(&net_test); fail_unless(txpacket == 1); /* DHCP discover sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); memcpy(&dhcp_offer_invalid_overload[46], &xid, 4); /* insert correct transaction id */ dhcp_offer_invalid_overload[311] = 3; send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ dhcp_offer_invalid_overload[311] = 2; send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ dhcp_offer_invalid_overload[311] = 1; send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload)); /* IP addresses should be zero */ fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t))); fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t))); fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t))); fail_unless(txpacket == 1); /* Nothing more sent */ dhcp_offer_invalid_overload[311] = 0; send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer)); fail_unless(netif_dhcp_data(&net_test)->state == DHCP_STATE_REQUESTING); fail_unless(txpacket == 2); /* No more sent */ xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */ netif_remove(&net_test); } END_TEST /** Create the suite including all tests for this module */ Suite * dhcp_suite(void) { testfunc tests[] = { TESTFUNC(test_dhcp), TESTFUNC(test_dhcp_nak), TESTFUNC(test_dhcp_relayed), TESTFUNC(test_dhcp_nak_no_endmarker), TESTFUNC(test_dhcp_invalid_overload) }; return create_suite("DHCP", tests, sizeof(tests)/sizeof(testfunc), dhcp_setup, dhcp_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/dhcp/test_dhcp.c
C
unknown
40,116
#ifndef LWIP_HDR_TEST_DHCP_H #define LWIP_HDR_TEST_DHCP_H #include "../lwip_check.h" Suite* dhcp_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/dhcp/test_dhcp.h
C
unknown
128
#include "test_etharp.h" #include "lwip/udp.h" #include "lwip/etharp.h" #include "netif/ethernet.h" #include "lwip/stats.h" #if !LWIP_STATS || !UDP_STATS || !MEMP_STATS || !ETHARP_STATS #error "This tests needs UDP-, MEMP- and ETHARP-statistics enabled" #endif #if !ETHARP_SUPPORT_STATIC_ENTRIES #error "This test needs ETHARP_SUPPORT_STATIC_ENTRIES enabled" #endif static struct netif test_netif; static ip4_addr_t test_ipaddr, test_netmask, test_gw; struct eth_addr test_ethaddr = {{1,1,1,1,1,1}}; struct eth_addr test_ethaddr2 = {{1,1,1,1,1,2}}; struct eth_addr test_ethaddr3 = {{1,1,1,1,1,3}}; struct eth_addr test_ethaddr4 = {{1,1,1,1,1,4}}; static int linkoutput_ctr; /* Helper functions */ static void etharp_remove_all(void) { int i; /* call etharp_tmr often enough to have all entries cleaned */ for(i = 0; i < 0xff; i++) { etharp_tmr(); } } static err_t default_netif_linkoutput(struct netif *netif, struct pbuf *p) { fail_unless(netif == &test_netif); fail_unless(p != NULL); linkoutput_ctr++; return ERR_OK; } static err_t default_netif_init(struct netif *netif) { fail_unless(netif != NULL); netif->linkoutput = default_netif_linkoutput; netif->output = etharp_output; netif->mtu = 1500; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP; netif->hwaddr_len = ETHARP_HWADDR_LEN; return ERR_OK; } static void default_netif_add(void) { IP4_ADDR(&test_gw, 192,168,0,1); IP4_ADDR(&test_ipaddr, 192,168,0,1); IP4_ADDR(&test_netmask, 255,255,0,0); fail_unless(netif_default == NULL); netif_set_default(netif_add(&test_netif, &test_ipaddr, &test_netmask, &test_gw, NULL, default_netif_init, NULL)); netif_set_up(&test_netif); } static void default_netif_remove(void) { fail_unless(netif_default == &test_netif); netif_remove(&test_netif); } static void create_arp_response(ip4_addr_t *adr) { int k; struct eth_hdr *ethhdr; struct etharp_hdr *etharphdr; struct pbuf *p = pbuf_alloc(PBUF_RAW, sizeof(struct eth_hdr) + sizeof(struct etharp_hdr), PBUF_RAM); if(p == NULL) { FAIL_RET(); } ethhdr = (struct eth_hdr*)p->payload; etharphdr = (struct etharp_hdr*)(ethhdr + 1); ethhdr->dest = test_ethaddr; ethhdr->src = test_ethaddr2; ethhdr->type = htons(ETHTYPE_ARP); etharphdr->hwtype = htons(/*HWTYPE_ETHERNET*/ 1); etharphdr->proto = htons(ETHTYPE_IP); etharphdr->hwlen = ETHARP_HWADDR_LEN; etharphdr->protolen = sizeof(ip4_addr_t); etharphdr->opcode = htons(ARP_REPLY); SMEMCPY(&etharphdr->sipaddr, adr, sizeof(ip4_addr_t)); SMEMCPY(&etharphdr->dipaddr, &test_ipaddr, sizeof(ip4_addr_t)); k = 6; while(k > 0) { k--; /* Write the ARP MAC-Addresses */ etharphdr->shwaddr.addr[k] = test_ethaddr2.addr[k]; etharphdr->dhwaddr.addr[k] = test_ethaddr.addr[k]; /* Write the Ethernet MAC-Addresses */ ethhdr->dest.addr[k] = test_ethaddr.addr[k]; ethhdr->src.addr[k] = test_ethaddr2.addr[k]; } ethernet_input(p, &test_netif); } /* Setups/teardown functions */ static void etharp_setup(void) { etharp_remove_all(); default_netif_add(); } static void etharp_teardown(void) { etharp_remove_all(); default_netif_remove(); } /* Test functions */ START_TEST(test_etharp_table) { #if ETHARP_SUPPORT_STATIC_ENTRIES err_t err; #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ s8_t idx; const ip4_addr_t *unused_ipaddr; struct eth_addr *unused_ethaddr; struct udp_pcb* pcb; LWIP_UNUSED_ARG(_i); if (netif_default != &test_netif) { fail("This test needs a default netif"); } linkoutput_ctr = 0; pcb = udp_new(); fail_unless(pcb != NULL); if (pcb != NULL) { ip4_addr_t adrs[ARP_TABLE_SIZE + 2]; int i; for(i = 0; i < ARP_TABLE_SIZE + 2; i++) { IP4_ADDR(&adrs[i], 192,168,0,i+2); } /* fill ARP-table with dynamic entries */ for(i = 0; i < ARP_TABLE_SIZE; i++) { struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 10, PBUF_RAM); fail_unless(p != NULL); if (p != NULL) { err_t err2; ip_addr_t dst; ip_addr_copy_from_ip4(dst, adrs[i]); err2 = udp_sendto(pcb, p, &dst, 123); fail_unless(err2 == ERR_OK); /* etharp request sent? */ fail_unless(linkoutput_ctr == (2*i) + 1); pbuf_free(p); /* create an ARP response */ create_arp_response(&adrs[i]); /* queued UDP packet sent? */ fail_unless(linkoutput_ctr == (2*i) + 2); idx = etharp_find_addr(NULL, &adrs[i], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == i); etharp_tmr(); } } linkoutput_ctr = 0; #if ETHARP_SUPPORT_STATIC_ENTRIES /* create one static entry */ err = etharp_add_static_entry(&adrs[ARP_TABLE_SIZE], &test_ethaddr3); fail_unless(err == ERR_OK); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == 0); fail_unless(linkoutput_ctr == 0); #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ linkoutput_ctr = 0; /* fill ARP-table with dynamic entries */ for(i = 0; i < ARP_TABLE_SIZE; i++) { struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 10, PBUF_RAM); fail_unless(p != NULL); if (p != NULL) { err_t err2; ip_addr_t dst; ip_addr_copy_from_ip4(dst, adrs[i]); err2 = udp_sendto(pcb, p, &dst, 123); fail_unless(err2 == ERR_OK); /* etharp request sent? */ fail_unless(linkoutput_ctr == (2*i) + 1); pbuf_free(p); /* create an ARP response */ create_arp_response(&adrs[i]); /* queued UDP packet sent? */ fail_unless(linkoutput_ctr == (2*i) + 2); idx = etharp_find_addr(NULL, &adrs[i], &unused_ethaddr, &unused_ipaddr); if (i < ARP_TABLE_SIZE - 1) { fail_unless(idx == i+1); } else { /* the last entry must not overwrite the static entry! */ fail_unless(idx == 1); } etharp_tmr(); } } #if ETHARP_SUPPORT_STATIC_ENTRIES /* create a second static entry */ err = etharp_add_static_entry(&adrs[ARP_TABLE_SIZE+1], &test_ethaddr4); fail_unless(err == ERR_OK); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == 0); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE+1], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == 2); /* and remove it again */ err = etharp_remove_static_entry(&adrs[ARP_TABLE_SIZE+1]); fail_unless(err == ERR_OK); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == 0); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE+1], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == -1); #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ /* check that static entries don't time out */ etharp_remove_all(); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == 0); #if ETHARP_SUPPORT_STATIC_ENTRIES /* remove the first static entry */ err = etharp_remove_static_entry(&adrs[ARP_TABLE_SIZE]); fail_unless(err == ERR_OK); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == -1); idx = etharp_find_addr(NULL, &adrs[ARP_TABLE_SIZE+1], &unused_ethaddr, &unused_ipaddr); fail_unless(idx == -1); #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ udp_remove(pcb); } } END_TEST /** Create the suite including all tests for this module */ Suite * etharp_suite(void) { testfunc tests[] = { TESTFUNC(test_etharp_table) }; return create_suite("ETHARP", tests, sizeof(tests)/sizeof(testfunc), etharp_setup, etharp_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/etharp/test_etharp.c
C
unknown
8,036
#ifndef LWIP_HDR_TEST_ETHARP_H #define LWIP_HDR_TEST_ETHARP_H #include "../lwip_check.h" Suite* etharp_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/etharp/test_etharp.h
C
unknown
134
#include "test_ip4.h" #include "lwip/ip4.h" #include "lwip/inet_chksum.h" #include "lwip/stats.h" #include "lwip/prot/ip.h" #include "lwip/prot/ip4.h" #if !LWIP_IPV4 || !IP_REASSEMBLY || !MIB2_STATS || !IPFRAG_STATS #error "This tests needs LWIP_IPV4, IP_REASSEMBLY; MIB2- and IPFRAG-statistics enabled" #endif /* Helper functions */ static void create_ip4_input_fragment(u16_t ip_id, u16_t start, u16_t len, int last) { struct pbuf *p; struct netif *input_netif = netif_list; /* just use any netif */ fail_unless((start & 7) == 0); fail_unless(((len & 7) == 0) || last); fail_unless(input_netif != NULL); p = pbuf_alloc(PBUF_RAW, len + sizeof(struct ip_hdr), PBUF_RAM); fail_unless(p != NULL); if (p != NULL) { err_t err; struct ip_hdr *iphdr = (struct ip_hdr *)p->payload; IPH_VHL_SET(iphdr, 4, sizeof(struct ip_hdr) / 4); IPH_TOS_SET(iphdr, 0); IPH_LEN_SET(iphdr, lwip_htons(p->tot_len)); IPH_ID_SET(iphdr, lwip_htons(ip_id)); if (last) { IPH_OFFSET_SET(iphdr, lwip_htons(start / 8)); } else { IPH_OFFSET_SET(iphdr, lwip_htons((start / 8) | IP_MF)); } IPH_TTL_SET(iphdr, 5); IPH_PROTO_SET(iphdr, IP_PROTO_UDP); IPH_CHKSUM_SET(iphdr, 0); ip4_addr_copy(iphdr->src, *netif_ip4_addr(input_netif)); iphdr->src.addr = lwip_htonl(lwip_htonl(iphdr->src.addr) + 1); ip4_addr_copy(iphdr->dest, *netif_ip4_addr(input_netif)); IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, sizeof(struct ip_hdr))); err = ip4_input(p, input_netif); if (err != ERR_OK) { pbuf_free(p); } fail_unless(err == ERR_OK); } } /* Setups/teardown functions */ static void ip4_setup(void) { } static void ip4_teardown(void) { if (netif_list->loop_first != NULL) { pbuf_free(netif_list->loop_first); netif_list->loop_first = NULL; } netif_list->loop_last = NULL; } /* Test functions */ START_TEST(test_ip4_reass) { const u16_t ip_id = 128; LWIP_UNUSED_ARG(_i); memset(&lwip_stats.mib2, 0, sizeof(lwip_stats.mib2)); create_ip4_input_fragment(ip_id, 8*200, 200, 1); fail_unless(lwip_stats.ip_frag.recv == 1); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 0*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 2); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 1*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 3); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 2*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 4); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 3*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 5); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 4*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 6); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 7*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 7); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 6*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 8); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 0); create_ip4_input_fragment(ip_id, 5*200, 200, 0); fail_unless(lwip_stats.ip_frag.recv == 9); fail_unless(lwip_stats.ip_frag.err == 0); fail_unless(lwip_stats.ip_frag.memerr == 0); fail_unless(lwip_stats.ip_frag.drop == 0); fail_unless(lwip_stats.mib2.ipreasmoks == 1); } END_TEST /** Create the suite including all tests for this module */ Suite * ip4_suite(void) { testfunc tests[] = { TESTFUNC(test_ip4_reass), }; return create_suite("IPv4", tests, sizeof(tests)/sizeof(testfunc), ip4_setup, ip4_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/ip4/test_ip4.c
C
unknown
4,956
#ifndef LWIP_HDR_TEST_IP4_H #define LWIP_HDR_TEST_IP4_H #include "../lwip_check.h" Suite* ip4_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/ip4/test_ip4.h
C
unknown
125
#ifndef LWIP_HDR_LWIP_CHECK_H #define LWIP_HDR_LWIP_CHECK_H /* Common header file for lwIP unit tests using the check framework */ #include <config.h> #include <check.h> #include <stdlib.h> #define FAIL_RET() do { fail(); return; } while(0) #define EXPECT(x) fail_unless(x) #define EXPECT_RET(x) do { fail_unless(x); if(!(x)) { return; }} while(0) #define EXPECT_RETX(x, y) do { fail_unless(x); if(!(x)) { return y; }} while(0) #define EXPECT_RETNULL(x) EXPECT_RETX(x, NULL) typedef struct { TFun func; const char *name; } testfunc; #define TESTFUNC(x) {(x), "" # x "" } /* Modified function from check.h, supplying function name */ #define tcase_add_named_test(tc,tf) \ _tcase_add_test((tc),(tf).func,(tf).name,0, 0, 0, 1) /** typedef for a function returning a test suite */ typedef Suite* (suite_getter_fn)(void); /** Create a test suite */ Suite* create_suite(const char* name, testfunc *tests, size_t num_tests, SFun setup, SFun teardown); #ifdef LWIP_UNITTESTS_LIB int lwip_unittests_run(void) #endif #endif /* LWIP_HDR_LWIP_CHECK_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/lwip_check.h
C
unknown
1,096
#include "lwip_check.h" #include "ip4/test_ip4.h" #include "udp/test_udp.h" #include "tcp/test_tcp.h" #include "tcp/test_tcp_oos.h" #include "core/test_mem.h" #include "core/test_pbuf.h" #include "etharp/test_etharp.h" #include "dhcp/test_dhcp.h" #include "mdns/test_mdns.h" #include "lwip/init.h" Suite* create_suite(const char* name, testfunc *tests, size_t num_tests, SFun setup, SFun teardown) { size_t i; Suite *s = suite_create(name); for(i = 0; i < num_tests; i++) { TCase *tc_core = tcase_create(name); if ((setup != NULL) || (teardown != NULL)) { tcase_add_checked_fixture(tc_core, setup, teardown); } tcase_add_named_test(tc_core, tests[i]); suite_add_tcase(s, tc_core); } return s; } #ifdef LWIP_UNITTESTS_LIB int lwip_unittests_run(void) #else int main(void) #endif { int number_failed; SRunner *sr; size_t i; suite_getter_fn* suites[] = { ip4_suite, udp_suite, tcp_suite, tcp_oos_suite, mem_suite, pbuf_suite, etharp_suite, dhcp_suite, mdns_suite }; size_t num = sizeof(suites)/sizeof(void*); LWIP_ASSERT("No suites defined", num > 0); lwip_init(); sr = srunner_create((suites[0])()); for(i = 1; i < num; i++) { srunner_add_suite(sr, ((suite_getter_fn*)suites[i])()); } #ifdef LWIP_UNITTESTS_NOFORK srunner_set_fork_status(sr, CK_NOFORK); #endif #ifdef LWIP_UNITTESTS_FORK srunner_set_fork_status(sr, CK_FORK); #endif srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/lwip_unittests.c
C
unknown
1,676
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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 the lwIP TCP/IP stack. * * Author: Simon Goldschmidt * */ #ifndef LWIP_HDR_LWIPOPTS_H #define LWIP_HDR_LWIPOPTS_H /* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */ #define NO_SYS 1 #define SYS_LIGHTWEIGHT_PROT 0 #define LWIP_NETCONN 0 #define LWIP_SOCKET 0 /* Enable DHCP to test it, disable UDP checksum to easier inject packets */ #define LWIP_DHCP 1 /* Minimal changes to opt.h required for tcp unit tests: */ #define MEM_SIZE 16000 #define TCP_SND_QUEUELEN 40 #define MEMP_NUM_TCP_SEG TCP_SND_QUEUELEN #define TCP_SND_BUF (12 * TCP_MSS) #define TCP_WND (10 * TCP_MSS) #define LWIP_WND_SCALE 1 #define TCP_RCV_SCALE 0 #define PBUF_POOL_SIZE 400 /* pbuf tests need ~200KByte */ /* Enable IGMP and MDNS for MDNS tests */ #define LWIP_IGMP 1 #define LWIP_MDNS_RESPONDER 1 #define LWIP_NUM_NETIF_CLIENT_DATA (LWIP_MDNS_RESPONDER) /* Minimal changes to opt.h required for etharp unit tests: */ #define ETHARP_SUPPORT_STATIC_ENTRIES 1 /* MIB2 stats are required to check IPv4 reassembly results */ #define MIB2_STATS 1 #endif /* LWIP_HDR_LWIPOPTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/lwipopts.h
C
unknown
3,004
/* * Copyright (c) 2015 Verisure Innovation AB * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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 the lwIP TCP/IP stack. * * Author: Erik Ekman <erik@kryo.se> * */ #include "test_mdns.h" #include "lwip/pbuf.h" #include "lwip/apps/mdns.h" #include "lwip/apps/mdns_priv.h" START_TEST(readname_basic) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == sizeof(data)); fail_unless(domain.length == sizeof(data)); fail_if(memcmp(&domain.name, data, sizeof(data))); } END_TEST START_TEST(readname_anydata) { static const u8_t data[] = { 0x05, 0x00, 0xFF, 0x08, 0xc0, 0x0f, 0x04, 0x7f, 0x80, 0x82, 0x88, 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == sizeof(data)); fail_unless(domain.length == sizeof(data)); fail_if(memcmp(&domain.name, data, sizeof(data))); } END_TEST START_TEST(readname_short_buf) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a' }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_long_label) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x52, 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_overflow) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_jump_earlier) { static const u8_t data[] = { /* Some padding needed, not supported to jump to bytes containing dns header */ /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10 */ 0x0f, 0x0e, 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xab, /* 20 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x0c }; static const u8_t fullname[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 20, &domain); pbuf_free(p); fail_unless(offset == sizeof(data)); fail_unless(domain.length == sizeof(fullname)); fail_if(memcmp(&domain.name, fullname, sizeof(fullname))); } END_TEST START_TEST(readname_jump_earlier_jump) { static const u8_t data[] = { /* Some padding needed, not supported to jump to bytes containing dns header */ /* 0x00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08 */ 0x00, 0x00, 0x00, 0x00, 0x03, 0x0b, 0x0a, 0xf2, /* 0x10 */ 0x04, 'c', 'a', 's', 't', 0x00, 0xc0, 0x10, /* 0x18 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x16 }; static const u8_t fullname[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0x18, &domain); pbuf_free(p); fail_unless(offset == sizeof(data)); fail_unless(domain.length == sizeof(fullname)); fail_if(memcmp(&domain.name, fullname, sizeof(fullname))); } END_TEST START_TEST(readname_jump_maxdepth) { static const u8_t data[] = { /* Some padding needed, not supported to jump to bytes containing dns header */ /* 0x00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08 */ 0x00, 0x00, 0x00, 0x00, 0x03, 0x0b, 0x0a, 0xf2, /* 0x10 */ 0x04, 'n', 'a', 'm', 'e', 0xc0, 0x27, 0x03, /* 0x18 */ 0x03, 'd', 'n', 's', 0xc0, 0x10, 0xc0, 0x10, /* 0x20 */ 0x04, 'd', 'e', 'e', 'p', 0xc0, 0x18, 0x00, /* 0x28 */ 0x04, 'c', 'a', 's', 't', 0xc0, 0x20, 0xb0, /* 0x30 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x28 }; static const u8_t fullname[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x04, 'd', 'e', 'e', 'p', 0x03, 'd', 'n', 's', 0x04, 'n', 'a', 'm', 'e', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0x30, &domain); pbuf_free(p); fail_unless(offset == sizeof(data)); fail_unless(domain.length == sizeof(fullname)); fail_if(memcmp(&domain.name, fullname, sizeof(fullname))); } END_TEST START_TEST(readname_jump_later) { static const u8_t data[] = { /* 0x00 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x10, 0x00, 0x01, 0x40, /* 0x10 */ 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xab }; static const u8_t fullname[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == 13); fail_unless(domain.length == sizeof(fullname)); fail_if(memcmp(&domain.name, fullname, sizeof(fullname))); } END_TEST START_TEST(readname_half_jump) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_jump_toolong) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc2, 0x10, 0x00, 0x01, 0x40 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 0, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_jump_loop_label) { static const u8_t data[] = { /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x10 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 10, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(readname_jump_loop_jump) { static const u8_t data[] = { /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x15 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); offset = mdns_readname(p, 10, &domain); pbuf_free(p); fail_unless(offset == MDNS_READNAME_ERROR); } END_TEST START_TEST(add_label_basic) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 }; struct mdns_domain domain; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); fail_unless(domain.length == sizeof(data)); fail_if(memcmp(&domain.name, data, sizeof(data))); } END_TEST START_TEST(add_label_long_label) { static const char *toolong = "abcdefghijklmnopqrstuvwxyz0123456789-abcdefghijklmnopqrstuvwxyz0123456789-abcdefghijklmnopqrstuvwxyz0123456789-"; struct mdns_domain domain; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, toolong, (u8_t)strlen(toolong)); fail_unless(res == ERR_VAL); } END_TEST START_TEST(add_label_full) { static const char *label = "0123456789abcdef0123456789abcdef"; struct mdns_domain domain; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 33); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 66); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 99); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 132); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 165); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 198); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_OK); fail_unless(domain.length == 231); res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label)); fail_unless(res == ERR_VAL); fail_unless(domain.length == 231); res = mdns_domain_add_label(&domain, label, 25); fail_unless(res == ERR_VAL); fail_unless(domain.length == 231); res = mdns_domain_add_label(&domain, label, 24); fail_unless(res == ERR_VAL); fail_unless(domain.length == 231); res = mdns_domain_add_label(&domain, label, 23); fail_unless(res == ERR_OK); fail_unless(domain.length == 255); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); fail_unless(domain.length == 256); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_VAL); fail_unless(domain.length == 256); } END_TEST START_TEST(domain_eq_basic) { static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 }; struct mdns_domain domain1, domain2; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain1, 0, sizeof(domain1)); res = mdns_domain_add_label(&domain1, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, NULL, 0); fail_unless(res == ERR_OK); fail_unless(domain1.length == sizeof(data)); memset(&domain2, 0, sizeof(domain2)); res = mdns_domain_add_label(&domain2, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, NULL, 0); fail_unless(res == ERR_OK); fail_unless(mdns_domain_eq(&domain1, &domain2)); } END_TEST START_TEST(domain_eq_diff) { struct mdns_domain domain1, domain2; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain1, 0, sizeof(domain1)); res = mdns_domain_add_label(&domain1, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, "base", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, NULL, 0); fail_unless(res == ERR_OK); memset(&domain2, 0, sizeof(domain2)); res = mdns_domain_add_label(&domain2, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, NULL, 0); fail_unless(res == ERR_OK); fail_if(mdns_domain_eq(&domain1, &domain2)); } END_TEST START_TEST(domain_eq_case) { struct mdns_domain domain1, domain2; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain1, 0, sizeof(domain1)); res = mdns_domain_add_label(&domain1, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, NULL, 0); fail_unless(res == ERR_OK); memset(&domain2, 0, sizeof(domain2)); res = mdns_domain_add_label(&domain2, "MulTI", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, "casT", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, NULL, 0); fail_unless(res == ERR_OK); fail_unless(mdns_domain_eq(&domain1, &domain2)); } END_TEST START_TEST(domain_eq_anydata) { static const u8_t data1[] = { 0x05, 0xcc, 0xdc, 0x00, 0xa0 }; static const u8_t data2[] = { 0x7f, 0x8c, 0x01, 0xff, 0xcf }; struct mdns_domain domain1, domain2; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain1, 0, sizeof(domain1)); res = mdns_domain_add_label(&domain1, (const char*)data1, sizeof(data1)); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, "cast", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, (const char*)data2, sizeof(data2)); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, NULL, 0); fail_unless(res == ERR_OK); memset(&domain2, 0, sizeof(domain2)); res = mdns_domain_add_label(&domain2, (const char*)data1, sizeof(data1)); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, "casT", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, (const char*)data2, sizeof(data2)); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, NULL, 0); fail_unless(res == ERR_OK); fail_unless(mdns_domain_eq(&domain1, &domain2)); } END_TEST START_TEST(domain_eq_length) { struct mdns_domain domain1, domain2; err_t res; LWIP_UNUSED_ARG(_i); memset(&domain1, 0, sizeof(domain1)); memset(domain1.name, 0xAA, sizeof(MDNS_DOMAIN_MAXLEN)); res = mdns_domain_add_label(&domain1, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain1, "cast", 4); fail_unless(res == ERR_OK); memset(&domain2, 0, sizeof(domain2)); memset(domain2.name, 0xBB, sizeof(MDNS_DOMAIN_MAXLEN)); res = mdns_domain_add_label(&domain2, "multi", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain2, "cast", 4); fail_unless(res == ERR_OK); fail_unless(mdns_domain_eq(&domain1, &domain2)); } END_TEST START_TEST(compress_full_match) { static const u8_t data[] = { 0x00, 0x00, 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); /* Write 0 bytes, then a jump to addr 2 */ fail_unless(length == 0); fail_unless(offset == 2); pbuf_free(p); } END_TEST START_TEST(compress_full_match_subset) { static const u8_t data[] = { 0x00, 0x00, 0x02, 'g', 'o', 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); /* Write 0 bytes, then a jump to addr 5 */ fail_unless(length == 0); fail_unless(offset == 5); pbuf_free(p); } END_TEST START_TEST(compress_full_match_jump) { static const u8_t data[] = { /* 0x00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x10 */ 0x04, 'l', 'w', 'i', 'p', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xc0, 0x00, 0x02, 0x00, /* 0x20 */ 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0xc0, 0x15 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 0x20; length = mdns_compress_domain(p, &offset, &domain); /* Write 0 bytes, then a jump to addr 0x20 */ fail_unless(length == 0); fail_unless(offset == 0x20); pbuf_free(p); } END_TEST START_TEST(compress_no_match) { static const u8_t data[] = { 0x00, 0x00, 0x04, 'l', 'w', 'i', 'p', 0x05, 'w', 'i', 'k', 'i', 'a', 0x03, 'c', 'o', 'm', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); /* Write all bytes, no jump */ fail_unless(length == domain.length); pbuf_free(p); } END_TEST START_TEST(compress_2nd_label) { static const u8_t data[] = { 0x00, 0x00, 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "lwip", 4); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); /* Write 5 bytes, then a jump to addr 9 */ fail_unless(length == 5); fail_unless(offset == 9); pbuf_free(p); } END_TEST START_TEST(compress_2nd_label_short) { static const u8_t data[] = { 0x00, 0x00, 0x04, 'l', 'w', 'i', 'p', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); /* Write 5 bytes, then a jump to addr 7 */ fail_unless(length == 7); fail_unless(offset == 7); pbuf_free(p); } END_TEST START_TEST(compress_jump_to_jump) { static const u8_t data[] = { /* 0x00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x10 */ 0x04, 'l', 'w', 'i', 'p', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xc0, 0x00, 0x02, 0x00, /* 0x20 */ 0x07, 'b', 'a', 'n', 'a', 'n', 'a', 's', 0xc0, 0x15 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 0x20; length = mdns_compress_domain(p, &offset, &domain); /* Dont compress if jump would be to a jump */ fail_unless(length == domain.length); offset = 0x10; length = mdns_compress_domain(p, &offset, &domain); /* Write 7 bytes, then a jump to addr 0x15 */ fail_unless(length == 7); fail_unless(offset == 0x15); pbuf_free(p); } END_TEST START_TEST(compress_long_match) { static const u8_t data[] = { 0x00, 0x00, 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0x05, 'l', 'o', 'c', 'a', 'l', 0x03, 'c', 'o', 'm', 0x00 }; struct pbuf *p; struct mdns_domain domain; u16_t offset; u16_t length; err_t res; LWIP_UNUSED_ARG(_i); p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM); p->payload = (void *)(size_t)data; fail_if(p == NULL); memset(&domain, 0, sizeof(domain)); res = mdns_domain_add_label(&domain, "foobar", 6); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, "local", 5); fail_unless(res == ERR_OK); res = mdns_domain_add_label(&domain, NULL, 0); fail_unless(res == ERR_OK); offset = 2; length = mdns_compress_domain(p, &offset, &domain); fail_unless(length == domain.length); pbuf_free(p); } END_TEST Suite* mdns_suite(void) { testfunc tests[] = { TESTFUNC(readname_basic), TESTFUNC(readname_anydata), TESTFUNC(readname_short_buf), TESTFUNC(readname_long_label), TESTFUNC(readname_overflow), TESTFUNC(readname_jump_earlier), TESTFUNC(readname_jump_earlier_jump), TESTFUNC(readname_jump_maxdepth), TESTFUNC(readname_jump_later), TESTFUNC(readname_half_jump), TESTFUNC(readname_jump_toolong), TESTFUNC(readname_jump_loop_label), TESTFUNC(readname_jump_loop_jump), TESTFUNC(add_label_basic), TESTFUNC(add_label_long_label), TESTFUNC(add_label_full), TESTFUNC(domain_eq_basic), TESTFUNC(domain_eq_diff), TESTFUNC(domain_eq_case), TESTFUNC(domain_eq_anydata), TESTFUNC(domain_eq_length), TESTFUNC(compress_full_match), TESTFUNC(compress_full_match_subset), TESTFUNC(compress_full_match_jump), TESTFUNC(compress_no_match), TESTFUNC(compress_2nd_label), TESTFUNC(compress_2nd_label_short), TESTFUNC(compress_jump_to_jump), TESTFUNC(compress_long_match), }; return create_suite("MDNS", tests, sizeof(tests)/sizeof(testfunc), NULL, NULL); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/mdns/test_mdns.c
C
unknown
29,422
#ifndef LWIP_HDR_TEST_MDNS_H__ #define LWIP_HDR_TEST_MDNS_H__ #include "../lwip_check.h" Suite* mdns_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/mdns/test_mdns.h
C
unknown
132
#include "tcp_helper.h" #include "lwip/priv/tcp_priv.h" #include "lwip/stats.h" #include "lwip/pbuf.h" #include "lwip/inet_chksum.h" #include "lwip/ip_addr.h" #if !LWIP_STATS || !TCP_STATS || !MEMP_STATS #error "This tests needs TCP- and MEMP-statistics enabled" #endif /** Remove all pcbs on the given list. */ static void tcp_remove(struct tcp_pcb* pcb_list) { struct tcp_pcb *pcb = pcb_list; struct tcp_pcb *pcb2; while(pcb != NULL) { pcb2 = pcb; pcb = pcb->next; tcp_abort(pcb2); } } /** Remove all pcbs on listen-, active- and time-wait-list (bound- isn't exported). */ void tcp_remove_all(void) { tcp_remove(tcp_listen_pcbs.pcbs); tcp_remove(tcp_active_pcbs); tcp_remove(tcp_tw_pcbs); fail_unless(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); fail_unless(MEMP_STATS_GET(used, MEMP_TCP_PCB_LISTEN) == 0); fail_unless(MEMP_STATS_GET(used, MEMP_TCP_SEG) == 0); fail_unless(MEMP_STATS_GET(used, MEMP_PBUF_POOL) == 0); } /** Create a TCP segment usable for passing to tcp_input */ static struct pbuf* tcp_create_segment_wnd(ip_addr_t* src_ip, ip_addr_t* dst_ip, u16_t src_port, u16_t dst_port, void* data, size_t data_len, u32_t seqno, u32_t ackno, u8_t headerflags, u16_t wnd) { struct pbuf *p, *q; struct ip_hdr* iphdr; struct tcp_hdr* tcphdr; u16_t pbuf_len = (u16_t)(sizeof(struct ip_hdr) + sizeof(struct tcp_hdr) + data_len); LWIP_ASSERT("data_len too big", data_len <= 0xFFFF); p = pbuf_alloc(PBUF_RAW, pbuf_len, PBUF_POOL); EXPECT_RETNULL(p != NULL); /* first pbuf must be big enough to hold the headers */ EXPECT_RETNULL(p->len >= (sizeof(struct ip_hdr) + sizeof(struct tcp_hdr))); if (data_len > 0) { /* first pbuf must be big enough to hold at least 1 data byte, too */ EXPECT_RETNULL(p->len > (sizeof(struct ip_hdr) + sizeof(struct tcp_hdr))); } for(q = p; q != NULL; q = q->next) { memset(q->payload, 0, q->len); } iphdr = (struct ip_hdr*)p->payload; /* fill IP header */ iphdr->dest.addr = ip_2_ip4(dst_ip)->addr; iphdr->src.addr = ip_2_ip4(src_ip)->addr; IPH_VHL_SET(iphdr, 4, IP_HLEN / 4); IPH_TOS_SET(iphdr, 0); IPH_LEN_SET(iphdr, htons(p->tot_len)); IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN)); /* let p point to TCP header */ pbuf_header(p, -(s16_t)sizeof(struct ip_hdr)); tcphdr = (struct tcp_hdr*)p->payload; tcphdr->src = htons(src_port); tcphdr->dest = htons(dst_port); tcphdr->seqno = htonl(seqno); tcphdr->ackno = htonl(ackno); TCPH_HDRLEN_SET(tcphdr, sizeof(struct tcp_hdr)/4); TCPH_FLAGS_SET(tcphdr, headerflags); tcphdr->wnd = htons(wnd); if (data_len > 0) { /* let p point to TCP data */ pbuf_header(p, -(s16_t)sizeof(struct tcp_hdr)); /* copy data */ pbuf_take(p, data, (u16_t)data_len); /* let p point to TCP header again */ pbuf_header(p, sizeof(struct tcp_hdr)); } /* calculate checksum */ tcphdr->chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len, src_ip, dst_ip); pbuf_header(p, sizeof(struct ip_hdr)); return p; } /** Create a TCP segment usable for passing to tcp_input */ struct pbuf* tcp_create_segment(ip_addr_t* src_ip, ip_addr_t* dst_ip, u16_t src_port, u16_t dst_port, void* data, size_t data_len, u32_t seqno, u32_t ackno, u8_t headerflags) { return tcp_create_segment_wnd(src_ip, dst_ip, src_port, dst_port, data, data_len, seqno, ackno, headerflags, TCP_WND); } /** Create a TCP segment usable for passing to tcp_input * - IP-addresses, ports, seqno and ackno are taken from pcb * - seqno and ackno can be altered with an offset */ struct pbuf* tcp_create_rx_segment(struct tcp_pcb* pcb, void* data, size_t data_len, u32_t seqno_offset, u32_t ackno_offset, u8_t headerflags) { return tcp_create_segment(&pcb->remote_ip, &pcb->local_ip, pcb->remote_port, pcb->local_port, data, data_len, pcb->rcv_nxt + seqno_offset, pcb->lastack + ackno_offset, headerflags); } /** Create a TCP segment usable for passing to tcp_input * - IP-addresses, ports, seqno and ackno are taken from pcb * - seqno and ackno can be altered with an offset * - TCP window can be adjusted */ struct pbuf* tcp_create_rx_segment_wnd(struct tcp_pcb* pcb, void* data, size_t data_len, u32_t seqno_offset, u32_t ackno_offset, u8_t headerflags, u16_t wnd) { return tcp_create_segment_wnd(&pcb->remote_ip, &pcb->local_ip, pcb->remote_port, pcb->local_port, data, data_len, pcb->rcv_nxt + seqno_offset, pcb->lastack + ackno_offset, headerflags, wnd); } /** Safely bring a tcp_pcb into the requested state */ void tcp_set_state(struct tcp_pcb* pcb, enum tcp_state state, ip_addr_t* local_ip, ip_addr_t* remote_ip, u16_t local_port, u16_t remote_port) { u32_t iss; /* @todo: are these all states? */ /* @todo: remove from previous list */ pcb->state = state; iss = tcp_next_iss(pcb); pcb->snd_wl2 = iss; pcb->snd_nxt = iss; pcb->lastack = iss; pcb->snd_lbb = iss; if (state == ESTABLISHED) { TCP_REG(&tcp_active_pcbs, pcb); ip_addr_copy(pcb->local_ip, *local_ip); pcb->local_port = local_port; ip_addr_copy(pcb->remote_ip, *remote_ip); pcb->remote_port = remote_port; } else if(state == LISTEN) { TCP_REG(&tcp_listen_pcbs.pcbs, pcb); ip_addr_copy(pcb->local_ip, *local_ip); pcb->local_port = local_port; } else if(state == TIME_WAIT) { TCP_REG(&tcp_tw_pcbs, pcb); ip_addr_copy(pcb->local_ip, *local_ip); pcb->local_port = local_port; ip_addr_copy(pcb->remote_ip, *remote_ip); pcb->remote_port = remote_port; } else { fail(); } } void test_tcp_counters_err(void* arg, err_t err) { struct test_tcp_counters* counters = (struct test_tcp_counters*)arg; EXPECT_RET(arg != NULL); counters->err_calls++; counters->last_err = err; } static void test_tcp_counters_check_rxdata(struct test_tcp_counters* counters, struct pbuf* p) { struct pbuf* q; u32_t i, received; if(counters->expected_data == NULL) { /* no data to compare */ return; } EXPECT_RET(counters->recved_bytes + p->tot_len <= counters->expected_data_len); received = counters->recved_bytes; for(q = p; q != NULL; q = q->next) { char *data = (char*)q->payload; for(i = 0; i < q->len; i++) { EXPECT_RET(data[i] == counters->expected_data[received]); received++; } } EXPECT(received == counters->recved_bytes + p->tot_len); } err_t test_tcp_counters_recv(void* arg, struct tcp_pcb* pcb, struct pbuf* p, err_t err) { struct test_tcp_counters* counters = (struct test_tcp_counters*)arg; EXPECT_RETX(arg != NULL, ERR_OK); EXPECT_RETX(pcb != NULL, ERR_OK); EXPECT_RETX(err == ERR_OK, ERR_OK); if (p != NULL) { if (counters->close_calls == 0) { counters->recv_calls++; test_tcp_counters_check_rxdata(counters, p); counters->recved_bytes += p->tot_len; } else { counters->recv_calls_after_close++; counters->recved_bytes_after_close += p->tot_len; } pbuf_free(p); } else { counters->close_calls++; } EXPECT(counters->recv_calls_after_close == 0 && counters->recved_bytes_after_close == 0); return ERR_OK; } /** Allocate a pcb and set up the test_tcp_counters_* callbacks */ struct tcp_pcb* test_tcp_new_counters_pcb(struct test_tcp_counters* counters) { struct tcp_pcb* pcb = tcp_new(); if (pcb != NULL) { /* set up args and callbacks */ tcp_arg(pcb, counters); tcp_recv(pcb, test_tcp_counters_recv); tcp_err(pcb, test_tcp_counters_err); pcb->snd_wnd = TCP_WND; pcb->snd_wnd_max = TCP_WND; } return pcb; } /** Calls tcp_input() after adjusting current_iphdr_dest */ void test_tcp_input(struct pbuf *p, struct netif *inp) { struct ip_hdr *iphdr = (struct ip_hdr*)p->payload; /* these lines are a hack, don't use them as an example :-) */ ip_addr_copy_from_ip4(*ip_current_dest_addr(), iphdr->dest); ip_addr_copy_from_ip4(*ip_current_src_addr(), iphdr->src); ip_current_netif() = inp; ip_data.current_ip4_header = iphdr; /* since adding IPv6, p->payload must point to tcp header, not ip header */ pbuf_header(p, -(s16_t)sizeof(struct ip_hdr)); tcp_input(p, inp); ip_addr_set_zero(ip_current_dest_addr()); ip_addr_set_zero(ip_current_src_addr()); ip_current_netif() = NULL; ip_data.current_ip4_header = NULL; } static err_t test_tcp_netif_output(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr) { struct test_tcp_txcounters *txcounters = (struct test_tcp_txcounters*)netif->state; LWIP_UNUSED_ARG(ipaddr); if (txcounters != NULL) { txcounters->num_tx_calls++; txcounters->num_tx_bytes += p->tot_len; if (txcounters->copy_tx_packets) { struct pbuf *p_copy = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM); err_t err; EXPECT(p_copy != NULL); err = pbuf_copy(p_copy, p); EXPECT(err == ERR_OK); if (txcounters->tx_packets == NULL) { txcounters->tx_packets = p_copy; } else { pbuf_cat(txcounters->tx_packets, p_copy); } } } return ERR_OK; } void test_tcp_init_netif(struct netif *netif, struct test_tcp_txcounters *txcounters, ip_addr_t *ip_addr, ip_addr_t *netmask) { struct netif *n; memset(netif, 0, sizeof(struct netif)); if (txcounters != NULL) { memset(txcounters, 0, sizeof(struct test_tcp_txcounters)); netif->state = txcounters; } netif->output = test_tcp_netif_output; netif->flags |= NETIF_FLAG_UP | NETIF_FLAG_LINK_UP; ip_addr_copy_from_ip4(netif->netmask, *ip_2_ip4(netmask)); ip_addr_copy_from_ip4(netif->ip_addr, *ip_2_ip4(ip_addr)); for (n = netif_list; n != NULL; n = n->next) { if (n == netif) { return; } } netif->next = NULL; netif_list = netif; }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/tcp_helper.c
C
unknown
10,139
#ifndef LWIP_HDR_TCP_HELPER_H #define LWIP_HDR_TCP_HELPER_H #include "../lwip_check.h" #include "lwip/arch.h" #include "lwip/tcp.h" #include "lwip/netif.h" /* counters used for test_tcp_counters_* callback functions */ struct test_tcp_counters { u32_t recv_calls; u32_t recved_bytes; u32_t recv_calls_after_close; u32_t recved_bytes_after_close; u32_t close_calls; u32_t err_calls; err_t last_err; char* expected_data; u32_t expected_data_len; }; struct test_tcp_txcounters { u32_t num_tx_calls; u32_t num_tx_bytes; u8_t copy_tx_packets; struct pbuf *tx_packets; }; /* Helper functions */ void tcp_remove_all(void); struct pbuf* tcp_create_segment(ip_addr_t* src_ip, ip_addr_t* dst_ip, u16_t src_port, u16_t dst_port, void* data, size_t data_len, u32_t seqno, u32_t ackno, u8_t headerflags); struct pbuf* tcp_create_rx_segment(struct tcp_pcb* pcb, void* data, size_t data_len, u32_t seqno_offset, u32_t ackno_offset, u8_t headerflags); struct pbuf* tcp_create_rx_segment_wnd(struct tcp_pcb* pcb, void* data, size_t data_len, u32_t seqno_offset, u32_t ackno_offset, u8_t headerflags, u16_t wnd); void tcp_set_state(struct tcp_pcb* pcb, enum tcp_state state, ip_addr_t* local_ip, ip_addr_t* remote_ip, u16_t local_port, u16_t remote_port); void test_tcp_counters_err(void* arg, err_t err); err_t test_tcp_counters_recv(void* arg, struct tcp_pcb* pcb, struct pbuf* p, err_t err); struct tcp_pcb* test_tcp_new_counters_pcb(struct test_tcp_counters* counters); void test_tcp_input(struct pbuf *p, struct netif *inp); void test_tcp_init_netif(struct netif *netif, struct test_tcp_txcounters *txcounters, ip_addr_t *ip_addr, ip_addr_t *netmask); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/tcp_helper.h
C
unknown
1,855
#include "test_tcp.h" #include "lwip/priv/tcp_priv.h" #include "lwip/stats.h" #include "tcp_helper.h" #include "lwip/inet_chksum.h" #ifdef _MSC_VER #pragma warning(disable: 4307) /* we explicitly wrap around TCP seqnos */ #endif #if !LWIP_STATS || !TCP_STATS || !MEMP_STATS #error "This tests needs TCP- and MEMP-statistics enabled" #endif #if TCP_SND_BUF <= TCP_WND #error "This tests needs TCP_SND_BUF to be > TCP_WND" #endif static u8_t test_tcp_timer; /* our own version of tcp_tmr so we can reset fast/slow timer state */ static void test_tcp_tmr(void) { tcp_fasttmr(); if (++test_tcp_timer & 1) { tcp_slowtmr(); } } /* Setups/teardown functions */ static void tcp_setup(void) { /* reset iss to default (6510) */ tcp_ticks = 0; tcp_ticks = 0 - (tcp_next_iss(NULL) - 6510); tcp_next_iss(NULL); tcp_ticks = 0; test_tcp_timer = 0; tcp_remove_all(); } static void tcp_teardown(void) { netif_list = NULL; netif_default = NULL; tcp_remove_all(); } /* Test functions */ /** Call tcp_new() and tcp_abort() and test memp stats */ START_TEST(test_tcp_new_abort) { struct tcp_pcb* pcb; LWIP_UNUSED_ARG(_i); fail_unless(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); pcb = tcp_new(); fail_unless(pcb != NULL); if (pcb != NULL) { fail_unless(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); fail_unless(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } } END_TEST /** Create an ESTABLISHED pcb and check if receive callback is called */ START_TEST(test_tcp_recv_inseq) { struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf* p; char data[] = {1, 2, 3, 4}; ip_addr_t remote_ip, local_ip, netmask; u16_t data_len; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; struct test_tcp_txcounters txcounters; LWIP_UNUSED_ARG(_i); /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); data_len = sizeof(data); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = data_len; counters.expected_data = data; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); /* create a segment */ p = tcp_create_rx_segment(pcb, counters.expected_data, data_len, 0, 0, 0); EXPECT(p != NULL); if (p != NULL) { /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 1); EXPECT(counters.recved_bytes == data_len); EXPECT(counters.err_calls == 0); } /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST /** Check that we handle malformed tcp headers, and discard the pbuf(s) */ START_TEST(test_tcp_malformed_header) { struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf* p; char data[] = {1, 2, 3, 4}; ip_addr_t remote_ip, local_ip, netmask; u16_t data_len, chksum; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; struct test_tcp_txcounters txcounters; struct tcp_hdr *hdr; LWIP_UNUSED_ARG(_i); /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); data_len = sizeof(data); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = data_len; counters.expected_data = data; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); /* create a segment */ p = tcp_create_rx_segment(pcb, counters.expected_data, data_len, 0, 0, 0); pbuf_header(p, -(s16_t)sizeof(struct ip_hdr)); hdr = (struct tcp_hdr *)p->payload; TCPH_HDRLEN_FLAGS_SET(hdr, 15, 0x3d1); hdr->chksum = 0; chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len, &remote_ip, &local_ip); hdr->chksum = chksum; pbuf_header(p, sizeof(struct ip_hdr)); EXPECT(p != NULL); EXPECT(p->next == NULL); if (p != NULL) { /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); } /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST /** Provoke fast retransmission by duplicate ACKs and then recover by ACKing all sent data. * At the end, send more data. */ START_TEST(test_tcp_fast_retx_recover) { struct netif netif; struct test_tcp_txcounters txcounters; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf* p; char data1[] = { 1, 2, 3, 4}; char data2[] = { 5, 6, 7, 8}; char data3[] = { 9, 10, 11, 12}; char data4[] = {13, 14, 15, 16}; char data5[] = {17, 18, 19, 20}; char data6[TCP_MSS] = {21, 22, 23, 24}; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; err_t err; LWIP_UNUSED_ARG(_i); /* initialize local vars */ IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); memset(&counters, 0, sizeof(counters)); /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->mss = TCP_MSS; /* disable initial congestion window (we don't send a SYN here...) */ pcb->cwnd = pcb->snd_wnd; /* send data1 */ err = tcp_write(pcb, data1, sizeof(data1), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT_RET(txcounters.num_tx_calls == 1); EXPECT_RET(txcounters.num_tx_bytes == sizeof(data1) + sizeof(struct tcp_hdr) + sizeof(struct ip_hdr)); memset(&txcounters, 0, sizeof(txcounters)); /* "recv" ACK for data1 */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 4, TCP_ACK); EXPECT_RET(p != NULL); test_tcp_input(p, &netif); EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(pcb->unacked == NULL); /* send data2 */ err = tcp_write(pcb, data2, sizeof(data2), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT_RET(txcounters.num_tx_calls == 1); EXPECT_RET(txcounters.num_tx_bytes == sizeof(data2) + sizeof(struct tcp_hdr) + sizeof(struct ip_hdr)); memset(&txcounters, 0, sizeof(txcounters)); /* duplicate ACK for data1 (data2 is lost) */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); EXPECT_RET(p != NULL); test_tcp_input(p, &netif); EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(pcb->dupacks == 1); /* send data3 */ err = tcp_write(pcb, data3, sizeof(data3), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* nagle enabled, no tx calls */ EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(txcounters.num_tx_bytes == 0); memset(&txcounters, 0, sizeof(txcounters)); /* 2nd duplicate ACK for data1 (data2 and data3 are lost) */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); EXPECT_RET(p != NULL); test_tcp_input(p, &netif); EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(pcb->dupacks == 2); /* queue data4, don't send it (unsent-oversize is != 0) */ err = tcp_write(pcb, data4, sizeof(data4), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); /* 3nd duplicate ACK for data1 (data2 and data3 are lost) -> fast retransmission */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); EXPECT_RET(p != NULL); test_tcp_input(p, &netif); /*EXPECT_RET(txcounters.num_tx_calls == 1);*/ EXPECT_RET(pcb->dupacks == 3); memset(&txcounters, 0, sizeof(txcounters)); /* @todo: check expected data?*/ /* send data5, not output yet */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); /*err = tcp_output(pcb); EXPECT_RET(err == ERR_OK);*/ EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(txcounters.num_tx_bytes == 0); memset(&txcounters, 0, sizeof(txcounters)); { int i = 0; do { err = tcp_write(pcb, data6, TCP_MSS, TCP_WRITE_FLAG_COPY); i++; }while(err == ERR_OK); EXPECT_RET(err != ERR_OK); } err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /*EXPECT_RET(txcounters.num_tx_calls == 0); EXPECT_RET(txcounters.num_tx_bytes == 0);*/ memset(&txcounters, 0, sizeof(txcounters)); /* send even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* ...and even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* ...and even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* ...and even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* send ACKs for data2 and data3 */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 12, TCP_ACK); EXPECT_RET(p != NULL); test_tcp_input(p, &netif); /*EXPECT_RET(txcounters.num_tx_calls == 0);*/ /* ...and even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); /* ...and even more data */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); #if 0 /* create expected segment */ p1 = tcp_create_rx_segment(pcb, counters.expected_data, data_len, 0, 0, 0); EXPECT_RET(p != NULL); if (p != NULL) { /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT_RET(counters.close_calls == 0); EXPECT_RET(counters.recv_calls == 1); EXPECT_RET(counters.recved_bytes == data_len); EXPECT_RET(counters.err_calls == 0); } #endif /* make sure the pcb is freed */ EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST static u8_t tx_data[TCP_WND*2]; static void check_seqnos(struct tcp_seg *segs, int num_expected, u32_t *seqnos_expected) { struct tcp_seg *s = segs; int i; for (i = 0; i < num_expected; i++, s = s->next) { EXPECT_RET(s != NULL); EXPECT(s->tcphdr->seqno == htonl(seqnos_expected[i])); } EXPECT(s == NULL); } /** Send data with sequence numbers that wrap around the u32_t range. * Then, provoke fast retransmission by duplicate ACKs and check that all * segment lists are still properly sorted. */ START_TEST(test_tcp_fast_rexmit_wraparound) { struct netif netif; struct test_tcp_txcounters txcounters; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf* p; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; err_t err; #define SEQNO1 (0xFFFFFF00 - TCP_MSS) #define ISS 6510 u16_t i, sent_total = 0; u32_t seqnos[] = { SEQNO1, SEQNO1 + (1 * TCP_MSS), SEQNO1 + (2 * TCP_MSS), SEQNO1 + (3 * TCP_MSS), SEQNO1 + (4 * TCP_MSS), SEQNO1 + (5 * TCP_MSS)}; LWIP_UNUSED_ARG(_i); for (i = 0; i < sizeof(tx_data); i++) { tx_data[i] = (u8_t)i; } /* initialize local vars */ IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); memset(&counters, 0, sizeof(counters)); /* create and initialize the pcb */ tcp_ticks = SEQNO1 - ISS; pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->mss = TCP_MSS; /* disable initial congestion window (we don't send a SYN here...) */ pcb->cwnd = 2*TCP_MSS; /* start in congestion advoidance */ pcb->ssthresh = pcb->cwnd; /* send 6 mss-sized segments */ for (i = 0; i < 6; i++) { err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); sent_total += TCP_MSS; } check_seqnos(pcb->unsent, 6, seqnos); EXPECT(pcb->unacked == NULL); err = tcp_output(pcb); EXPECT(txcounters.num_tx_calls == 2); EXPECT(txcounters.num_tx_bytes == 2 * (TCP_MSS + 40U)); memset(&txcounters, 0, sizeof(txcounters)); check_seqnos(pcb->unacked, 2, seqnos); check_seqnos(pcb->unsent, 4, &seqnos[2]); /* ACK the first segment */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, TCP_MSS, TCP_ACK); test_tcp_input(p, &netif); /* ensure this didn't trigger a retransmission. Only one segment should be transmitted because cwnd opened up by TCP_MSS and a fraction since we are in congestion avoidance */ EXPECT(txcounters.num_tx_calls == 1); EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U); memset(&txcounters, 0, sizeof(txcounters)); check_seqnos(pcb->unacked, 2, &seqnos[1]); check_seqnos(pcb->unsent, 3, &seqnos[3]); /* 3 dupacks */ EXPECT(pcb->dupacks == 0); p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); test_tcp_input(p, &netif); EXPECT(txcounters.num_tx_calls == 0); EXPECT(pcb->dupacks == 1); p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); test_tcp_input(p, &netif); EXPECT(txcounters.num_tx_calls == 0); EXPECT(pcb->dupacks == 2); /* 3rd dupack -> fast rexmit */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); test_tcp_input(p, &netif); EXPECT(pcb->dupacks == 3); EXPECT(txcounters.num_tx_calls == 4); memset(&txcounters, 0, sizeof(txcounters)); EXPECT(pcb->unsent == NULL); check_seqnos(pcb->unacked, 5, &seqnos[1]); /* make sure the pcb is freed */ EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST /** Send data with sequence numbers that wrap around the u32_t range. * Then, provoke RTO retransmission and check that all * segment lists are still properly sorted. */ START_TEST(test_tcp_rto_rexmit_wraparound) { struct netif netif; struct test_tcp_txcounters txcounters; struct test_tcp_counters counters; struct tcp_pcb* pcb; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; err_t err; #define SEQNO1 (0xFFFFFF00 - TCP_MSS) #define ISS 6510 u16_t i, sent_total = 0; u32_t seqnos[] = { SEQNO1, SEQNO1 + (1 * TCP_MSS), SEQNO1 + (2 * TCP_MSS), SEQNO1 + (3 * TCP_MSS), SEQNO1 + (4 * TCP_MSS), SEQNO1 + (5 * TCP_MSS)}; LWIP_UNUSED_ARG(_i); for (i = 0; i < sizeof(tx_data); i++) { tx_data[i] = (u8_t)i; } /* initialize local vars */ IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); memset(&counters, 0, sizeof(counters)); /* create and initialize the pcb */ tcp_ticks = 0; tcp_ticks = 0 - tcp_next_iss(NULL); tcp_ticks = SEQNO1 - tcp_next_iss(NULL); pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->mss = TCP_MSS; /* disable initial congestion window (we don't send a SYN here...) */ pcb->cwnd = 2*TCP_MSS; /* send 6 mss-sized segments */ for (i = 0; i < 6; i++) { err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); sent_total += TCP_MSS; } check_seqnos(pcb->unsent, 6, seqnos); EXPECT(pcb->unacked == NULL); err = tcp_output(pcb); EXPECT(txcounters.num_tx_calls == 2); EXPECT(txcounters.num_tx_bytes == 2 * (TCP_MSS + 40U)); memset(&txcounters, 0, sizeof(txcounters)); check_seqnos(pcb->unacked, 2, seqnos); check_seqnos(pcb->unsent, 4, &seqnos[2]); /* call the tcp timer some times */ for (i = 0; i < 10; i++) { test_tcp_tmr(); EXPECT(txcounters.num_tx_calls == 0); } /* 11th call to tcp_tmr: RTO rexmit fires */ test_tcp_tmr(); EXPECT(txcounters.num_tx_calls == 1); check_seqnos(pcb->unacked, 1, seqnos); check_seqnos(pcb->unsent, 5, &seqnos[1]); /* fake greater cwnd */ pcb->cwnd = pcb->snd_wnd; /* send more data */ err = tcp_output(pcb); EXPECT(err == ERR_OK); /* check queues are sorted */ EXPECT(pcb->unsent == NULL); check_seqnos(pcb->unacked, 6, seqnos); /* make sure the pcb is freed */ EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST /** Provoke fast retransmission by duplicate ACKs and then recover by ACKing all sent data. * At the end, send more data. */ static void test_tcp_tx_full_window_lost(u8_t zero_window_probe_from_unsent) { struct netif netif; struct test_tcp_txcounters txcounters; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; err_t err; u16_t sent_total, i; u8_t expected = 0xFE; for (i = 0; i < sizeof(tx_data); i++) { u8_t d = (u8_t)i; if (d == 0xFE) { d = 0xF0; } tx_data[i] = d; } if (zero_window_probe_from_unsent) { tx_data[TCP_WND] = expected; } else { tx_data[0] = expected; } /* initialize local vars */ IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask); memset(&counters, 0, sizeof(counters)); memset(&txcounters, 0, sizeof(txcounters)); /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->mss = TCP_MSS; /* disable initial congestion window (we don't send a SYN here...) */ pcb->cwnd = pcb->snd_wnd; /* send a full window (minus 1 packets) of TCP data in MSS-sized chunks */ sent_total = 0; if ((TCP_WND - TCP_MSS) % TCP_MSS != 0) { u16_t initial_data_len = (TCP_WND - TCP_MSS) % TCP_MSS; err = tcp_write(pcb, &tx_data[sent_total], initial_data_len, TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT(txcounters.num_tx_calls == 1); EXPECT(txcounters.num_tx_bytes == initial_data_len + 40U); memset(&txcounters, 0, sizeof(txcounters)); sent_total += initial_data_len; } for (; sent_total < (TCP_WND - TCP_MSS); sent_total += TCP_MSS) { err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT(txcounters.num_tx_calls == 1); EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U); memset(&txcounters, 0, sizeof(txcounters)); } EXPECT(sent_total == (TCP_WND - TCP_MSS)); /* now ACK the packet before the first */ p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK); test_tcp_input(p, &netif); /* ensure this didn't trigger a retransmission */ EXPECT(txcounters.num_tx_calls == 0); EXPECT(txcounters.num_tx_bytes == 0); EXPECT(pcb->persist_backoff == 0); /* send the last packet, now a complete window has been sent */ err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY); sent_total += TCP_MSS; EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT(txcounters.num_tx_calls == 1); EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U); memset(&txcounters, 0, sizeof(txcounters)); EXPECT(pcb->persist_backoff == 0); if (zero_window_probe_from_unsent) { /* ACK all data but close the TX window */ p = tcp_create_rx_segment_wnd(pcb, NULL, 0, 0, TCP_WND, TCP_ACK, 0); test_tcp_input(p, &netif); /* ensure this didn't trigger any transmission */ EXPECT(txcounters.num_tx_calls == 0); EXPECT(txcounters.num_tx_bytes == 0); EXPECT(pcb->persist_backoff == 1); } /* send one byte more (out of window) -> persist timer starts */ err = tcp_write(pcb, &tx_data[sent_total], 1, TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); err = tcp_output(pcb); EXPECT_RET(err == ERR_OK); EXPECT(txcounters.num_tx_calls == 0); EXPECT(txcounters.num_tx_bytes == 0); memset(&txcounters, 0, sizeof(txcounters)); if (!zero_window_probe_from_unsent) { /* no persist timer unless a zero window announcement has been received */ EXPECT(pcb->persist_backoff == 0); } else { EXPECT(pcb->persist_backoff == 1); /* call tcp_timer some more times to let persist timer count up */ for (i = 0; i < 4; i++) { test_tcp_tmr(); EXPECT(txcounters.num_tx_calls == 0); EXPECT(txcounters.num_tx_bytes == 0); } /* this should trigger the zero-window-probe */ txcounters.copy_tx_packets = 1; test_tcp_tmr(); txcounters.copy_tx_packets = 0; EXPECT(txcounters.num_tx_calls == 1); EXPECT(txcounters.num_tx_bytes == 1 + 40U); EXPECT(txcounters.tx_packets != NULL); if (txcounters.tx_packets != NULL) { u8_t sent; u16_t ret; ret = pbuf_copy_partial(txcounters.tx_packets, &sent, 1, 40U); EXPECT(ret == 1); EXPECT(sent == expected); } if (txcounters.tx_packets != NULL) { pbuf_free(txcounters.tx_packets); txcounters.tx_packets = NULL; } } /* make sure the pcb is freed */ EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } START_TEST(test_tcp_tx_full_window_lost_from_unsent) { LWIP_UNUSED_ARG(_i); test_tcp_tx_full_window_lost(1); } END_TEST START_TEST(test_tcp_tx_full_window_lost_from_unacked) { LWIP_UNUSED_ARG(_i); test_tcp_tx_full_window_lost(0); } END_TEST /** Create the suite including all tests for this module */ Suite * tcp_suite(void) { testfunc tests[] = { TESTFUNC(test_tcp_new_abort), TESTFUNC(test_tcp_recv_inseq), TESTFUNC(test_tcp_malformed_header), TESTFUNC(test_tcp_fast_retx_recover), TESTFUNC(test_tcp_fast_rexmit_wraparound), TESTFUNC(test_tcp_rto_rexmit_wraparound), TESTFUNC(test_tcp_tx_full_window_lost_from_unacked), TESTFUNC(test_tcp_tx_full_window_lost_from_unsent) }; return create_suite("TCP", tests, sizeof(tests)/sizeof(testfunc), tcp_setup, tcp_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/test_tcp.c
C
unknown
24,264
#ifndef LWIP_HDR_TEST_TCP_H #define LWIP_HDR_TEST_TCP_H #include "../lwip_check.h" Suite *tcp_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/test_tcp.h
C
unknown
125
#include "test_tcp_oos.h" #include "lwip/priv/tcp_priv.h" #include "lwip/stats.h" #include "tcp_helper.h" #if !LWIP_STATS || !TCP_STATS || !MEMP_STATS #error "This tests needs TCP- and MEMP-statistics enabled" #endif #if !TCP_QUEUE_OOSEQ #error "This tests needs TCP_QUEUE_OOSEQ enabled" #endif /** CHECK_SEGMENTS_ON_OOSEQ: * 1: check count, seqno and len of segments on pcb->ooseq (strict) * 0: only check that bytes are received in correct order (less strict) */ #define CHECK_SEGMENTS_ON_OOSEQ 1 #if CHECK_SEGMENTS_ON_OOSEQ #define EXPECT_OOSEQ(x) EXPECT(x) #else #define EXPECT_OOSEQ(x) #endif /* helper functions */ /** Get the numbers of segments on the ooseq list */ static int tcp_oos_count(struct tcp_pcb* pcb) { int num = 0; struct tcp_seg* seg = pcb->ooseq; while(seg != NULL) { num++; seg = seg->next; } return num; } #if TCP_OOSEQ_MAX_PBUFS && (TCP_OOSEQ_MAX_PBUFS < ((TCP_WND / TCP_MSS) + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) /** Get the numbers of pbufs on the ooseq list */ static int tcp_oos_pbuf_count(struct tcp_pcb* pcb) { int num = 0; struct tcp_seg* seg = pcb->ooseq; while(seg != NULL) { num += pbuf_clen(seg->p); seg = seg->next; } return num; } #endif /** Get the seqno of a segment (by index) on the ooseq list * * @param pcb the pcb to check for ooseq segments * @param seg_index index of the segment on the ooseq list * @return seqno of the segment */ static u32_t tcp_oos_seg_seqno(struct tcp_pcb* pcb, int seg_index) { int num = 0; struct tcp_seg* seg = pcb->ooseq; /* then check the actual segment */ while(seg != NULL) { if(num == seg_index) { return seg->tcphdr->seqno; } num++; seg = seg->next; } fail(); return 0; } /** Get the tcplen (datalen + SYN/FIN) of a segment (by index) on the ooseq list * * @param pcb the pcb to check for ooseq segments * @param seg_index index of the segment on the ooseq list * @return tcplen of the segment */ static int tcp_oos_seg_tcplen(struct tcp_pcb* pcb, int seg_index) { int num = 0; struct tcp_seg* seg = pcb->ooseq; /* then check the actual segment */ while(seg != NULL) { if(num == seg_index) { return TCP_TCPLEN(seg); } num++; seg = seg->next; } fail(); return -1; } /** Get the tcplen (datalen + SYN/FIN) of all segments on the ooseq list * * @param pcb the pcb to check for ooseq segments * @return tcplen of all segment */ static int tcp_oos_tcplen(struct tcp_pcb* pcb) { int len = 0; struct tcp_seg* seg = pcb->ooseq; /* then check the actual segment */ while(seg != NULL) { len += TCP_TCPLEN(seg); seg = seg->next; } return len; } /* Setup/teardown functions */ static void tcp_oos_setup(void) { tcp_remove_all(); } static void tcp_oos_teardown(void) { tcp_remove_all(); netif_list = NULL; netif_default = NULL; } /* Test functions */ /** create multiple segments and pass them to tcp_input in a wrong * order to see if ooseq-caching works correctly * FIN is received in out-of-sequence segments only */ START_TEST(test_tcp_recv_ooseq_FIN_OOSEQ) { struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p_8_9, *p_4_8, *p_4_10, *p_2_14, *p_fin, *pinseq; char data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; ip_addr_t remote_ip, local_ip, netmask; u16_t data_len; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; LWIP_UNUSED_ARG(_i); /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); data_len = sizeof(data); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = data_len; counters.expected_data = data; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); /* create segments */ /* pinseq is sent as last segment! */ pinseq = tcp_create_rx_segment(pcb, &data[0], 4, 0, 0, TCP_ACK); /* p1: 8 bytes before FIN */ /* seqno: 8..16 */ p_8_9 = tcp_create_rx_segment(pcb, &data[8], 8, 8, 0, TCP_ACK|TCP_FIN); /* p2: 4 bytes before p1, including the first 4 bytes of p1 (partly duplicate) */ /* seqno: 4..11 */ p_4_8 = tcp_create_rx_segment(pcb, &data[4], 8, 4, 0, TCP_ACK); /* p3: same as p2 but 2 bytes longer */ /* seqno: 4..13 */ p_4_10 = tcp_create_rx_segment(pcb, &data[4], 10, 4, 0, TCP_ACK); /* p4: 14 bytes before FIN, includes data from p1 and p2, plus partly from pinseq */ /* seqno: 2..15 */ p_2_14 = tcp_create_rx_segment(pcb, &data[2], 14, 2, 0, TCP_ACK); /* FIN, seqno 16 */ p_fin = tcp_create_rx_segment(pcb, NULL, 0,16, 0, TCP_ACK|TCP_FIN); EXPECT(pinseq != NULL); EXPECT(p_8_9 != NULL); EXPECT(p_4_8 != NULL); EXPECT(p_4_10 != NULL); EXPECT(p_2_14 != NULL); EXPECT(p_fin != NULL); if ((pinseq != NULL) && (p_8_9 != NULL) && (p_4_8 != NULL) && (p_4_10 != NULL) && (p_2_14 != NULL) && (p_fin != NULL)) { /* pass the segment to tcp_input */ test_tcp_input(p_8_9, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 8); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 9); /* includes FIN */ /* pass the segment to tcp_input */ test_tcp_input(p_4_8, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 4); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 4); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 8); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 9); /* includes FIN */ /* pass the segment to tcp_input */ test_tcp_input(p_4_10, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* ooseq queue: unchanged */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 4); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 4); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 8); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 9); /* includes FIN */ /* pass the segment to tcp_input */ test_tcp_input(p_2_14, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 2); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 15); /* includes FIN */ /* pass the segment to tcp_input */ test_tcp_input(p_fin, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* ooseq queue: unchanged */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 2); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 15); /* includes FIN */ /* pass the segment to tcp_input */ test_tcp_input(pinseq, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 1); EXPECT(counters.recv_calls == 1); EXPECT(counters.recved_bytes == data_len); EXPECT(counters.err_calls == 0); EXPECT(pcb->ooseq == NULL); } /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST /** create multiple segments and pass them to tcp_input in a wrong * order to see if ooseq-caching works correctly * FIN is received IN-SEQUENCE at the end */ START_TEST(test_tcp_recv_ooseq_FIN_INSEQ) { struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p_1_2, *p_4_8, *p_3_11, *p_2_12, *p_15_1, *p_15_1a, *pinseq, *pinseqFIN; char data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; ip_addr_t remote_ip, local_ip, netmask; u16_t data_len; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; LWIP_UNUSED_ARG(_i); /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); data_len = sizeof(data); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = data_len; counters.expected_data = data; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); /* create segments */ /* p1: 7 bytes - 2 before FIN */ /* seqno: 1..2 */ p_1_2 = tcp_create_rx_segment(pcb, &data[1], 2, 1, 0, TCP_ACK); /* p2: 4 bytes before p1, including the first 4 bytes of p1 (partly duplicate) */ /* seqno: 4..11 */ p_4_8 = tcp_create_rx_segment(pcb, &data[4], 8, 4, 0, TCP_ACK); /* p3: same as p2 but 2 bytes longer and one byte more at the front */ /* seqno: 3..13 */ p_3_11 = tcp_create_rx_segment(pcb, &data[3], 11, 3, 0, TCP_ACK); /* p4: 13 bytes - 2 before FIN - should be ignored as contained in p1 and p3 */ /* seqno: 2..13 */ p_2_12 = tcp_create_rx_segment(pcb, &data[2], 12, 2, 0, TCP_ACK); /* pinseq is the first segment that is held back to create ooseq! */ /* seqno: 0..3 */ pinseq = tcp_create_rx_segment(pcb, &data[0], 4, 0, 0, TCP_ACK); /* p5: last byte before FIN */ /* seqno: 15 */ p_15_1 = tcp_create_rx_segment(pcb, &data[15], 1, 15, 0, TCP_ACK); /* p6: same as p5, should be ignored */ p_15_1a= tcp_create_rx_segment(pcb, &data[15], 1, 15, 0, TCP_ACK); /* pinseqFIN: last 2 bytes plus FIN */ /* only segment containing seqno 14 and FIN */ pinseqFIN = tcp_create_rx_segment(pcb, &data[14], 2, 14, 0, TCP_ACK|TCP_FIN); EXPECT(pinseq != NULL); EXPECT(p_1_2 != NULL); EXPECT(p_4_8 != NULL); EXPECT(p_3_11 != NULL); EXPECT(p_2_12 != NULL); EXPECT(p_15_1 != NULL); EXPECT(p_15_1a != NULL); EXPECT(pinseqFIN != NULL); if ((pinseq != NULL) && (p_1_2 != NULL) && (p_4_8 != NULL) && (p_3_11 != NULL) && (p_2_12 != NULL) && (p_15_1 != NULL) && (p_15_1a != NULL) && (pinseqFIN != NULL)) { /* pass the segment to tcp_input */ test_tcp_input(p_1_2, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2); /* pass the segment to tcp_input */ test_tcp_input(p_4_8, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 4); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 8); /* pass the segment to tcp_input */ test_tcp_input(p_3_11, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2); /* p_3_11 has removed p_4_8 from ooseq */ EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 3); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 11); /* pass the segment to tcp_input */ test_tcp_input(p_2_12, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 2); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 2); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 12); /* pass the segment to tcp_input */ test_tcp_input(pinseq, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 1); EXPECT(counters.recved_bytes == 14); EXPECT(counters.err_calls == 0); EXPECT(pcb->ooseq == NULL); /* pass the segment to tcp_input */ test_tcp_input(p_15_1, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 1); EXPECT(counters.recved_bytes == 14); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 15); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1); /* pass the segment to tcp_input */ test_tcp_input(p_15_1a, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 1); EXPECT(counters.recved_bytes == 14); EXPECT(counters.err_calls == 0); /* check ooseq queue: unchanged */ EXPECT_OOSEQ(tcp_oos_count(pcb) == 1); EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 15); EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1); /* pass the segment to tcp_input */ test_tcp_input(pinseqFIN, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 1); EXPECT(counters.recv_calls == 2); EXPECT(counters.recved_bytes == data_len); EXPECT(counters.err_calls == 0); EXPECT(pcb->ooseq == NULL); } /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } END_TEST static char data_full_wnd[TCP_WND + TCP_MSS]; /** create multiple segments and pass them to tcp_input with the first segment missing * to simulate overruning the rxwin with ooseq queueing enabled */ START_TEST(test_tcp_recv_ooseq_overrun_rxwin) { #if !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS int i, k; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *pinseq, *p_ovr; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; int datalen = 0; int datalen2; for(i = 0; i < (int)sizeof(data_full_wnd); i++) { data_full_wnd[i] = (char)i; } /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = TCP_WND; counters.expected_data = data_full_wnd; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->rcv_nxt = 0x8000; /* create segments */ /* pinseq is sent as last segment! */ pinseq = tcp_create_rx_segment(pcb, &data_full_wnd[0], TCP_MSS, 0, 0, TCP_ACK); for(i = TCP_MSS, k = 0; i < TCP_WND; i += TCP_MSS, k++) { int count, expected_datalen; struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)], TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK); EXPECT_RET(p != NULL); /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ count = tcp_oos_count(pcb); EXPECT_OOSEQ(count == k+1); datalen = tcp_oos_tcplen(pcb); if (i + TCP_MSS < TCP_WND) { expected_datalen = (k+1)*TCP_MSS; } else { expected_datalen = TCP_WND - TCP_MSS; } if (datalen != expected_datalen) { EXPECT_OOSEQ(datalen == expected_datalen); } } /* pass in one more segment, cleary overrunning the rxwin */ p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)], TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK); EXPECT_RET(p_ovr != NULL); /* pass the segment to tcp_input */ test_tcp_input(p_ovr, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == k); datalen2 = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen == datalen2); /* now pass inseq */ test_tcp_input(pinseq, &netif); EXPECT(pcb->ooseq == NULL); /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); #endif /* !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS */ LWIP_UNUSED_ARG(_i); } END_TEST /** similar to above test, except seqno starts near the max rxwin */ START_TEST(test_tcp_recv_ooseq_overrun_rxwin_edge) { #if !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS int i, k; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *pinseq, *p_ovr; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; int datalen = 0; int datalen2; for(i = 0; i < (int)sizeof(data_full_wnd); i++) { data_full_wnd[i] = (char)i; } /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = TCP_WND; counters.expected_data = data_full_wnd; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->rcv_nxt = 0xffffffff - (TCP_WND / 2); /* create segments */ /* pinseq is sent as last segment! */ pinseq = tcp_create_rx_segment(pcb, &data_full_wnd[0], TCP_MSS, 0, 0, TCP_ACK); for(i = TCP_MSS, k = 0; i < TCP_WND; i += TCP_MSS, k++) { int count, expected_datalen; struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)], TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK); EXPECT_RET(p != NULL); /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ count = tcp_oos_count(pcb); EXPECT_OOSEQ(count == k+1); datalen = tcp_oos_tcplen(pcb); if (i + TCP_MSS < TCP_WND) { expected_datalen = (k+1)*TCP_MSS; } else { expected_datalen = TCP_WND - TCP_MSS; } if (datalen != expected_datalen) { EXPECT_OOSEQ(datalen == expected_datalen); } } /* pass in one more segment, cleary overrunning the rxwin */ p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)], TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK); EXPECT_RET(p_ovr != NULL); /* pass the segment to tcp_input */ test_tcp_input(p_ovr, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ EXPECT_OOSEQ(tcp_oos_count(pcb) == k); datalen2 = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen == datalen2); /* now pass inseq */ test_tcp_input(pinseq, &netif); EXPECT(pcb->ooseq == NULL); /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); #endif /* !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS */ LWIP_UNUSED_ARG(_i); } END_TEST START_TEST(test_tcp_recv_ooseq_max_bytes) { #if TCP_OOSEQ_MAX_BYTES && (TCP_OOSEQ_MAX_BYTES < (TCP_WND + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) int i, k; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p_ovr; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; int datalen = 0; int datalen2; for(i = 0; i < sizeof(data_full_wnd); i++) { data_full_wnd[i] = (char)i; } /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = TCP_WND; counters.expected_data = data_full_wnd; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->rcv_nxt = 0x8000; /* don't 'recv' the first segment (1 byte) so that all other segments will be ooseq */ /* create segments and 'recv' them */ for(k = 1, i = 1; k < TCP_OOSEQ_MAX_BYTES; k += TCP_MSS, i++) { int count; struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[k], TCP_MSS, k, 0, TCP_ACK); EXPECT_RET(p != NULL); EXPECT_RET(p->next == NULL); /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ count = tcp_oos_pbuf_count(pcb); EXPECT_OOSEQ(count == i); datalen = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen == (i * TCP_MSS)); } /* pass in one more segment, overrunning the limit */ p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[k+1], 1, k+1, 0, TCP_ACK); EXPECT_RET(p_ovr != NULL); /* pass the segment to tcp_input */ test_tcp_input(p_ovr, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue (ensure the new segment was not accepted) */ EXPECT_OOSEQ(tcp_oos_count(pcb) == (i-1)); datalen2 = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen2 == ((i-1) * TCP_MSS)); /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); #endif /* TCP_OOSEQ_MAX_BYTES && (TCP_OOSEQ_MAX_BYTES < (TCP_WND + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) */ LWIP_UNUSED_ARG(_i); } END_TEST START_TEST(test_tcp_recv_ooseq_max_pbufs) { #if TCP_OOSEQ_MAX_PBUFS && (TCP_OOSEQ_MAX_PBUFS < ((TCP_WND / TCP_MSS) + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) int i; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p_ovr; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; int datalen = 0; int datalen2; for(i = 0; i < sizeof(data_full_wnd); i++) { data_full_wnd[i] = (char)i; } /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = TCP_WND; counters.expected_data = data_full_wnd; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->rcv_nxt = 0x8000; /* don't 'recv' the first segment (1 byte) so that all other segments will be ooseq */ /* create segments and 'recv' them */ for(i = 1; i <= TCP_OOSEQ_MAX_PBUFS; i++) { int count; struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[i], 1, i, 0, TCP_ACK); EXPECT_RET(p != NULL); EXPECT_RET(p->next == NULL); /* pass the segment to tcp_input */ test_tcp_input(p, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue */ count = tcp_oos_pbuf_count(pcb); EXPECT_OOSEQ(count == i); datalen = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen == i); } /* pass in one more segment, overrunning the limit */ p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[i+1], 1, i+1, 0, TCP_ACK); EXPECT_RET(p_ovr != NULL); /* pass the segment to tcp_input */ test_tcp_input(p_ovr, &netif); /* check if counters are as expected */ EXPECT(counters.close_calls == 0); EXPECT(counters.recv_calls == 0); EXPECT(counters.recved_bytes == 0); EXPECT(counters.err_calls == 0); /* check ooseq queue (ensure the new segment was not accepted) */ EXPECT_OOSEQ(tcp_oos_count(pcb) == (i-1)); datalen2 = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(datalen2 == (i-1)); /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); #endif /* TCP_OOSEQ_MAX_PBUFS && (TCP_OOSEQ_MAX_BYTES < (TCP_WND + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) */ LWIP_UNUSED_ARG(_i); } END_TEST static void check_rx_counters(struct tcp_pcb *pcb, struct test_tcp_counters *counters, u32_t exp_close_calls, u32_t exp_rx_calls, u32_t exp_rx_bytes, u32_t exp_err_calls, int exp_oos_count, int exp_oos_len) { int oos_len; EXPECT(counters->close_calls == exp_close_calls); EXPECT(counters->recv_calls == exp_rx_calls); EXPECT(counters->recved_bytes == exp_rx_bytes); EXPECT(counters->err_calls == exp_err_calls); /* check that pbuf is queued in ooseq */ EXPECT_OOSEQ(tcp_oos_count(pcb) == exp_oos_count); oos_len = tcp_oos_tcplen(pcb); EXPECT_OOSEQ(exp_oos_len == oos_len); } /* this test uses 4 packets: * - data (len=TCP_MSS) * - FIN * - data after FIN (len=1) (invalid) * - 2nd FIN (invalid) * * the parameter 'delay_packet' is a bitmask that choses which on these packets is ooseq */ static void test_tcp_recv_ooseq_double_FINs(int delay_packet) { int i, k; struct test_tcp_counters counters; struct tcp_pcb* pcb; struct pbuf *p_normal_fin, *p_data_after_fin, *p, *p_2nd_fin_ooseq; ip_addr_t remote_ip, local_ip, netmask; u16_t remote_port = 0x100, local_port = 0x101; struct netif netif; u32_t exp_rx_calls = 0, exp_rx_bytes = 0, exp_close_calls = 0, exp_oos_pbufs = 0, exp_oos_tcplen = 0; int first_dropped = 0xff; for(i = 0; i < (int)sizeof(data_full_wnd); i++) { data_full_wnd[i] = (char)i; } /* initialize local vars */ memset(&netif, 0, sizeof(netif)); IP_ADDR4(&local_ip, 192, 168, 1, 1); IP_ADDR4(&remote_ip, 192, 168, 1, 2); IP_ADDR4(&netmask, 255, 255, 255, 0); test_tcp_init_netif(&netif, NULL, &local_ip, &netmask); /* initialize counter struct */ memset(&counters, 0, sizeof(counters)); counters.expected_data_len = TCP_WND; counters.expected_data = data_full_wnd; /* create and initialize the pcb */ pcb = test_tcp_new_counters_pcb(&counters); EXPECT_RET(pcb != NULL); tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port); pcb->rcv_nxt = 0x8000; /* create segments */ p = tcp_create_rx_segment(pcb, &data_full_wnd[0], TCP_MSS, 0, 0, TCP_ACK); p_normal_fin = tcp_create_rx_segment(pcb, NULL, 0, TCP_MSS, 0, TCP_ACK|TCP_FIN); k = 1; p_data_after_fin = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS+1], k, TCP_MSS+1, 0, TCP_ACK); p_2nd_fin_ooseq = tcp_create_rx_segment(pcb, NULL, 0, TCP_MSS+1+k, 0, TCP_ACK|TCP_FIN); if(delay_packet & 1) { /* drop normal data */ first_dropped = 1; } else { /* send normal data */ test_tcp_input(p, &netif); exp_rx_calls++; exp_rx_bytes += TCP_MSS; } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 2) { /* drop FIN */ if(first_dropped > 2) { first_dropped = 2; } } else { /* send FIN */ test_tcp_input(p_normal_fin, &netif); if (first_dropped < 2) { /* already dropped packets, this one is ooseq */ exp_oos_pbufs++; exp_oos_tcplen++; } else { /* inseq */ exp_close_calls++; } } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 4) { /* drop data-after-FIN */ if(first_dropped > 3) { first_dropped = 3; } } else { /* send data-after-FIN */ test_tcp_input(p_data_after_fin, &netif); if (first_dropped < 3) { /* already dropped packets, this one is ooseq */ if (delay_packet & 2) { /* correct FIN was ooseq */ exp_oos_pbufs++; exp_oos_tcplen += k; } } else { /* inseq: no change */ } } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 8) { /* drop 2nd-FIN */ if(first_dropped > 4) { first_dropped = 4; } } else { /* send 2nd-FIN */ test_tcp_input(p_2nd_fin_ooseq, &netif); if (first_dropped < 3) { /* already dropped packets, this one is ooseq */ if (delay_packet & 2) { /* correct FIN was ooseq */ exp_oos_pbufs++; exp_oos_tcplen++; } } else { /* inseq: no change */ } } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 1) { /* dropped normal data before */ test_tcp_input(p, &netif); exp_rx_calls++; exp_rx_bytes += TCP_MSS; if((delay_packet & 2) == 0) { /* normal FIN was NOT delayed */ exp_close_calls++; exp_oos_pbufs = exp_oos_tcplen = 0; } } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 2) { /* dropped normal FIN before */ test_tcp_input(p_normal_fin, &netif); exp_close_calls++; exp_oos_pbufs = exp_oos_tcplen = 0; } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 4) { /* dropped data-after-FIN before */ test_tcp_input(p_data_after_fin, &netif); } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); if(delay_packet & 8) { /* dropped 2nd-FIN before */ test_tcp_input(p_2nd_fin_ooseq, &netif); } /* check if counters are as expected */ check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen); /* check that ooseq data has been dumped */ EXPECT(pcb->ooseq == NULL); /* make sure the pcb is freed */ EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1); tcp_abort(pcb); EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } /** create multiple segments and pass them to tcp_input with the first segment missing * to simulate overruning the rxwin with ooseq queueing enabled */ #define FIN_TEST(name, num) \ START_TEST(name) \ { \ LWIP_UNUSED_ARG(_i); \ test_tcp_recv_ooseq_double_FINs(num); \ } \ END_TEST FIN_TEST(test_tcp_recv_ooseq_double_FIN_0, 0) FIN_TEST(test_tcp_recv_ooseq_double_FIN_1, 1) FIN_TEST(test_tcp_recv_ooseq_double_FIN_2, 2) FIN_TEST(test_tcp_recv_ooseq_double_FIN_3, 3) FIN_TEST(test_tcp_recv_ooseq_double_FIN_4, 4) FIN_TEST(test_tcp_recv_ooseq_double_FIN_5, 5) FIN_TEST(test_tcp_recv_ooseq_double_FIN_6, 6) FIN_TEST(test_tcp_recv_ooseq_double_FIN_7, 7) FIN_TEST(test_tcp_recv_ooseq_double_FIN_8, 8) FIN_TEST(test_tcp_recv_ooseq_double_FIN_9, 9) FIN_TEST(test_tcp_recv_ooseq_double_FIN_10, 10) FIN_TEST(test_tcp_recv_ooseq_double_FIN_11, 11) FIN_TEST(test_tcp_recv_ooseq_double_FIN_12, 12) FIN_TEST(test_tcp_recv_ooseq_double_FIN_13, 13) FIN_TEST(test_tcp_recv_ooseq_double_FIN_14, 14) FIN_TEST(test_tcp_recv_ooseq_double_FIN_15, 15) /** Create the suite including all tests for this module */ Suite * tcp_oos_suite(void) { testfunc tests[] = { TESTFUNC(test_tcp_recv_ooseq_FIN_OOSEQ), TESTFUNC(test_tcp_recv_ooseq_FIN_INSEQ), TESTFUNC(test_tcp_recv_ooseq_overrun_rxwin), TESTFUNC(test_tcp_recv_ooseq_overrun_rxwin_edge), TESTFUNC(test_tcp_recv_ooseq_max_bytes), TESTFUNC(test_tcp_recv_ooseq_max_pbufs), TESTFUNC(test_tcp_recv_ooseq_double_FIN_0), TESTFUNC(test_tcp_recv_ooseq_double_FIN_1), TESTFUNC(test_tcp_recv_ooseq_double_FIN_2), TESTFUNC(test_tcp_recv_ooseq_double_FIN_3), TESTFUNC(test_tcp_recv_ooseq_double_FIN_4), TESTFUNC(test_tcp_recv_ooseq_double_FIN_5), TESTFUNC(test_tcp_recv_ooseq_double_FIN_6), TESTFUNC(test_tcp_recv_ooseq_double_FIN_7), TESTFUNC(test_tcp_recv_ooseq_double_FIN_8), TESTFUNC(test_tcp_recv_ooseq_double_FIN_9), TESTFUNC(test_tcp_recv_ooseq_double_FIN_10), TESTFUNC(test_tcp_recv_ooseq_double_FIN_11), TESTFUNC(test_tcp_recv_ooseq_double_FIN_12), TESTFUNC(test_tcp_recv_ooseq_double_FIN_13), TESTFUNC(test_tcp_recv_ooseq_double_FIN_14), TESTFUNC(test_tcp_recv_ooseq_double_FIN_15) }; return create_suite("TCP_OOS", tests, sizeof(tests)/sizeof(testfunc), tcp_oos_setup, tcp_oos_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/test_tcp_oos.c
C
unknown
36,904
#ifndef LWIP_HDR_TEST_TCP_OOS_H #define LWIP_HDR_TEST_TCP_OOS_H #include "../lwip_check.h" Suite *tcp_oos_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/tcp/test_tcp_oos.h
C
unknown
137
#include "test_udp.h" #include "lwip/udp.h" #include "lwip/stats.h" #if !LWIP_STATS || !UDP_STATS || !MEMP_STATS #error "This tests needs UDP- and MEMP-statistics enabled" #endif /* Helper functions */ static void udp_remove_all(void) { struct udp_pcb *pcb = udp_pcbs; struct udp_pcb *pcb2; while(pcb != NULL) { pcb2 = pcb; pcb = pcb->next; udp_remove(pcb2); } fail_unless(MEMP_STATS_GET(used, MEMP_UDP_PCB) == 0); } /* Setups/teardown functions */ static void udp_setup(void) { udp_remove_all(); } static void udp_teardown(void) { udp_remove_all(); } /* Test functions */ START_TEST(test_udp_new_remove) { struct udp_pcb* pcb; LWIP_UNUSED_ARG(_i); fail_unless(MEMP_STATS_GET(used, MEMP_UDP_PCB) == 0); pcb = udp_new(); fail_unless(pcb != NULL); if (pcb != NULL) { fail_unless(MEMP_STATS_GET(used, MEMP_UDP_PCB) == 1); udp_remove(pcb); fail_unless(MEMP_STATS_GET(used, MEMP_UDP_PCB) == 0); } } END_TEST /** Create the suite including all tests for this module */ Suite * udp_suite(void) { testfunc tests[] = { TESTFUNC(test_udp_new_remove), }; return create_suite("UDP", tests, sizeof(tests)/sizeof(testfunc), udp_setup, udp_teardown); }
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/udp/test_udp.c
C
unknown
1,282
#ifndef LWIP_HDR_TEST_UDP_H #define LWIP_HDR_TEST_UDP_H #include "../lwip_check.h" Suite* udp_suite(void); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/test/unit/udp/test_udp.h
C
unknown
125
#LWIP LWIP_VERSION?=2.0.3 ifeq ($(LWIP_VERSION),1.5.0-beta) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include/ipv4 inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include/ipv6 inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/LwipAdp ifeq ($(CFG_STM32F1X),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/arm_cm3 vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/arm_cm3 obj-$(USE_LWIP) += ethernetif.o else ifeq ($(CFG_MPC5748G)$(CFG_MPC5747C)$(CFG_MPC5746C)$(CFG_MPC5777C),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/asrIf vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/asrIf else ifeq ($(CFG_MPC55XX),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/mpc5xxx vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/mpc5xxx obj-$(USE_LWIP) += fec_5xxx.o obj-$(USE_LWIP) += ethernetif.o else ifeq ($(CFG_TC29X),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/tc29x vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/tc29x else ifeq ($(CFG_BRD_LINUX),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/utest vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/utest else inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/asrIf vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/asrIf #obj-$(USE_LWIP) += memhdl.o endif obj-$(USE_LWIP) += sys_arch.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/port/ArcticCore/LwipAdp #obj-$(USE_LWIP) += httpd.o obj-$(USE_LWIP) += mbox.o obj-$(USE_LWIP) += LwIpAdp.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core/ipv4 vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core/ipv6 #ipv6 obj-$(USE_LWIP) += dhcp6.o obj-$(USE_LWIP) += icmp6.o obj-$(USE_LWIP) += ethip6.o obj-$(USE_LWIP) += inet6.o obj-$(USE_LWIP) += ip6_addr.o obj-$(USE_LWIP) += ip6_frag.o obj-$(USE_LWIP) += ip6.o obj-$(USE_LWIP) += mld6.o obj-$(USE_LWIP) += nd6.o #ipv4 obj-$(USE_LWIP) += autoip.o obj-$(USE_LWIP) += icmp.o obj-$(USE_LWIP) += igmp.o obj-$(USE_LWIP) += ip_frag.o obj-$(USE_LWIP) += ip4_addr.o obj-$(USE_LWIP) += ip4.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core obj-$(USE_LWIP) += inet_chksum.o obj-$(USE_LWIP) += init_lwip.o obj-$(USE_LWIP) += dns.o obj-$(USE_LWIP) += def.o obj-$(USE_LWIP) += dhcp.o obj-$(USE_LWIP) += mem.o obj-$(USE_LWIP) += memp.o obj-$(USE_LWIP) += netif.o obj-$(USE_LWIP) += pbuf.o obj-$(USE_LWIP) += raw.o obj-$(USE_LWIP) += stats.o obj-$(USE_LWIP) += sys.o obj-$(USE_LWIP) += tcp.o obj-$(USE_LWIP) += tcp_in.o obj-$(USE_LWIP) += tcp_out.o obj-$(USE_LWIP) += udp.o obj-$(USE_LWIP) += timers.o obj-$(USE_LWIP) += netbios.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/api obj-$(USE_LWIP) += api_msg.o obj-$(USE_LWIP) += api_lib.o obj-$(USE_LWIP) += err.o obj-$(USE_LWIP) += netbuf.o obj-$(USE_LWIP) += netdb.o obj-$(USE_LWIP) += netifapi.o obj-$(USE_LWIP) += sockets.o obj-$(USE_LWIP) += tcpip_lwip.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/netif obj-$(USE_LWIP) += etharp.o else inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include/ipv4 inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/include/ipv6 inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/LwipAdp ifeq ($(CFG_STM32F1X),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/arm_cm3 vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/arm_cm3 obj-$(USE_LWIP) += ethernetif.o else ifeq ($(CFG_MPC5748G)$(CFG_MPC5747C)$(CFG_MPC5746C)$(CFG_MPC5777C),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/asrIf vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/asrIf else ifeq ($(CFG_MPC55XX),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/mpc5xxx vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/mpc5xxx obj-$(USE_LWIP) += fec_5xxx.o obj-$(USE_LWIP) += ethernetif.o else ifeq ($(CFG_TC29X),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/tc29x vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/tc29x else ifeq ($(CFG_BRD_LINUX),y) inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/utest vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/utest else inc-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/asrIf vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/asrIf #obj-$(USE_LWIP) += memhdl.o endif obj-$(USE_LWIP) += sys_arch.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/contrib/ports/ArcticCore/LwipAdp #obj-$(USE_LWIP) += httpd.o obj-$(USE_LWIP) += mbox.o obj-$(USE_LWIP) += LwIpAdp.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core/ipv4 vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core/ipv6 #ipv6 obj-$(USE_LWIP) += dhcp6.o obj-$(USE_LWIP) += icmp6.o obj-$(USE_LWIP) += ethip6.o obj-$(USE_LWIP) += inet6.o obj-$(USE_LWIP) += ip6_addr.o obj-$(USE_LWIP) += ip6_frag.o obj-$(USE_LWIP) += ip6.o obj-$(USE_LWIP) += mld6.o obj-$(USE_LWIP) += nd6.o #ipv4 obj-$(USE_LWIP) += autoip.o obj-$(USE_LWIP) += icmp.o obj-$(USE_LWIP) += igmp.o obj-$(USE_LWIP) += ip4_frag.o obj-$(USE_LWIP) += ip4_addr.o obj-$(USE_LWIP) += ip4.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/core obj-$(USE_LWIP) += ip.o obj-$(USE_LWIP) += inet_chksum.o obj-$(USE_LWIP) += init_lwip.o obj-$(USE_LWIP) += dns.o obj-$(USE_LWIP) += def.o obj-$(USE_LWIP) += dhcp.o obj-$(USE_LWIP) += mem.o obj-$(USE_LWIP) += memp.o obj-$(USE_LWIP) += netif.o obj-$(USE_LWIP) += pbuf.o obj-$(USE_LWIP) += raw.o obj-$(USE_LWIP) += stats.o obj-$(USE_LWIP) += sys.o obj-$(USE_LWIP) += tcp.o obj-$(USE_LWIP) += tcp_in.o obj-$(USE_LWIP) += tcp_out.o obj-$(USE_LWIP) += udp.o obj-$(USE_LWIP) += timeouts.o obj-$(USE_LWIP) += netbios.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/api obj-$(USE_LWIP) += api_msg.o obj-$(USE_LWIP) += api_lib.o obj-$(USE_LWIP) += err.o obj-$(USE_LWIP) += netbuf.o obj-$(USE_LWIP) += netdb.o obj-$(USE_LWIP) += netifapi.o obj-$(USE_LWIP) += sockets.o obj-$(USE_LWIP) += tcpip_lwip.o vpath-$(USE_LWIP) += $(ROOTDIR)/communication/lwip-$(LWIP_VERSION)/src/netif obj-$(USE_LWIP) += ethernet.o obj-$(USE_LWIP) += etharp.o endif
2301_81045437/classic-platform
communication/lwip.mod.mk
Makefile
unknown
7,881
ifneq ($(filter y,$(USE_RTE) $(USE_QUEUE)),) obj-$(USE_QUEUE) += Queue.o inc-y += $(ROOTDIR)/datastructures/Queue/inc vpath-y += $(ROOTDIR)/datastructures/Queue/src endif
2301_81045437/classic-platform
datastructures/Queue/Queue.mod.mk
Makefile
unknown
178
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef QUEUE_H_ #define QUEUE_H_ #include <stddef.h> #include "Os.h" #include "Std_Types.h" /* * Used to guard against multiple queue imports */ #ifndef QUEUE_DEFS typedef uint8 Queue_ReturnType; /* @req ARC_SWS_Queue_00009*/ #define QUEUE_E_OK (Queue_ReturnType)0u #define QUEUE_E_TRUE (Queue_ReturnType)1u #define QUEUE_E_NO_INIT (Queue_ReturnType)2u #define QUEUE_E_FULL (Queue_ReturnType)130u #define QUEUE_E_NO_DATA (Queue_ReturnType)131u #define QUEUE_E_LOST_DATA (Queue_ReturnType)5u #define QUEUE_E_NO_CONTAINS (Queue_ReturnType)7u #define QUEUE_E_ALREADY_INIT (Queue_ReturnType)8u #define QUEUE_E_FALSE (Queue_ReturnType)9u #define QUEUE_E_NULL (Queue_ReturnType)10u /* Compare function for contains */ /* @req ARC_SWS_Queue_00008*/ typedef int (*cmpFunc)(void *, void *, size_t); #define QUEUE_DEFS #endif #ifndef MEMCPY #if defined(__GNUC__) #define MEMCPY(_x,_y,_z) __builtin_memcpy(_x,_y,_z) #else #include <string.h> #define MEMCPY(_x,_y,_z) memcpy(_x,_y,_z) #define MEMCPY #endif #endif /* MEMCPY*/ typedef struct queue { /* The max number of elements in the list */ uint8 max_count; uint8 count; /* Error flag */ boolean bufFullFlag; /* If queue is initiated */ boolean isInit; /* Size of the elements in the list */ size_t dataSize; /* List head and tail */ void *head; void *tail; /* Buffer start/stop */ void *bufStart; void *bufEnd; /* Compare function */ cmpFunc compare_func; } Queue_t; /** * @brief Initiates the queue * * @param queue Address of the queue to be initialized with Queue_Init() * The queue must be declared as a reference, not just a pointer. * @param buffer Char[] allocated data where the actual contents of the queue should reside. * @param max_count Maximum number of elements that the queue can contain * @param dataSize The size of each element in the queue. * @param compare_func Pointer to a function that has the signature int (*cmpFunc)(void *, void *, size_t). * Used for comparing elements in the queue * * @return QUEUE_E_OK - if successfully initialized. * @return QUEUE_E_ALREADY_INIT - queue already initiated */ Queue_ReturnType Queue_Init(Queue_t *queue, void *buffer, uint8 max_count, size_t dataSize, cmpFunc compare_func); /** * @brief Add an element to the queue * * @param queue Address of the queue that has been initialized with Queue_Init() * @param dataPtr Pointer to the data that is to be added * * @return QUEUE_E_OK - if successfully added. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Queue_Init() * @return QUEUE_E_FULL - Queue is full. */ Queue_ReturnType Queue_Add(Queue_t *queue, void const *dataPtr); /** * @brief Get next entry from the queue. This removes the item from the queue. * * @param queue Pointer to the queue that has been initialized with Queue_Init() * @param dataPtr Reference to a variable which will hold the result data * * @return QUEUE_E_OK - if successfully popped. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Queue_Init() * @return QUEUE_E_NO_DATA - nothing popped (it was empty) * @return QUEUE_E_LOST_DATA - if a buffer overflow has occurred previously */ Queue_ReturnType Queue_Next(Queue_t *queue, void *dataPtr); /** * @brief Peek (i.e lookup) the next element in the queue. This does not alter the queue. * * @param queue Pointer to the queue that has been initialized with Queue_Init() * @param dataPtr Reference to a variable which will hold the result data * * @return QUEUE_E_OK - if successfully peeked. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Queue_Init() * @return QUEUE_E_NO_DATA - nothing to peek at (it was empty) * @return QUEUE_E_LOST_DATA - if a buffer overflow has occurred previously */ Queue_ReturnType Queue_Peek(Queue_t const *queue, void *dataPtr); /** * @brief Looks through the queue after element dataPtr points to using its compare_func. * * @param queue Pointer to the queue that has been initialized with Queue_Init() * @param dataPtr Reference to a variable which will hold the element it will look for using its compare_func * * @return QUEUE_E_TRUE - if queue contains the element * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Queue_Init() * @return QUEUE_E_NO_DATA - nothing to peek at (it was empty) * @return QUEUE_E_FALSE - if the element could not be found in the queue * */ Queue_ReturnType Queue_Contains(Queue_t const *queue, void const *dataPtr); #endif /* QUEUE_H_ */
2301_81045437/classic-platform
datastructures/Queue/inc/Queue.h
C
unknown
5,895
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Queue.h" /* @req ARC_SWS_Queue_00001 The queue shall use FIFO (First in, First out) order.*/ /* @req ARC_SWS_Queue_00002 The queue shall support any datatype defined by user.*/ /* @req ARC_SWS_Queue_00010 The files of the queue shall be named: Queue.c and Queue.h */ /* @req ARC_SWS_Queue_00011 The queue shall not use native C types. */ /* @req ARC_SWS_Queue_00012 The queue shall be ready to be invoked at any time */ /* @req ARC_SWS_Queue_00013 The queue shall not call any BSW modules function */ /* * A circular buffer implementation of fifo queue.* */ /* @req ARC_SWS_Queue_00003 */ Queue_ReturnType Queue_Init(Queue_t *queue, void *buffer, uint8 max_count, size_t dataSize, cmpFunc cmp) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (buffer == NULL_PTR) || (cmp == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit == TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_ALREADY_INIT; } queue->bufStart = buffer; /*lint -e970 MISRA:OTHER:argument check:[MISRA 2012 Directive 4.6, advisory]*/ queue->bufEnd = (char *) buffer + (max_count * dataSize); /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ queue->head = queue->bufStart; queue->tail = queue->bufStart; queue->dataSize = dataSize; queue->count = 0u; queue->max_count = max_count; queue->compare_func = *cmp; queue->isInit = TRUE; queue->bufFullFlag = FALSE; SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_Queue_00004 */ Queue_ReturnType Queue_Add(Queue_t *queue, void const *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } //Not initialized if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; /* Faulty pointer into method */ } //Queue is full if (queue->count == queue->max_count) { queue->bufFullFlag = TRUE; SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_FULL; /* No more room */ } MEMCPY(queue->head, dataPtr, queue->dataSize); /*lint -e970 MISRA:OTHER:argument check:[MISRA 2012 Directive 4.6, advisory]*/ queue->head = (char *) queue->head + queue->dataSize; /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ //Wrap-around if (queue->head == queue->bufEnd) { queue->head = queue->bufStart; } queue->count++; SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_Queue_00005 */ Queue_ReturnType Queue_Next(Queue_t *queue, void *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; /* Faulty pointer into method */ } if (queue->count == 0) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } MEMCPY((void*) dataPtr, queue->tail, queue->dataSize); /*lint -e970 MISRA:OTHER:argument check:[MISRA 2012 Directive 4.6, advisory]*/ queue->tail = (char *) queue->tail + queue->dataSize; /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ if (queue->tail == queue->bufEnd) { queue->tail = queue->bufStart; } --queue->count; if (queue->bufFullFlag == TRUE) { queue->bufFullFlag = FALSE; SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_LOST_DATA; } SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_Queue_00006 */ Queue_ReturnType Queue_Peek(Queue_t const *queue, void *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; } if (queue->count == 0) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } MEMCPY((void*) dataPtr, queue->tail, queue->dataSize); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_Queue_00007 */ Queue_ReturnType Queue_Contains(Queue_t const *queue, void const *dataPtr) { uint8 i; SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != (boolean)TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; } if (queue->count == 0) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } /*lint -e970 MISRA:OTHER:argument check:[MISRA 2012 Directive 4.6, advisory]*/ char *iter = queue->tail; //Loop through queue for (i = 0; i < queue->count; i++) { if (queue->compare_func(iter, (void*) dataPtr, queue->dataSize) == 0) { /*lint !e9005 MISRA:PERFORMANCE:casting away const is okay:[MISRA 2012 Rule 11.8, required]*/ SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_TRUE; } iter = iter + queue->dataSize; /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ } SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_FALSE; }
2301_81045437/classic-platform
datastructures/Queue/src/Queue.c
C
unknown
7,504
obj-$(USE_SAFEQ) += Safety_Queue.o inc-$(USE_SAFEQ) += $(ROOTDIR)/datastructures/Safety_Queue/inc vpath-$(USE_SAFEQ) += $(ROOTDIR)/datastructures/Safety_Queue/src
2301_81045437/classic-platform
datastructures/Safety_Queue/SafeQ.mod.mk
Makefile
unknown
168
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef SAFETY_QUEUE_H_ #define SAFETY_QUEUE_H_ #include <stddef.h> #include "Os.h" #include "Crc.h" #include "Std_Types.h" /* * Used to guard against multiple queue imports */ #ifndef QUEUE_DEFS typedef uint8 Queue_ReturnType; /* @req ARC_SWS_SafeQueue_00012*/ #define QUEUE_E_OK (Queue_ReturnType)0u #define QUEUE_E_TRUE (Queue_ReturnType)1u #define QUEUE_E_NO_INIT (Queue_ReturnType)2u #define QUEUE_E_FULL (Queue_ReturnType)130u #define QUEUE_E_NO_DATA (Queue_ReturnType)131u #define QUEUE_E_LOST_DATA (Queue_ReturnType)5u #define QUEUE_E_NO_CONTAINS (Queue_ReturnType)7u #define QUEUE_E_ALREADY_INIT (Queue_ReturnType)8u #define QUEUE_E_FALSE (Queue_ReturnType)9u #define QUEUE_E_NULL (Queue_ReturnType)10u /* @req ARC_SWS_SafeQueue_00009*/ /* Compare function for contains */ typedef int (*cmpFunc)(void *, void *, size_t); #define QUEUE_DEFS #endif /* QUEUE_DEFS */ #define QUEUE_E_CRC_ERR (Queue_ReturnType)6u #ifndef MEMCPY #if defined(__GNUC__) #define MEMCPY(_x,_y,_z) __builtin_memcpy(_x,_y,_z) #else #include <string.h> #define MEMCPY(_x,_y,_z) memcpy(_x,_y,_z) #endif #endif typedef struct safety_queue { /* The max number of elements in the list */ uint8 max_count; uint8 count; /* Error flag */ boolean bufFullFlag; /* If queue is initiated */ boolean isInit; /* Size of the elements in the list */ size_t dataSize; /* List head and tail */ void *head; void *tail; /* Buffer start/stop */ void *bufStart; void *bufEnd; /* Function pointer to compare function */ cmpFunc compare_func; /* CRC Value, one for the buffer and one for the queue struct */ uint8 bufferCrc; uint8 queueCrc; } Safety_Queue_t; /** * @brief Initiates the queue * * @param queue Address of the queue to be initialized with Safety_Queue_Init() * The queue must be declared as a reference, not just a pointer. * @param buffer Char[] allocated data where the actual contents of the queue should reside. * @param max_count Maximum number of elements that the queue can contain * @param dataSize The size of each element in the queue. * @param compare_func Pointer to a function that has the signature int (*cmpFunc)(void *, void *, size_t). * Used for comparing elements in the queue * * @return QUEUE_E_OK - if successfully initialized. * @return QUEUE_E_ALREADY_INIT - queue already initiated */ Queue_ReturnType Safety_Queue_Init(Safety_Queue_t *queue, void *buffer, uint8 max_count, size_t dataSize, cmpFunc compare_func); /** * @brief Add an element to the queue * * @param queue Address of the queue that has been initialized with Safety_Queue_Init() * @param dataPtr Pointer to the data that is to be added * * @return QUEUE_E_OK - if successfully added. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Safety_Queue_Init() * @return QUEUE_E_CRC_ERR - CRC error indicates that the memory the queue resides in was compromised. * @return QUEUE_E_FULL - Queue is full. */ Queue_ReturnType Safety_Queue_Add(Safety_Queue_t *queue, void const *dataPtr); /** * @brief Get next entry from the queue. This removes the item from the queue. * * @param queue Pointer to the queue that has been initialized with Safety_Queue_Init() * @param dataPtr Reference to a variable which will hold the result data * * @return QUEUE_E_OK - if successfully popped. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Safety_Queue_Init() * @return QUEUE_E_NO_DATA - nothing popped (it was empty) * @return QUEUE_E_CRC_ERR - CRC error indicates that the memory the queue resides in was compromised. * @return QUEUE_E_LOST_DATA - if a buffer overflow has occurred previously */ Queue_ReturnType Safety_Queue_Next(Safety_Queue_t *queue, void *dataPtr); /** * @brief Peek (i.e lookup) the next element in the queue. This does not alter the queue. * * @param queue Pointer to the queue that has been initialized with Safety_Queue_Init() * @param dataPtr Reference to a variable which will hold the result data * * @return QUEUE_E_OK - if successfully peeked. * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Safety_Queue_Init() * @return QUEUE_E_NO_DATA - nothing to peek at (it was empty) * @return QUEUE_E_CRC_ERR - CRC error indicates that the memory the queue resides in was compromised. * @return QUEUE_E_LOST_DATA - if a buffer overflow has occurred previously */ Queue_ReturnType Safety_Queue_Peek(Safety_Queue_t const *queue, void *dataPtr); /** * @brief Looks through the queue after element dataPtr points to using its compare_func. * * @param queue Pointer to the queue that has been initialized with Safety_Queue_Init() * @param dataPtr Reference to a variable which will hold the element it will look for using its compare_func * * @return QUEUE_E_TRUE - if queue contains the element * @return QUEUE_E_NO_INIT - the queue pointed to has not been initiated by Safety_Queue_Init() * @return QUEUE_E_NO_DATA - nothing to peek at (it was empty) * @return QUEUE_E_CRC_ERR - CRC error indicates that the memory the queue resides in was compromised. * @return QUEUE_E_FALSE - if the element could not be found in the queue */ Queue_ReturnType Safety_Queue_Contains(Safety_Queue_t const *queue, void const *dataPtr); #endif /* SAFETY_QUEUE_H_ */
2301_81045437/classic-platform
datastructures/Safety_Queue/inc/Safety_Queue.h
C
unknown
6,791
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Safety_Queue.h" /* @req ARC_SWS_SafeQueue_00010 The queue shall use FIFO order*/ /* @req ARC_SWS_SafeQueue_00011 The queue shall handle any type specified by user*/ /* @req ARC_SWS_SafeQueue_00013 The files shall be named Safety_Queue.c and Safety_Queue.h*/ /* @req ARC_SWS_SafeQueue_00014 The safety queue shall not use native C types*/ /* @req ARC_SWS_SafeQueue_00015 The safety queue shall be ready to be invoked at any moment*/ /* @req ARC_SWS_SafeQueue_00016 The safety queue shall not call any BSW modules functions*/ /* * A circular buffer implementation of FIFO queue.* */ /* @req ARC_SWS_SafeQueue_00004*/ /*lint -e{9016} MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.45, advisory]*/ Queue_ReturnType Safety_Queue_Init(Safety_Queue_t *queue, void *buffer, uint8 max_count, size_t dataSize, cmpFunc compare_func) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (buffer == NULL_PTR) || (compare_func == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit == TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_ALREADY_INIT; } queue->bufStart = buffer; /*lint -e970 MISRA:OTHER:argument check:[MISRA 2012 Directive 4.6, advisory]*/ queue->bufEnd = (char *) buffer + (max_count * dataSize); /*lint !e960 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2004 Info, advisory]*/ queue->head = queue->bufStart; queue->tail = queue->bufStart; queue->dataSize = dataSize; queue->count = 0u; queue->max_count = max_count; queue->compare_func = *compare_func; queue->bufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); queue->isInit = TRUE; /*lint -e928 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 11.5, advisory]*/ /*lint -e926 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 11.5, advisory]*/ /*lint -e946 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 18.3, required]*/ /*lint -e960 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ /*lint -e947 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 18.3, required]*/ /*lint -e732 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ size_t without_buffer_size = (char*) &(queue->queueCrc) - (char*) queue; queue->queueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 0u); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_SafeQueue_00005*/ Queue_ReturnType Safety_Queue_Add(Safety_Queue_t *queue, void const *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; /* Faulty pointer into method */ } /* @req ARC_SWS_SafeQueue_00002*/ uint8 currBufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); size_t without_buffer_size = (char*) &(queue->queueCrc) - (char*) queue; /*lint !e970 MISRA:OTHER:Pointer arithmetic:[MISRA 2012 Directive 4.6, advisory]*/ uint8 currQueueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 0u); /* @req ARC_SWS_SafeQueue_00001*/ if ((queue->bufferCrc != currBufferCrc) || (queue->queueCrc != currQueueCrc)) { SYS_CALL_ResumeOSInterrupts(); /* @req ARC_SWS_SafeQueue_00003*/ /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_CRC_ERR; } //Queue is full if (queue->count == queue->max_count) { queue->bufFullFlag = TRUE; //Update CRC values queue->queueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 1u); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_FULL; } MEMCPY(queue->head, dataPtr, queue->dataSize); /*lint -e{970} MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Directive 4.6, advisory]*/ queue->head = (char *) queue->head + queue->dataSize; /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ //Wrap-around if (queue->head == queue->bufEnd) { queue->head = queue->bufStart; } queue->count++; //Update CRC values queue->bufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); queue->queueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 1u); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_SafeQueue_00006*/ Queue_ReturnType Safety_Queue_Next(Safety_Queue_t *queue, void *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; /* Faulty pointer into method */ } if (queue->count == 0u) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } //CRC check uint8 currBufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); /*lint -e970 MISRA:OTHER:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Directive 4.6, advisory]*/ /*lint -e928 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 11.5, advisory]*/ /*lint -e926 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 11.5, advisory]*/ /*lint -e946 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 18.3, required]*/ /*lint -e960 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ /*lint -e947 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Rule 18.3, required]*/ /*lint -e732 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ size_t without_buffer_size = (char*) &(queue->queueCrc) - (char*) queue; uint8 currQueueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 0u); if ((queue->bufferCrc != currBufferCrc) || (queue->queueCrc != currQueueCrc)) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_CRC_ERR; } MEMCPY((void*) dataPtr, queue->tail, queue->dataSize); /*lint !e9005 MISRA:PERFORMANCE:casting away const is okay:[MISRA 2012 Rule 11.8, required]*/ /*lint -e970 MISRA:OTHER:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Directive 4.6, advisory]*/ /*lint -e{9016} MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2004 Info,advisory]*/ queue->tail = (char *) queue->tail + queue->dataSize; /*lint !e960 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2004 Info,advisory]*/ if (queue->tail == queue->bufEnd) { queue->tail = queue->bufStart; } --queue->count; if (queue->bufFullFlag == TRUE) { queue->bufFullFlag = FALSE; //Update CRC values queue->queueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 1u); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_LOST_DATA; } queue->bufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); queue->queueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 1u); SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_SafeQueue_00007*/ Queue_ReturnType Safety_Queue_Peek(Safety_Queue_t const *queue, void *dataPtr) { SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; } //CRC check uint8 currBufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); /*lint -e9005 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ size_t without_buffer_size = (char*) &(queue->queueCrc) - (char*) queue; uint8 currQueueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 0u); if ((queue->bufferCrc != currBufferCrc) || (queue->queueCrc != currQueueCrc)) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_CRC_ERR; } if (queue->count == 0u) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } MEMCPY((void*) dataPtr, queue->tail, queue->dataSize); /*lint !e9005 MISRA:PERFORMANCE:casting away const is okay:[MISRA 2012 Rule 11.8, required]*/ SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_OK; } /* @req ARC_SWS_SafeQueue_00008*/ Queue_ReturnType Safety_Queue_Contains(Safety_Queue_t const *queue, void const *dataPtr) { uint32 i; /*lint !e970 LINT:OTHER:pointer declaration:[MISRA 2012 Directive 4.6, advisory]*/ char *iter; SYS_CALL_SuspendOSInterrupts(); if ((queue == NULL_PTR) || (dataPtr == NULL_PTR)) { SYS_CALL_ResumeOSInterrupts(); /*lint -e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ return QUEUE_E_NULL; } if (queue->isInit != TRUE) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_INIT; } //CRC check uint8 currBufferCrc = Crc_CalculateCRC8(queue->bufStart, queue->dataSize * queue->max_count, 0u, 1u); /*lint -e9005 MISRA:PERFORMANCE:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2004 Info, advisory]*/ size_t without_buffer_size = (char*) &(queue->queueCrc) - (char*) queue; uint8 currQueueCrc = Crc_CalculateCRC8((void*) queue, without_buffer_size, 0u, 0u); /*lint !e9005 MISRA:PERFORMANCE:casting away const is okay:[MISRA 2012 Rule 11.8, required]*/ if ((queue->bufferCrc != currBufferCrc) || (queue->queueCrc != currQueueCrc)) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_CRC_ERR; } if (queue->count == 0u) { SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_NO_DATA; } iter = queue->tail; //Loop through queue for (i = 0u; i < queue->count; i++) { /*lint !e970 MISRA:OTHER:Need pointer arithmetic to determine size of struct - crc value:[MISRA 2012 Directive 4.6, advisory]*/ /*lint !e904 MISRA:OTHER:Validation of parameters, if failure, function will return.This is not inline with Table 8, ISO26262-6-2011, Req 1a:[MISRA 2012 Rule 15.5, advisory]*/ if (queue->compare_func(iter, (void*) dataPtr, queue->dataSize) == 0) { /*lint !e9005 MISRA:PERFORMANCE:casting away const is okay:[MISRA 2012 Rule 11.8, required]*/ SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_TRUE; } iter = iter + queue->dataSize; /*lint !e9016 MISRA:OTHER:correct arithmetic even if Array index is not used:[MISRA 2012 Rule 18.4, advisory]*/ } SYS_CALL_ResumeOSInterrupts(); return QUEUE_E_FALSE; }
2301_81045437/classic-platform
datastructures/Safety_Queue/src/Safety_Queue.c
C
unknown
13,887
#Dcm obj-$(USE_DCM) += Dcm.o obj-$(USE_DCM) += Dcm_Dsp.o obj-$(USE_DCM) += Dcm_Dsd.o obj-$(USE_DCM) += Dcm_Dsl.o obj-$(USE_DCM) += Dcm_ROE.o obj-$(USE_DCM) += Dcm_Internal.o obj-$(USE_DCM) += Dcm_LCfg.o ifeq ($(filter Dcm_Callout_Stubs.o,$(obj-y)),) obj-$(USE_DCM) += Dcm_Callout_Stubs.o endif inc-$(USE_DCM) += $(ROOTDIR)/diagnostic/Dcm/inc inc-$(USE_DCM) += $(ROOTDIR)/diagnostic/Dcm/src vpath-$(USE_DCM) += $(ROOTDIR)/diagnostic/Dcm/src
2301_81045437/classic-platform
diagnostic/Dcm/Dcm.mod.mk
Makefile
unknown
454
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DCM_H_ #define DCM_H_ #define DCM_AR_RELEASE_MAJOR_VERSION 4u #define DCM_AR_RELEASE_MINOR_VERSION 0u #define DCM_AR_RELEASE_REVISION_VERSION 3u #define DCM_MODULE_ID 53u /* @req DCM052 */ #define DCM_VENDOR_ID 60u #define DCM_SW_MAJOR_VERSION 8u #define DCM_SW_MINOR_VERSION 7u #define DCM_SW_PATCH_VERSION 0u #define DCM_AR_MAJOR_VERSION DCM_AR_RELEASE_MAJOR_VERSION #define DCM_AR_MINOR_VERSION DCM_AR_RELEASE_MINOR_VERSION #define DCM_AR_PATCH_VERSION DCM_AR_RELEASE_REVISION_VERSION #include "Dcm_Types.h"/* @!req DCM750 Dcm_Types.h includes Rte_Dcm_Type.h */ #include "Dcm_Cfg.h" #include "Dcm_Lcfg.h"/* !req DCM549 */ #include "ComStack_Types.h" #include "Dcm_Cbk.h" #if (DCM_DEV_ERROR_DETECT == STD_ON) // Error codes produced by this module defined by Autosar #define DCM_E_INTERFACE_TIMEOUT 0x01u #define DCM_E_INTERFACE_VALUE_OUT_OF_RANGE 0x02u #define DCM_E_INTERFACE_BUFFER_OVERFLOW 0x03u #define DCM_E_INTERFACE_PROTOCOL_MISMATCH 0x04u #define DCM_E_UNINIT 0x05u #define DCM_E_PARAM 0x06u // Other error codes reported by this module #define DCM_E_CONFIG_INVALID 0x40u #define DCM_E_TP_LENGTH_MISMATCH 0x50u #define DCM_E_UNEXPECTED_RESPONSE 0x60u #define DCM_E_UNEXPECTED_EXECUTION 0x61u #define DCM_E_INTEGRATION_ERROR 0x62u #define DCM_E_WRONG_BUFFER 0x63u #define DCM_E_NOT_SUPPORTED 0xfeu #define DCM_E_NOT_IMPLEMENTED_YET 0xffu // Service IDs in this module defined by Autosar #define DCM_START_OF_RECEPTION_ID 0x00u #define DCM_INIT_ID 0x01u #define DCM_COPY_RX_DATA_ID 0x02u #define DCM_TP_RX_INDICATION_ID 0x03u #define DCM_COPY_TX_DATA_ID 0x04u #define DCM_TP_TX_CONFIRMATION_ID 0x05u #define DCM_GET_SES_CTRL_TYPE_ID 0x06u #define DCM_GET_SECURITY_LEVEL_ID 0x0du #define DCM_GET_ACTIVE_PROTOCOL_ID 0x0fu #define DCM_COMM_NO_COM_MODE_ENTERED_ID 0x21u #define DCM_COMM_SILENT_COM_MODE_ENTERED_ID 0x22u #define DCM_COMM_FULL_COM_MODE_ENTERED_ID 0x23u #define DCM_MAIN_ID 0x25u #define DCM_RESETTODEFAULTSESSION_ID 0x2au #define DCM_EXTERNALSETNEGRESPONSE_ID 0x30u #define DCM_EXTERNALPROCESSINGDONE_ID 0x31u // Other service IDs reported by this module #define DCM_HANDLE_RESPONSE_TRANSMISSION_ID 0x80u #define DCM_UDS_READ_DTC_INFO_ID 0x81u #define DCM_UDS_RESET_ID 0x82u #define DCM_UDS_COMMUNICATION_CONTROL_ID 0x83u #define DCM_CHANGE_DIAGNOSTIC_SESSION_ID 0x88u #define DCM_GLOBAL_ID 0xffu #endif /* * Interfaces for BSW components (8.3.1) */ #if ( DCM_VERSION_INFO_API == STD_ON ) /* @req DCM337 */ /* @req DCM065 */ /* @req DCM335 */ /* @req DCM336 */ #define Dcm_GetVersionInfo(_vi) STD_GET_VERSION_INFO(_vi,DCM) #endif /* DCM_VERSION_INFO_API */ void Dcm_Init( const Dcm_ConfigType *ConfigPtr ); /* @req DCM037 */ /* * Interfaces for BSW modules and to SW-Cs (8.3.2) */ Std_ReturnType Dcm_GetSecurityLevel(Dcm_SecLevelType *secLevel); /* @req DCM338 */ Std_ReturnType Dcm_GetSesCtrlType(Dcm_SesCtrlType *sesCtrlType); /* @req DCM339 */ Std_ReturnType Dcm_GetActiveProtocol(Dcm_ProtocolType *activeProtocol); /* @req DCM340 */ Std_ReturnType Dcm_ResetToDefaultSession( void ); /* @req DCM520 */ #ifdef DCM_USE_SERVICE_RESPONSEONEVENT /* Response on Event related functions */ Std_ReturnType Dcm_TriggerOnEvent(uint8 RoeEventId); /* @req DCM521 */ Std_ReturnType Dcm_StopROE(void); /* @req DCM730 May return E_NOT_OK when no RxPduId has been saved */ Std_ReturnType Dcm_RestartROE(void); /* @req DCM731 */ Std_ReturnType Dcm_Arc_AddDataIdentifierEvent(uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength); void Dcm_Arc_InitROEBlock(void); Std_ReturnType Dcm_Arc_GetROEPreConfig(const Dcm_ArcROEDidPreconfigType **ROEPreConfigPtr); #endif /* * Interface for basic software scheduler (8.5) */ void Dcm_MainFunction( void ); /* @req DCM053 */ /* * Dcm callouts. */ Dcm_ReturnWriteMemoryType Dcm_WriteMemory(Dcm_OpStatusType OpStatus, uint8 MemoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8* MemoryData); Dcm_ReturnReadMemoryType Dcm_ReadMemory(Dcm_OpStatusType OpStatus, uint8 MemoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8* MemoryData); void Dcm_Arc_CommunicationControl(uint8 subFunction, uint8 communicationType, Dcm_NegativeResponseCodeType *responseCode ); Std_ReturnType Dcm_ProcessRequestDownload(Dcm_OpStatusType OpStatus, uint8 DataFormatIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint32 *BlockLength, Dcm_NegativeResponseCodeType* ErrorCode); Std_ReturnType Dcm_ProcessRequestUpload(Dcm_OpStatusType OpStatus, uint8 DataFormatIdentifier, uint32 MemoryAddress, uint32 MemorySize, Dcm_NegativeResponseCodeType* ErrorCode); Std_ReturnType Dcm_ProcessRequestTransferExit(Dcm_OpStatusType OpStatus, uint8 *ParameterRecord, uint32 ParameterRecordSize, Dcm_NegativeResponseCodeType* ErrorCode); void Dcm_Arc_GetDownloadResponseParameterRecord(uint8 *Data, uint16 *ParameterRecordLength); void Dcm_Arc_GetTransferExitResponseParameterRecord(uint8 *Data, uint16 *ParameterRecordLength); Std_ReturnType Dcm_SetProgConditions(Dcm_ProgConditionsType *ProgConditions); Dcm_EcuStartModeType Dcm_GetProgConditions(Dcm_ProgConditionsType * ProgConditions); void Dcm_Confirmation(Dcm_IdContextType idContext,PduIdType dcmRxPduId,Dcm_ConfirmationStatusType status); /* External diagnostic service processing */ void Dcm_ExternalSetNegResponse(Dcm_MsgContextType* pMsgContext, Dcm_NegativeResponseCodeType ErrorCode); void Dcm_ExternalProcessingDone(Dcm_MsgContextType* pMsgContext); #ifdef DCM_NOT_SERVICE_COMPONENT Std_ReturnType Rte_Switch_DcmEcuReset_DcmEcuReset(Dcm_EcuResetType resetType); Std_ReturnType Rte_Switch_DcmDiagnosticSessionControl_DcmDiagnosticSessionControl(Dcm_SesCtrlType session); Std_ReturnType Rte_Switch_DcmControlDTCSetting_DcmControlDTCSetting(uint8 mode); #endif #endif /*DCM_H_*/
2301_81045437/classic-platform
diagnostic/Dcm/inc/Dcm.h
C
unknown
7,007
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DCM_CBK_H_ #define DCM_CBK_H_ //lint -e451 //451 PC-Lint OK. Sl� av regel helt? #include "ComStack_Types.h" /* * Interfaces for callback notifications from PduR and ComM (8.4) */ BufReq_ReturnType Dcm_CopyRxData(PduIdType dcmRxPduId, PduInfoType *pduInfoPtr, PduLengthType *rxBufferSizePtr); /** @req DCM556 */ BufReq_ReturnType Dcm_StartOfReception(PduIdType dcmRxPduId, PduLengthType tpSduLength, PduLengthType *rxBufferSizePtr); /** @req DCM094 */ void Dcm_TpRxIndication(PduIdType dcmRxPduId, NotifResultType result); /** @req DCM093 */ BufReq_ReturnType Dcm_CopyTxData(PduIdType dcmTxPduId, PduInfoType *pduInfoPtr, RetryInfoType *retryInfoPtr, PduLengthType *txDataCntPtr); /** @req DCM092 */ void Dcm_TpTxConfirmation(PduIdType dcmTxPduId, NotifResultType result); /** @req DCM351 */ void Dcm_ComM_NoComModeEntered( uint8 NetworkId ); /** @req DCM356 */ void Dcm_ComM_SilentComModeEntered( uint8 NetworkId ); /** @req DCM358 */ void Dcm_ComM_FullComModeEntered( uint8 NetworkId ); /** @req DCM360 */ #endif /*DCM_CBK_H_*/
2301_81045437/classic-platform
diagnostic/Dcm/inc/Dcm_Cbk.h
C
unknown
1,834
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DCM_LCFG_H_ #define DCM_LCFG_H_ /* * General requirements */ /** @req 3.1.5/DCM075 */ /** @req 3.1.5/DCM076 */ #include "ComStack_Types.h" #include "Dcm_Types.h" #if defined(USE_NVM) #include "NvM.h" #endif typedef uint8 Dcm_ProtocolTransTypeType; #define DCM_PROTOCOL_TRANS_TYPE_1 1u #define DCM_PROTOCOL_TRANS_TYPE_2 2u typedef uint8 Dcm_ProtocolAddrTypeType; #define DCM_PROTOCOL_FUNCTIONAL_ADDR_TYPE 1u #define DCM_PROTOCOL_PHYSICAL_ADDR_TYPE 2u #define DCM_PROTOCAL_TP_MAX_LENGTH 0x1000u #define DCM_INVALID_PDU_ID 0xFFFFu /* * Callback function prototypes */ // SessionControl typedef Std_ReturnType (*Dcm_CallbackGetSesChgPermissionFncType)(Dcm_SesCtrlType sesCtrlTypeActive, Dcm_SesCtrlType sesCtrlTypeNew); typedef Std_ReturnType (*Dcm_CallbackChangeIndicationFncType)(Dcm_SesCtrlType sesCtrlTypeOld, Dcm_SesCtrlType sesCtrlTypeNew); typedef Std_ReturnType (*Dcm_CallbackConfirmationRespPendFncType)(Dcm_ConfirmationStatusType status); // SecurityAccess_<LEVEL> typedef Std_ReturnType (*Dcm_CallbackGetSeedFncTypeWithRecord)(const uint8 *securityAccessDataRecord, Dcm_OpStatusType OpStatus, uint8 *seed, Dcm_NegativeResponseCodeType *errorCode); typedef Std_ReturnType (*Dcm_CallbackGetSeedFncTypeWithoutRecord)(Dcm_OpStatusType OpStatus, uint8 *seed, Dcm_NegativeResponseCodeType *errorCode); typedef union { Dcm_CallbackGetSeedFncTypeWithRecord getSeedWithRecord; Dcm_CallbackGetSeedFncTypeWithoutRecord getSeedWithoutRecord; }Dcm_CallbackGetSeedFncType; typedef Std_ReturnType (*Dcm_CallbackCompareKeyFncType)(const uint8 *key, Dcm_OpStatusType OpStatus); // PidServices_<PID> typedef Std_ReturnType (*Dcm_CallbackGetPIDValueFncType)(uint8 *dataValueBuffer); // DidServices_<DID> typedef Std_ReturnType (*Dcm_SynchCallbackReadDataFncType)(uint8 *data);/* @req DCM793 */ typedef Std_ReturnType (*Dcm_AsynchCallbackReadDataFncType)(Dcm_OpStatusType OpStatus, uint8 *data); typedef Std_ReturnType (*Dcm_FixLenCallbackWriteDataFncType)(const uint8 *data, Dcm_OpStatusType opStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM794 */ typedef Std_ReturnType (*Dcm_DynLenCallbackWriteDataFncType)(const uint8 *data, uint16 dataLength, Dcm_OpStatusType opStatus, Dcm_NegativeResponseCodeType *errorCode); typedef Std_ReturnType (*Dcm_CallbackReadDataLengthFncType)(uint16 *didLength);/* @req DCM796 */ typedef Std_ReturnType (*Dcm_CallbackConditionCheckReadFncType)(Dcm_OpStatusType OpStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM797 */ typedef Std_ReturnType (*Dcm_FuncCallbackReturnControlToECUFncType)(Dcm_OpStatusType OpStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM799 */ typedef Std_ReturnType (*Dcm_FuncCallbackResetToDefaultFncType)(Dcm_OpStatusType OpStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM800 */ typedef Std_ReturnType (*Dcm_FuncCallbackFreezeCurrentStateFncType)(Dcm_OpStatusType OpStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM801 */ typedef Std_ReturnType (*Dcm_FuncCallbackShortTermAdjustmentFncType)(const uint8 *controlOptionRecord, Dcm_OpStatusType OpStatus, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM802 */ typedef Std_ReturnType (*Dcm_EcuSignalCallbackReturnControlToECUFncType)(uint8 action, uint8 *controlOptionRecord); typedef Std_ReturnType (*Dcm_EcuSignalCallbackResetToDefaultFncType)(uint8 action, uint8 *controlOptionRecord); typedef Std_ReturnType (*Dcm_EcuSignalCallbackFreezeCurrentStateFncType)(uint8 action, uint8 *controlOptionRecord); typedef Std_ReturnType (*Dcm_EcuSignalCallbackShortTermAdjustmentFncType)(uint8 action, uint8 *controlOptionRecord); typedef Std_ReturnType (*Dcm_SRCallbackReadDataFncType)(void *data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_UINT8_DataFncType)(uint8 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_SINT8_DataFncType)(sint8 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_UINT16_DataFncType)(uint16 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_SINT16_DataFncType)(sint16 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_UINT32_DataFncType)(uint32 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_SINT32_DataFncType)(sint32 data); typedef Std_ReturnType (*Dcm_SRCallbackWrite_BOOLEAN_DataFncType)(boolean data); typedef Std_ReturnType (*Dcm_RoeActivateCallbackFncType)(uint8 RoeEventId, Dcm_RoeStateType state); typedef Std_ReturnType (*Dcm_CallbackGetScalingInformationFncType)(Dcm_OpStatusType OpStatus, uint8 *scalingInfo, Dcm_NegativeResponseCodeType *errorCode);/* @req DCM798 */ // InfoTypeServices_<INFOTYPENUMBER> typedef Std_ReturnType (*Dcm_CallbackGetInfoTypeValueFncType)(uint8 *dataValueBuffer); // DTRServices typedef Std_ReturnType (*Dcm_CallbackGetDTRValueFncType)(Dcm_OpStatusType OpStatus,uint16 *Testval, uint16 *Minlimit, uint16 *Maxlimit, uint8* Status); // RoutineServices_<ROUTINENAME> typedef Std_ReturnType (*Dcm_CallbackStartRoutineFncType)(uint8 *indata, Dcm_OpStatusType OpStatus, uint8 *outdata, uint16* currentDataLength, Dcm_NegativeResponseCodeType *errorCode, boolean changeEndianess); typedef Std_ReturnType (*Dcm_CallbackStopRoutineFncType)(uint8 *indata, Dcm_OpStatusType OpStatus, uint8 *outdata, uint16* currentDataLength, Dcm_NegativeResponseCodeType *errorCode, boolean changeEndianess); typedef Std_ReturnType (*Dcm_CallbackRequestResultRoutineFncType)(Dcm_OpStatusType OpStatus, uint8 *outdata, uint16* currentDataLength, Dcm_NegativeResponseCodeType *errorCode, boolean changeEndianess); // RequestControlServices_<TID> typedef Std_ReturnType (*Dcm_CallbackRequestControlType)(uint8 *outBuffer, uint8 *inBuffer); // CallBackDCMRequestServices typedef Std_ReturnType (*Dcm_CallbackStartProtocolFncType)(Dcm_ProtocolType protocolID); typedef Std_ReturnType (*Dcm_CallbackStopProtocolFncType)(Dcm_ProtocolType protocolID); // ServiceRequestIndication typedef Std_ReturnType (*Dcm_CallbackNotificationIndicationFncType)(uint8 SID, const uint8* requestData, uint16 dataSize, uint8 reqType, uint16 soruceAddress, Dcm_NegativeResponseCodeType* ErrorCode); typedef Std_ReturnType (*Dcm_CallbackNotificationConfirmationFncType)(uint8 SID, uint8 reqType, uint16 sourceAddress, Dcm_ConfirmationStatusType status); // ResetService typedef Std_ReturnType (*Dcm_CallbackEcuResetType)(uint8 resetType, Dcm_NegativeResponseCodeType *errorCode); //OBD service 0x04 condition check callback typedef Std_ReturnType (*Dcm_DsdConditionGetFncType)(void); typedef Std_ReturnType (*Dcm_DsdResetPidsFncType)(void); typedef Std_ReturnType (*Dcm_DsdDspSidTabFncType)(Dcm_OpStatusType OpStatus, Dcm_MsgContextType* pMsgContext);/* @req DCM763 */ typedef Std_ReturnType (*Dcm_ComControlModeSwitchFcnType)(uint8 mode); typedef enum { DATA_PORT_NO_PORT, DATA_PORT_BLOCK_ID, DATA_PORT_ASYNCH, DATA_PORT_SYNCH, DATA_PORT_ECU_SIGNAL, DATA_PORT_SR }Dcm_DataPortType; typedef union { Dcm_SynchCallbackReadDataFncType SynchDataReadFnc; // (0..1) Dcm_AsynchCallbackReadDataFncType AsynchDataReadFnc; // (0..1) Dcm_SRCallbackReadDataFncType SRDataReadFnc; } Dcm_CallbackReadDataFncType; typedef union { Dcm_FixLenCallbackWriteDataFncType FixLenDataWriteFnc; // (0..1) Dcm_DynLenCallbackWriteDataFncType DynLenDataWriteFnc; // (0..1) Dcm_SRCallbackWrite_UINT8_DataFncType SRDataWriteFnc_UINT8; Dcm_SRCallbackWrite_SINT8_DataFncType SRDataWriteFnc_SINT8; Dcm_SRCallbackWrite_UINT16_DataFncType SRDataWriteFnc_UINT16; Dcm_SRCallbackWrite_SINT16_DataFncType SRDataWriteFnc_SINT16; Dcm_SRCallbackWrite_UINT32_DataFncType SRDataWriteFnc_UINT32; Dcm_SRCallbackWrite_SINT32_DataFncType SRDataWriteFnc_SINT32; Dcm_SRCallbackWrite_BOOLEAN_DataFncType SRDataWriteFnc_BOOLEAN; } Dcm_CallbackWriteDataFncType; typedef union { Dcm_FuncCallbackResetToDefaultFncType FuncResetToDefaultFnc; // (0..1) Dcm_EcuSignalCallbackResetToDefaultFncType EcuSignalResetToDefaultFnc; // (0..1) } Dcm_CallbackResetToDefaultFncType; typedef union { Dcm_FuncCallbackReturnControlToECUFncType FuncReturnControlToECUFnc; // (0..1) Dcm_EcuSignalCallbackReturnControlToECUFncType EcuSignalReturnControlToECUFnc; // (0..1) } Dcm_CallbackReturnControlToECUFncType; typedef union { Dcm_FuncCallbackShortTermAdjustmentFncType FuncShortTermAdjustmentFnc; // (0..1) Dcm_EcuSignalCallbackShortTermAdjustmentFncType EcuSignalShortTermAdjustmentFnc; // (0..1) } Dcm_CallbackShortTermAdjustmentFncType; typedef union { Dcm_FuncCallbackFreezeCurrentStateFncType FuncFreezeCurrentStateFnc; // (0..1) Dcm_EcuSignalCallbackFreezeCurrentStateFncType EcuSignalFreezeCurrentStateFnc; // (0..1) } Dcm_CallbackFreezeCurrentStateFncType; /* * DCM configurations */ /******* * DSP * *******/ typedef enum { DCM_NO_BOOT, DCM_OEM_BOOT, DCM_SYS_BOOT, DCM_OEM_BOOT_RESPAPP, DCM_SYS_BOOT_RESPAPP }Dcm_DspSessionForBootType; // 10.2.44 typedef struct { uint32 DspSessionP2ServerMax; // (1) uint32 DspSessionP2StarServerMax; // (1) Dcm_SesCtrlType DspSessionLevel; // (1) Dcm_SesCtrlType ArcDspRteSessionLevelName; Dcm_DspSessionForBootType DspSessionForBoot; boolean Arc_EOL; } Dcm_DspSessionRowType; // 10.2.42 typedef struct { uint32 DspSecurityADRSize; // (0..1) uint32 DspSecurityDelayTimeOnBoot; // (1) uint32 DspSecurityDelayTime; // (1) Dcm_SecLevelType DspSecurityLevel; // (1) uint8 DspSecurityNumAttDelay; // (1) uint8 DspSecurityNumAttLock; // (1) uint8 DspSecuritySeedSize; // (1) uint8 DspSecurityKeySize; // (1) Dcm_CallbackGetSeedFncType GetSeed; Dcm_CallbackCompareKeyFncType CompareKey; boolean Arc_EOL; } Dcm_DspSecurityRowType; // 10.2.26 typedef struct { const Dcm_DspSessionRowType * const *DspDidControlSessionRef; // (1..*) const Dcm_DspSecurityRowType * const *DspDidControlSecurityLevelRef; // (1..*) } Dcm_DspDidControlType; // 10.2.27 typedef struct { const Dcm_DspSessionRowType * const *DspDidReadSessionRef; // (1..*) const Dcm_DspSecurityRowType * const *DspDidReadSecurityLevelRef; // (1..*) } Dcm_DspDidReadType; // 10.2.28 typedef struct { const Dcm_DspSessionRowType * const *DspDidWriteSessionRef; // (1..*) const Dcm_DspSecurityRowType * const *DspDidWriteSecurityLevelRef; // (1..*) } Dcm_DspDidWriteType; /** @req DCM616 */ // 10.2.25 typedef struct { // Containers const Dcm_DspDidReadType *DspDidRead; // (0..1) const Dcm_DspDidWriteType *DspDidWrite; // (0..1) const Dcm_DspDidControlType *DspDidControl; // (0..1) } Dcm_DspDidAccessType; // 10.2.24 typedef struct { boolean DspDidDynamicllyDefined; // (1) // Containers Dcm_DspDidAccessType DspDidAccess; // (1) } Dcm_DspDidInfoType; typedef struct { boolean DspDidFixedLength; // (1) uint8 DspDidScalingInfoSize; // (0..1) }Dcm_DspDataInfoType; typedef enum { DCM_BIG_ENDIAN, DCM_LITTLE_ENDIAN, DCM_ENDIAN_NOT_USED }DcmDspDataEndianessType; typedef enum { DCM_BOOLEAN, DCM_UINT8, DCM_UINT16, DCM_UINT32, DCM_SINT8, DCM_SINT16, DCM_SINT32, DCM_UINT8_N }DcmDspDataType; typedef struct { const Dcm_DspDataInfoType *DspDataInfoRef; Dcm_CallbackReadDataLengthFncType DspDataReadDataLengthFnc; // (0..1) Dcm_CallbackConditionCheckReadFncType DspDataConditionCheckReadFnc; // (0..1) Dcm_CallbackReadDataFncType DspDataReadDataFnc; // (0..1) Dcm_CallbackWriteDataFncType DspDataWriteDataFnc; // (0..1) Dcm_CallbackGetScalingInformationFncType DspDataGetScalingInfoFnc; // (0..1) Dcm_CallbackFreezeCurrentStateFncType DspDataFreezeCurrentStateFnc; // (0..1) Dcm_CallbackResetToDefaultFncType DspDataResetToDefaultFnc; // (0..1) Dcm_CallbackReturnControlToECUFncType DspDataReturnControlToEcuFnc; // (0..1) Dcm_CallbackShortTermAdjustmentFncType DspDataShortTermAdjustmentFnc; // (0..1) Dcm_DataPortType DspDataUsePort; // (1) uint16 DspDataBitSize; #if defined(USE_NVM) NvM_BlockIdType DspNvmUseBlockID; #endif DcmDspDataType DspDataType; DcmDspDataEndianessType DspDataEndianess; }Dcm_DspDataType; typedef struct { const Dcm_DspDataType *DspSignalDataRef; const uint16 DspSignalBitPosition; }Dcm_DspSignalType; // 10.2.22 typedef struct Dcm_DspDidType { const Dcm_DspDidInfoType *DspDidInfoRef; // (1) const struct Dcm_DspDidType * const *DspDidRef; // (0..*) const Dcm_DspSignalType * const DspSignalRef; uint16 DspDidIdentifier; // (1) uint16 DspNofSignals; uint16 DspDidDataByteSize; uint16 DspDidDataScalingInfoSize; Dcm_RoeActivateCallbackFncType DspDidRoeActivateFnc; // (0..1) uint8 DspDidRoeEventId; // (0..1) // Containers boolean Arc_EOL; } Dcm_DspDidType; // 10.2.30 typedef struct { const Dcm_DspSessionRowType * const *DspEcuResetSessionRef; // (1..*) const Dcm_DspSecurityRowType * const *DspEcuResetSecurityLevelRef; // (1..*) } Dcm_DspEcuResetType; // 10.2.31 typedef struct { boolean DspPidUsePort; // (1) uint8 DspPidIdentifier; // (1) uint8 DspPidSize; // (1) Dcm_PidServiceType DspPidService; Dcm_CallbackGetPIDValueFncType DspGetPidValFnc; // (1) const boolean *Arc_DcmPidEnabled; // (0..1) boolean Arc_EOL; } Dcm_DspPidType; // 10.2.33 typedef struct { boolean DspDTCInfoSubFuncSupp; // (1) uint8 DspDTCInfoSubFuncLevel; // (1) const Dcm_DspSecurityRowType * const *DspDTCInfoSecLevelRef; // (1..*) } Dcm_DspReadDTCRowType; // 10.2.32 typedef struct { // Containers Dcm_DspReadDTCRowType *DspReadDTCRow; // (0..*) } Dcm_DspReadDTCType; // 10.2.34 typedef struct { uint8 DspRequestControl; // (1) uint8 DspRequestControlOutBufferSize; // (1) uint8 DspRequestControlTestId; // (1) } Dcm_DspRequestControlType; // 10.2.37 typedef struct { const Dcm_DspSessionRowType * const *DspRoutineSessionRef; // (1..*) const Dcm_DspSecurityRowType * const *DspRoutineSecurityLevelRef; // (1..*) } Dcm_DspRoutineAuthorizationType; /** @req DCM644 */ // 10.2.38 typedef struct { uint8 DspReqResRtnCtrlOptRecSize; // (1) } Dcm_DspRoutineRequestResType; // 10.2.39 typedef struct { uint8 DspStopRoutineCtrlOptRecSize; // (1) uint8 DspStopRoutineStsOptRecSize; // (1) } Dcm_DspRoutineStopType; // 10.2.40 typedef struct { uint32 DspStartRoutineCtrlOptRecSize; // (1) uint32 DspStartRoutineStsOptRecSize; // (1) } Dcm_DspStartRoutineType; // 10.2.36 typedef struct { // Containers const Dcm_DspRoutineAuthorizationType DspRoutineAuthorization; // (1) const Dcm_DspStartRoutineType *DspStartRoutine; // (1) const Dcm_DspRoutineStopType *DspRoutineStop; // (0..1) const Dcm_DspRoutineRequestResType *DspRoutineRequestRes; // (0..1) } Dcm_DspRoutineInfoType; // 10.2.35 typedef struct { boolean DspRoutineUsePort; // (1) uint16 DspRoutineIdentifier; // (1) const Dcm_DspRoutineInfoType *DspRoutineInfoRef; // (1) Dcm_CallbackStartRoutineFncType DspStartRoutineFnc; // (0..1) Dcm_CallbackStopRoutineFncType DspStopRoutineFnc; // (0..1) Dcm_CallbackRequestResultRoutineFncType DspRequestResultRoutineFnc; // (0..1) boolean Arc_EOL; } Dcm_DspRoutineType; // 10.2.41 typedef struct { // Containers const Dcm_DspSecurityRowType *DspSecurityRow; // (0..31) } Dcm_DspSecurityType; // 10.2.43 typedef struct { // Containers const Dcm_DspSessionRowType *DspSessionRow; // (0..31) } Dcm_DspSessionType; typedef struct { uint8 DspTestResultUaSid; // (1) uint8 DspTestResultTestId; // (1) /* Defined internally */ Dcm_CallbackGetDTRValueFncType DspGetDTRValueFnc; // (1) } Dcm_DspTestResultObdmidTidType; typedef struct { uint8 DspTestResultObdmid; // (1) uint8 DspTestResultTidSize; // (1) const Dcm_DspTestResultObdmidTidType *DspTestResultObdmidTidRef; // (1..*) boolean Arc_EOL; } Dcm_DspTestResultObdmidType; typedef struct { // Containers const Dcm_DspTestResultObdmidType *DspTestResultObdmidTid; // (1..*) } Dcm_DspTestResultByObdmidType; typedef struct { Dcm_CallbackGetInfoTypeValueFncType DspGetVehInfoTypeFnc; // (1) uint8 DspVehInfoSize; // (1) }Dcm_DspVehInfoDataType; // 10.2.48 typedef struct { const Dcm_DspVehInfoDataType *DspVehInfoDataItems; uint16 DspVehInfoTotalSize; uint8 DspVehInfoType; // (1) uint8 DspVehInfoNumberOfDataItems; boolean Arc_EOL; } Dcm_DspVehInfoType; // 10.2.21 typedef struct { uint32 MemoryAddressHigh; uint32 MemoryAddressLow; /*DcmDspMemoryRangeRuleRef * pRule;*/ const Dcm_DspSecurityRowType * const *pSecurityLevel; boolean Arc_EOL; } Dcm_DspMemoryRangeInfo; typedef struct { uint8 MemoryIdValue; const Dcm_DspMemoryRangeInfo *pReadMemoryInfo; const Dcm_DspMemoryRangeInfo *pWriteMemoryInfo; boolean Arc_EOL; } Dcm_DspMemoryIdInfo; typedef struct { boolean DcmDspUseMemoryId; const Dcm_DspMemoryIdInfo *DspMemoryIdInfo; }Dcm_DspMemoryType; typedef struct { uint8 ComMChannelIndex; boolean Arc_EOL; }Dcm_DspComControlAllChannelType; typedef struct { uint8 ComMChannelIndex; uint8 SubnetNumber; boolean Arc_EOL; }Dcm_DspComControlSpecificChannelType; typedef struct { const Dcm_DspComControlAllChannelType *DspControlAllChannel; const Dcm_DspComControlSpecificChannelType *DspControlSpecificChannel; }Dcm_DspComControlType; // 10.2.21 typedef struct { uint8 DspMaxDidToRead; // (0..1) // Containers const Dcm_DspDidType *DspDid; // (0..*) const Dcm_DspDidInfoType *DspDidInfo; // (0..*) const Dcm_DspEcuResetType *DspEcuReset; // (0..*) const Dcm_DspPidType *DspPid; // (0..*) const Dcm_DspReadDTCType *DspReadDTC; // (1) const Dcm_DspRequestControlType *DspRequestControl; // (0..*) const Dcm_DspRoutineType *DspRoutine; // (0..*) const Dcm_DspRoutineInfoType *DspRoutineInfo; // (0..*) const Dcm_DspSecurityType *DspSecurity; // (0..*) const Dcm_DspSessionType *DspSession; // (1) const Dcm_DspTestResultByObdmidType *DspTestResultByObdmid; // (1) const Dcm_DspVehInfoType *DspVehInfo; const Dcm_DspMemoryType *DspMemory; const Dcm_DspComControlType *DspComControl; } Dcm_DspType; /******* * DSD * *******/ typedef Std_ReturnType (*DsdSubServiceFncType)(Dcm_OpStatusType opStatus, Dcm_MsgContextType *msg);/* @req DCM764 */ typedef struct { uint8 DsdSubServiceId; DsdSubServiceFncType DsdSubServiceFnc; const Dcm_DspSecurityRowType * const *DsdSubServiceSecurityLevelRef; // (1..*) const Dcm_DspSessionRowType * const *DsdSubServiceSessionLevelRef; // (1..*) boolean Arc_EOL; } Dcm_DsdSubServiceType; // 10.2.4 DcmDsdService typedef struct { uint8 DsdSidTabServiceId; // (1) boolean DsdSidTabSubfuncAvail; // (1) const Dcm_DspSecurityRowType * const *DsdSidTabSecurityLevelRef; // (1..*) const Dcm_DspSessionRowType * const *DsdSidTabSessionLevelRef; // (1..*) // Containers Dcm_DsdDspSidTabFncType DspSidTabFnc; const Dcm_DsdSubServiceType *const DsdSubServiceList; boolean Arc_EOL; } Dcm_DsdServiceType; // 10.2.3 DcmDsdServiceTable typedef struct { uint8 DsdSidTabId; // (1) // Containers const Dcm_DsdServiceType *DsdService; // (1..*) boolean Arc_EOL; } Dcm_DsdServiceTableType; // 10.2.2 DcmDsd typedef struct { // Containers const Dcm_DsdServiceTableType *DsdServiceTable; // (1..256) } Dcm_DsdType; /******* * DSL * *******/ typedef enum { BUFFER_AVAILABLE, BUFFER_BUSY }Dcm_DslBufferStatusType; typedef enum { NOT_IN_USE, // The buffer is not used (it is available). IN_USE, PROVIDED_TO_PDUR, // The buffer is currently in use by PDUR. DSD_PENDING_RESPONSE_SIGNALED, // Signals have been received saying the buffer contain valid data. DCM_TRANSMIT_SIGNALED, // The DCM has been asked to transfer the response, system is now waiting for TP layer to reqest Tx buffer. PROVIDED_TO_DSD, // The buffer is currently in use by DSD. PREEMPT_TRANSMIT_NRC,//when preemption happens,then sent NRC 0x21 to OBD tester #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) PENDING_BUFFER_RELEASE, #endif UNDEFINED_USAGE }Dcm_DslBufferUserType; typedef struct { Dcm_DslBufferStatusType status; // Flag for buffer in use. PduLengthType nofBytesHandled; PduIdType DcmRxPduId; //The external buffer is locked to this PDU id #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) boolean dspProcessingActive;/* Flag indicating that a dsp processing is currently active and buffers can be accessed only by dsp */ #endif } Dcm_DslBufferRuntimeType; // 10.2.6 typedef struct { uint8 DslBufferID; // (1) // Kept for reference, will be removed (polite calls will be made). uint16 DslBufferSize; // (1) PduInfoType pduInfo; Dcm_DslBufferRuntimeType *externalBufferRuntimeData; } Dcm_DslBufferType; // 10.2.7 typedef struct { Dcm_CallbackStartProtocolFncType StartProtocol; Dcm_CallbackStopProtocolFncType StopProtocol; boolean Arc_EOL; } Dcm_DslCallbackDCMRequestServiceType; // 10.2.8 typedef struct { boolean DslDiagRespForceRespPendEn; // (1) uint8 DslDiagRespMaxNumRespPend; // (1) } Dcm_DslDiagRespType; // 10.2.18 typedef struct { // uint16 TimStrP2ServerMax; // (1) // uint16 TimStrP2ServerMin; // (1) uint32 TimStrP2ServerAdjust; // (1) uint32 TimStrP2StarServerAdjust; // (1) uint32 TimStrS3Server; // (1) const boolean Arc_EOL; } Dcm_DslProtocolTimingRowType; // 10.2.17 typedef struct { const Dcm_DslProtocolTimingRowType *DslProtocolTimingRow; // (0..*) } Dcm_DslProtocolTimingType; // 10.2.16 typedef uint8 Dcm_DslResponseOnEventType; /* Makes it possible to cross-reference structures. */ typedef struct Dcm_DslMainConnectionType_t Dcm_DslMainConnectionType; typedef struct Dcm_DslProtocolRxType_t Dcm_DslProtocolRxType; // 10.2.13 struct Dcm_DslProtocolRxType_t { const Dcm_DslMainConnectionType *DslMainConnectionParent; // (1) /* Cross reference. */ const Dcm_ProtocolAddrTypeType DslProtocolAddrType; // (1) const PduIdType DcmDslProtocolRxPduId; // (1) const uint8 ComMChannelInternalIndex; const boolean Arc_EOL; }; /* Makes it possible to cross-reference structures. */ //typedef struct Dcm_DslMainConnectionType_t Dcm_DslMainConnectionType; typedef struct Dcm_DslProtocolTxType_t Dcm_DslProtocolTxType; // 10.2.14 struct Dcm_DslProtocolTxType_t { const Dcm_DslMainConnectionType *DslMainConnectionParent; // (1) /* Cross reference. */ const PduIdType DcmDslProtocolTxPduId; // (1) /* Will be removed (polite), kept for reference. */ const boolean Arc_EOL; }; /* Make it possible to cross reference. */ typedef struct Dcm_DslConnectionType_t Dcm_DslConnectionType; /* Make it possible to cross reference. */ typedef struct Dcm_DslProtocolRowType_t Dcm_DslProtocolRowType; typedef struct { const Dcm_DslProtocolRowType *DslProtocolRow; const PduIdType PduRTxPduId; const PduIdType DcmTxPduId; const boolean Arc_EOL; }Dcm_DslPeriodicTxType; // 10.2.15 typedef struct { const Dcm_DslProtocolRowType *DslProtocolRow; const Dcm_DslPeriodicTxType *TxPduList; const boolean Arc_EOL; } Dcm_DslPeriodicTransmissionType; // 10.2.12 struct Dcm_DslMainConnectionType_t { // Cross referenced from Dcm_DslProtocolRxType_t. const Dcm_DslConnectionType *DslConnectionParent; // Cross reference. const Dcm_DslPeriodicTransmissionType *DslPeriodicTransmissionConRef; // (0..1) // Containers const Dcm_DslProtocolRxType *DslPhysicalProtocolRx; const Dcm_DslProtocolTxType *DslProtocolTx; // (1) uint16 DslRxTesterSourceAddress; // (1) }; // 10.2.11 struct Dcm_DslConnectionType_t { // Containers const Dcm_DslProtocolRowType *DslProtocolRow; // Cross reference. const Dcm_DslMainConnectionType *DslMainConnection; // (1) const Dcm_DslPeriodicTransmissionType *DslPeriodicTransmission; // (0..1) boolean Arc_EOL; }; typedef enum { DCM_IDLE = 0, /* Not in use. */ DCM_WAITING_DIAGNOSTIC_RESPONSE, /* A diagnostic request has been forwarded to the DSD, and DSL is waiting for response. */ DCM_DIAGNOSTIC_RESPONSE_PENDING, /* A diagnostic response has been deployed to the external buffer and is waiting to be transmitted. */ DCM_TRANSMITTING_EXTERNAL_BUFFER_DATA_TO_PDUR, /* We are in the process of transmitting a diagnostic response most likely that reside in the external buffer, from DSD to PDUR. */ DCM_TRANSMITTING_LOCAL_BUFFER_DATA_TO_PDUR /* */ } Dcm_DslProtocolStateType; typedef enum { DCM_DSL_PDUR_DCM_IDLE = 0, DCM_DSL_PDUR_TRANSMIT_INDICATED = 1, DCM_DSL_PDUR_TRANSMIT_TX_BUFFER_PROVIDED = 2, DCM_DSL_RECEPTION_INDICATED = 3, DCM_DSL_RX_BUFFER_PROVIDED = 4 } Dcm_DslPdurCommuncationState; // This buffer is used for implement 7.2.4.3 (Concurrent "tester present"). #define DCM_DSL_LOCAL_BUFFER_LENGTH 8 typedef struct { Dcm_DslBufferUserType status; uint8 buffer[DCM_DSL_LOCAL_BUFFER_LENGTH]; PduLengthType messageLenght; PduInfoType PduInfo; PduLengthType nofBytesHandled; Dcm_NegativeResponseCodeType responseCode; PduIdType DcmRxPduId; //The local buffer is locked to this PDU id } Dcm_DslLocalBufferType; typedef struct { PduIdType diagReqestRxPduId; // Tester request PduId. uint32 stateTimeoutCount; // Counter for timeout. Dcm_DslBufferUserType externalRxBufferStatus; PduInfoType diagnosticRequestFromTester; PduInfoType diagnosticResponseFromDsd; Dcm_DslBufferUserType externalTxBufferStatus; boolean protocolStarted; // Has the protocol been started? Dcm_DslLocalBufferType localRxBuffer; Dcm_DslLocalBufferType localTxBuffer; boolean diagnosticActiveComM; // uint32 S3ServerTimeoutCount; boolean S3ServerStarted; uint8 responsePendingCount; Dcm_SecLevelType securityLevel; Dcm_SesCtrlType sessionControl; Dcm_DslLocalBufferType PeriodicTxBuffer; uint32 preemptTimeoutCount; PduIdType diagResponseTxPduId; boolean isType2Tx; } Dcm_DslRunTimeProtocolParametersType; // 10.2.10 struct Dcm_DslProtocolRowType_t { // Cross referenced from Dcm_DslConnectionType_t. Dcm_ProtocolType DslProtocolID; // (1) boolean DslProtocolIsParallelExecutab; // (1) uint16 DslProtocolPreemptTimeout; // (1) uint8 DslProtocolPriority; // (1) Dcm_ProtocolTransTypeType DslProtocolTransType; // (1) const Dcm_DslBufferType *DslProtocolRxBufferID; // (1) const Dcm_DslBufferType *DslProtocolTxBufferID; // (1) const Dcm_DsdServiceTableType *DslProtocolSIDTable; // (1) const Dcm_DslProtocolTimingRowType *DslProtocolTimeLimit; // (0..1) // Containers const Dcm_DslConnectionType *DslConnections; // (1..*)/* Only main connections */ // Reference to runtime parameters to this protocol. Dcm_DslRunTimeProtocolParametersType *DslRunTimeProtocolParameters; // Maybe this needs to change to index. boolean DslSendRespPendOnTransToBoot; boolean Arc_EOL; }; // 10.2.9 typedef struct { // Containers const Dcm_DslProtocolRxType *DslProtocolRxGlobalList; // (1..*) A polite list for all RX protocol configurations. const Dcm_DslProtocolTxType *DslProtocolTxGlobalList; // (1..*) A polite list for all TX protocol configurations. const Dcm_DslPeriodicTxType *DslProtocolPeriodicTxGlobalList; const Dcm_DslProtocolRowType *DslProtocolRowList; // (1..*) } Dcm_DslProtocolType; // 10.2.19 typedef struct { Dcm_CallbackNotificationIndicationFncType Indication; Dcm_CallbackNotificationConfirmationFncType Confirmation; boolean Arc_EOL; } Dcm_DslServiceRequestNotificationType; // 10.2.5 typedef struct { // Containers const Dcm_DslBufferType *DslBuffer; // (1..256) const Dcm_DslCallbackDCMRequestServiceType *DslCallbackDCMRequestService; // (1..*) const Dcm_DslDiagRespType *DslDiagResp; // (1) const Dcm_DslProtocolType *DslProtocol; // (1) const Dcm_DslProtocolTimingType *DslProtocolTiming; // (1) const Dcm_DslServiceRequestNotificationType *DslServiceRequestNotification; // (0..*) } Dcm_DslType; typedef struct { Dcm_ComControlModeSwitchFcnType ModeSwitchFnc; NetworkHandleType NetworkHandle; uint8 InternalIndex; boolean Arc_EOL; }Dcm_ComMChannelConfigType; // 10.2.1 Dcm typedef struct { // Containers const Dcm_DspType *Dsp; // (1) const Dcm_DsdType *Dsd; // (1) const Dcm_DslType *Dsl; // (1) const Dcm_ComMChannelConfigType *DcmComMChannelCfg; } Dcm_ConfigType; #define DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH 10 /* Max number of bytes in the service to respond to */ typedef struct { uint16 DID; uint8 ServiceToRespondToLength; uint8 ServiceToRespondTo[DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH]; }Dcm_ArcROEDidType; typedef struct { const Dcm_ArcROEDidType *ROEDids; uint8 NofROEDids; }Dcm_ArcROEDidPreconfigType; /* * Make the DCM_Config and Dcm_ConfigPtr visible for others. */ extern const Dcm_ConfigType DCM_Config; extern const Dcm_ConfigType *Dcm_ConfigPtr; #endif /*DCM_LCFG_H_*/
2301_81045437/classic-platform
diagnostic/Dcm/inc/Dcm_Lcfg.h
C
unknown
32,384
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DCM_TYPES_H_ #define DCM_TYPES_H_ /* !req DCM683 */ #include "Std_Types.h" #include "Rte_Dcm_Type.h" #include "ComStack_Types.h" /** Enum literals for Dcm_ConfirmationStatusType */ #ifndef DCM_RES_POS_OK #define DCM_RES_POS_OK 0U #endif /* DCM_RES_POS_OK */ #ifndef DCM_RES_POS_NOT_OK #define DCM_RES_POS_NOT_OK 1U #endif /* DCM_RES_POS_NOT_OK */ #ifndef DCM_RES_NEG_OK #define DCM_RES_NEG_OK 2U #endif /* DCM_RES_NEG_OK */ #ifndef DCM_RES_NEG_NOT_OK #define DCM_RES_NEG_NOT_OK 3U #endif /* DCM_RES_NEG_NOT_OK */ /** Enum literals for Dcm_NegativeResponseCodeType */ #ifndef DCM_E_POSITIVERESPONSE #define DCM_E_POSITIVERESPONSE 0U #endif /* DCM_E_POSITIVERESPONSE */ #ifndef DCM_E_GENERALREJECT #define DCM_E_GENERALREJECT 16U #endif /* DCM_E_GENERALREJECT */ #ifndef DCM_E_SERVICENOTSUPPORTED #define DCM_E_SERVICENOTSUPPORTED 17U #endif /* DCM_E_SERVICENOTSUPPORTED */ #ifndef DCM_E_SUBFUNCTIONNOTSUPPORTED #define DCM_E_SUBFUNCTIONNOTSUPPORTED 18U #endif /* DCM_E_SUBFUNCTIONNOTSUPPORTED */ #ifndef DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT #define DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT 19U #endif /* DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT */ #ifndef DCM_E_RESPONSETOOLONG #define DCM_E_RESPONSETOOLONG 20U #endif /* DCM_E_RESPONSETOOLONG */ #ifndef DCM_E_BUSYREPEATREQUEST #define DCM_E_BUSYREPEATREQUEST 33U #endif /* DCM_E_BUSYREPEATREQUEST */ #ifndef DCM_E_CONDITIONSNOTCORRECT #define DCM_E_CONDITIONSNOTCORRECT 34U #endif /* DCM_E_CONDITIONSNOTCORRECT */ #ifndef DCM_E_REQUESTSEQUENCEERROR #define DCM_E_REQUESTSEQUENCEERROR 36U #endif /* DCM_E_REQUESTSEQUENCEERROR */ #ifndef DCM_E_NORESPONSEFROMSUBNETCOMPONENT #define DCM_E_NORESPONSEFROMSUBNETCOMPONENT 37U #endif /* DCM_E_NORESPONSEFROMSUBNETCOMPONENT */ #ifndef DCM_E_FAILUREPREVENTSEXECUTIONOFREQUESTEDACTION #define DCM_E_FAILUREPREVENTSEXECUTIONOFREQUESTEDACTION 38U #endif /* DCM_E_FAILUREPREVENTSEXECUTIONOFREQUESTEDACTION */ #ifndef DCM_E_REQUESTOUTOFRANGE #define DCM_E_REQUESTOUTOFRANGE 49U #endif /* DCM_E_REQUESTOUTOFRANGE */ #ifndef DCM_E_SECURITYACCESSDENIED #define DCM_E_SECURITYACCESSDENIED 51U #endif /* DCM_E_SECURITYACCESSDENIED */ #ifndef DCM_E_INVALIDKEY #define DCM_E_INVALIDKEY 53U #endif /* DCM_E_INVALIDKEY */ #ifndef DCM_E_EXCEEDNUMBEROFATTEMPTS #define DCM_E_EXCEEDNUMBEROFATTEMPTS 54U #endif /* DCM_E_EXCEEDNUMBEROFATTEMPTS */ #ifndef DCM_E_REQUIREDTIMEDELAYNOTEXPIRED #define DCM_E_REQUIREDTIMEDELAYNOTEXPIRED 55U #endif /* DCM_E_REQUIREDTIMEDELAYNOTEXPIRED */ #ifndef DCM_E_UPLOADDOWNLOADNOTACCEPTED #define DCM_E_UPLOADDOWNLOADNOTACCEPTED 112U #endif /* DCM_E_UPLOADDOWNLOADNOTACCEPTED */ #ifndef DCM_E_TRANSFERDATASUSPENDED #define DCM_E_TRANSFERDATASUSPENDED 113U #endif /* DCM_E_TRANSFERDATASUSPENDED */ #ifndef DCM_E_GENERALPROGRAMMINGFAILURE #define DCM_E_GENERALPROGRAMMINGFAILURE 114U #endif /* DCM_E_GENERALPROGRAMMINGFAILURE */ #ifndef DCM_E_WRONGBLOCKSEQUENCECOUNTER #define DCM_E_WRONGBLOCKSEQUENCECOUNTER 115U #endif /* DCM_E_WRONGBLOCKSEQUENCECOUNTER */ #ifndef DCM_E_SUBFUNCTIONNOTSUPPORTEDINACTIVESESSION #define DCM_E_SUBFUNCTIONNOTSUPPORTEDINACTIVESESSION 126U #endif /* DCM_E_SUBFUNCTIONNOTSUPPORTEDINACTIVESESSION */ #ifndef DCM_E_SERVICENOTSUPPORTEDINACTIVESESSION #define DCM_E_SERVICENOTSUPPORTEDINACTIVESESSION 127U #endif /* DCM_E_SERVICENOTSUPPORTEDINACTIVESESSION */ #ifndef DCM_E_RPMTOOHIGH #define DCM_E_RPMTOOHIGH 129U #endif /* DCM_E_RPMTOOHIGH */ #ifndef DCM_E_RPMTOOLOW #define DCM_E_RPMTOOLOW 130U #endif /* DCM_E_RPMTOOLOW */ #ifndef DCM_E_ENGINEISRUNNING #define DCM_E_ENGINEISRUNNING 131U #endif /* DCM_E_ENGINEISRUNNING */ #ifndef DCM_E_ENGINEISNOTRUNNING #define DCM_E_ENGINEISNOTRUNNING 132U #endif /* DCM_E_ENGINEISNOTRUNNING */ #ifndef DCM_E_ENGINERUNTIMETOOLOW #define DCM_E_ENGINERUNTIMETOOLOW 133U #endif /* DCM_E_ENGINERUNTIMETOOLOW */ #ifndef DCM_E_TEMPERATURETOOHIGH #define DCM_E_TEMPERATURETOOHIGH 134U #endif /* DCM_E_TEMPERATURETOOHIGH */ #ifndef DCM_E_TEMPERATURETOOLOW #define DCM_E_TEMPERATURETOOLOW 135U #endif /* DCM_E_TEMPERATURETOOLOW */ #ifndef DCM_E_VEHICLESPEEDTOOHIGH #define DCM_E_VEHICLESPEEDTOOHIGH 136U #endif /* DCM_E_VEHICLESPEEDTOOHIGH */ #ifndef DCM_E_VEHICLESPEEDTOOLOW #define DCM_E_VEHICLESPEEDTOOLOW 137U #endif /* DCM_E_VEHICLESPEEDTOOLOW */ #ifndef DCM_E_THROTTLE_PEDALTOOHIGH #define DCM_E_THROTTLE_PEDALTOOHIGH 138U #endif /* DCM_E_THROTTLE_PEDALTOOHIGH */ #ifndef DCM_E_THROTTLE_PEDALTOOLOW #define DCM_E_THROTTLE_PEDALTOOLOW 139U #endif /* DCM_E_THROTTLE_PEDALTOOLOW */ #ifndef DCM_E_TRANSMISSIONRANGENOTINNEUTRAL #define DCM_E_TRANSMISSIONRANGENOTINNEUTRAL 140U #endif /* DCM_E_TRANSMISSIONRANGENOTINNEUTRAL */ #ifndef DCM_E_TRANSMISSIONRANGENOTINGEAR #define DCM_E_TRANSMISSIONRANGENOTINGEAR 141U #endif /* DCM_E_TRANSMISSIONRANGENOTINGEAR */ #ifndef DCM_E_BRAKESWITCH_NOTCLOSED #define DCM_E_BRAKESWITCH_NOTCLOSED 143U #endif /* DCM_E_BRAKESWITCH_NOTCLOSED */ #ifndef DCM_E_SHIFTERLEVERNOTINPARK #define DCM_E_SHIFTERLEVERNOTINPARK 144U #endif /* DCM_E_SHIFTERLEVERNOTINPARK */ #ifndef DCM_E_TORQUECONVERTERCLUTCHLOCKED #define DCM_E_TORQUECONVERTERCLUTCHLOCKED 145U #endif /* DCM_E_TORQUECONVERTERCLUTCHLOCKED */ #ifndef DCM_E_VOLTAGETOOHIGH #define DCM_E_VOLTAGETOOHIGH 146U #endif /* DCM_E_VOLTAGETOOHIGH */ #ifndef DCM_E_VOLTAGETOOLOW #define DCM_E_VOLTAGETOOLOW 147U #endif /* DCM_E_VOLTAGETOOLOW */ /** Enum literals for Dcm_OpStatusType */ #ifndef DCM_INITIAL #define DCM_INITIAL 0U #endif /* DCM_INITIAL */ #ifndef DCM_PENDING #define DCM_PENDING 1U #endif /* DCM_PENDING */ #ifndef DCM_CANCEL #define DCM_CANCEL 2U #endif /* DCM_CANCEL */ #ifndef DCM_FORCE_RCRRP_OK #define DCM_FORCE_RCRRP_OK 3U #endif /* DCM_FORCE_RCRRP_OK */ /** Enum literals for Dcm_ProtocolType */ #ifndef DCM_OBD_ON_CAN #define DCM_OBD_ON_CAN 0U #endif /* DCM_OBD_ON_CAN */ #ifndef DCM_OBD_ON_FLEXRAY #define DCM_OBD_ON_FLEXRAY 1U #endif /* DCM_OBD_ON_FLEXRAY */ #ifndef DCM_OBD_ON_IP #define DCM_OBD_ON_IP 2U #endif /* DCM_OBD_ON_IP */ #ifndef DCM_UDS_ON_CAN #define DCM_UDS_ON_CAN 3U #endif /* DCM_UDS_ON_CAN */ #ifndef DCM_UDS_ON_FLEXRAY #define DCM_UDS_ON_FLEXRAY 4U #endif /* DCM_UDS_ON_FLEXRAY */ #ifndef DCM_UDS_ON_IP #define DCM_UDS_ON_IP 5U #endif /* DCM_UDS_ON_IP */ #ifndef DCM_ROE_ON_CAN #define DCM_ROE_ON_CAN 6U #endif /* DCM_ROE_ON_CAN */ #ifndef DCM_ROE_ON_FLEXRAY #define DCM_ROE_ON_FLEXRAY 7U #endif /* DCM_ROE_ON_FLEXRAY */ #ifndef DCM_ROE_ON_IP #define DCM_ROE_ON_IP 8U #endif /* DCM_ROE_ON_IP */ #ifndef DCM_PERIODICTRANS_ON_CAN #define DCM_PERIODICTRANS_ON_CAN 9U #endif /* DCM_PERIODICTRANS_ON_CAN */ #ifndef DCM_PERIODICTRANS_ON_FLEXRAY #define DCM_PERIODICTRANS_ON_FLEXRAY 10U #endif /* DCM_PERIODICTRANS_ON_FLEXRAY */ #ifndef DCM_PERIODICTRANS_ON_IP #define DCM_PERIODICTRANS_ON_IP 11U #endif /* DCM_PERIODICTRANS_ON_IP */ #ifndef DCM_NO_ACTIVE_PROTOCOL #define DCM_NO_ACTIVE_PROTOCOL 12U #endif /* DCM_NO_ACTIVE_PROTOCOL */ #ifndef DCM_SUPPLIER_1 #define DCM_SUPPLIER_1 240U #endif /* DCM_SUPPLIER_1 */ #ifndef DCM_SUPPLIER_2 #define DCM_SUPPLIER_2 241U #endif /* DCM_SUPPLIER_2 */ #ifndef DCM_SUPPLIER_3 #define DCM_SUPPLIER_3 242U #endif /* DCM_SUPPLIER_3 */ #ifndef DCM_SUPPLIER_4 #define DCM_SUPPLIER_4 243U #endif /* DCM_SUPPLIER_4 */ #ifndef DCM_SUPPLIER_5 #define DCM_SUPPLIER_5 244U #endif /* DCM_SUPPLIER_5 */ #ifndef DCM_SUPPLIER_6 #define DCM_SUPPLIER_6 245U #endif /* DCM_SUPPLIER_6 */ #ifndef DCM_SUPPLIER_7 #define DCM_SUPPLIER_7 246U #endif /* DCM_SUPPLIER_7 */ #ifndef DCM_SUPPLIER_8 #define DCM_SUPPLIER_8 247U #endif /* DCM_SUPPLIER_8 */ #ifndef DCM_SUPPLIER_9 #define DCM_SUPPLIER_9 248U #endif /* DCM_SUPPLIER_9 */ #ifndef DCM_SUPPLIER_10 #define DCM_SUPPLIER_10 249U #endif /* DCM_SUPPLIER_10 */ #ifndef DCM_SUPPLIER_11 #define DCM_SUPPLIER_11 250U #endif /* DCM_SUPPLIER_11 */ #ifndef DCM_SUPPLIER_12 #define DCM_SUPPLIER_12 251U #endif /* DCM_SUPPLIER_12 */ #ifndef DCM_SUPPLIER_13 #define DCM_SUPPLIER_13 252U #endif /* DCM_SUPPLIER_13 */ #ifndef DCM_SUPPLIER_14 #define DCM_SUPPLIER_14 253U #endif /* DCM_SUPPLIER_14 */ #ifndef DCM_SUPPLIER_15 #define DCM_SUPPLIER_15 254U #endif /* DCM_SUPPLIER_15 */ /* * Dcm_SecLevelType */ #ifndef DCM_SEC_LEV_LOCKED #define DCM_SEC_LEV_LOCKED ((Dcm_SecLevelType)0x00) #endif #ifndef DCM_SEC_LEV_L1 #define DCM_SEC_LEV_L1 ((Dcm_SecLevelType)0x01) #endif #ifndef DCM_SEC_LEV_ALL #define DCM_SEC_LEV_ALL ((Dcm_SecLevelType)0xFF) #endif /* * Dcm_SesCtrlType */ typedef uint8 Dcm_EcuResetType; #define DCM_HARD_RESET ((Dcm_EcuResetType)0x01) #define DCM_KEY_OFF_ON_RESET ((Dcm_EcuResetType)0x02) #define DCM_SOFT_RESET ((Dcm_EcuResetType)0x03) #define DCM_ENABLE_RAPID_POWER_SHUTDOWN ((Dcm_EcuResetType)0x04) #define DCM_DISABLE_RAPID_POWER_SHUTDOWN ((Dcm_EcuResetType)0x05) #ifndef RTE_MODE_DcmEcuReset_EXECUTE #define RTE_MODE_DcmEcuReset_EXECUTE 0U #endif #ifndef RTE_MODE_DcmEcuReset_HARD #define RTE_MODE_DcmEcuReset_HARD 1U #endif #ifndef RTE_MODE_DcmEcuReset_JUMPTOBOOTLOADER #define RTE_MODE_DcmEcuReset_JUMPTOBOOTLOADER 2U #endif #ifndef RTE_MODE_DcmEcuReset_JUMPTOSYSSUPPLIERBOOTLOADER #define RTE_MODE_DcmEcuReset_JUMPTOSYSSUPPLIERBOOTLOADER 3U #endif #ifndef RTE_MODE_DcmEcuReset_KEYONOFF #define RTE_MODE_DcmEcuReset_KEYONOFF 4U #endif #ifndef RTE_MODE_DcmEcuReset_NONE #define RTE_MODE_DcmEcuReset_NONE 5U #endif #ifndef RTE_MODE_DcmEcuReset_SOFT #define RTE_MODE_DcmEcuReset_SOFT 6U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM 0U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM 1U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM 2U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORMAL #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORMAL 3U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NM 4U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NM 5U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NM #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NM 6U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NM #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NM 7U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM_NM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM_NM 8U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM_NM #define RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM_NM 9U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM_NM #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM_NM 10U #endif #ifndef RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORM_NM #define RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORM_NM 11U #endif /* * Dcm_SesCtrlType */ #ifndef DCM_DEFAULT_SESSION #define DCM_DEFAULT_SESSION ((Dcm_SesCtrlType)0x01) #endif #ifndef DCM_PROGRAMMING_SESSION #define DCM_PROGRAMMING_SESSION ((Dcm_SesCtrlType)0x02) #endif #ifndef DCM_EXTENDED_DIAGNOSTIC_SESSION #define DCM_EXTENDED_DIAGNOSTIC_SESSION ((Dcm_SesCtrlType)0x03) #endif #ifndef DCM_SAFTEY_SYSTEM_DIAGNOSTIC_SESSION #define DCM_SAFTEY_SYSTEM_DIAGNOSTIC_SESSION ((Dcm_SesCtrlType)0x04) #endif #ifndef DCM_OBD_SESSION #define DCM_OBD_SESSION ((Dcm_SesCtrlType)0x05)//only used for OBD diagnostic #endif #ifndef DCM_ALL_SESSION_LEVEL #define DCM_ALL_SESSION_LEVEL ((Dcm_SesCtrlType)0xFF) #endif typedef uint8 Dcm_PidServiceType; #define DCM_SERVICE_01 ((Dcm_PidServiceType)0x01) #define DCM_SERVICE_02 ((Dcm_PidServiceType)0x02) #define DCM_SERVICE_01_02 ((Dcm_PidServiceType)0x03) /* * Dcm_ReturnReadMemoryType */ typedef uint8 Dcm_ReturnReadMemoryType; #define DCM_READ_OK ((Dcm_ReturnReadMemoryType)0x00) #define DCM_READ_PENDING ((Dcm_ReturnReadMemoryType)0x01) #define DCM_READ_FAILED ((Dcm_ReturnReadMemoryType)0x02) /* * Dcm_ReturnWriteMemoryType */ typedef uint8 Dcm_ReturnWriteMemoryType; #define DCM_WRITE_OK ((Dcm_ReturnWriteMemoryType)0x00) #define DCM_WRITE_PENDING ((Dcm_ReturnWriteMemoryType)0x01) #define DCM_WRITE_FAILED ((Dcm_ReturnWriteMemoryType)0x02) #define DCM_WRITE_FORCE_RCRRP ((Dcm_ReturnWriteMemoryType)0x03) typedef uint8 Dcm_StatusType; #define DCM_E_OK (Dcm_StatusType)0x00u #define DCM_E_COMPARE_KEY_FAILED (Dcm_StatusType)0x01u #define DCM_E_TI_PREPARE_LIMITS (Dcm_StatusType)0x02u #define DCM_E_TI_PREPARE_INCONSTENT (Dcm_StatusType)0x03u #define DCM_E_SESSION_NOT_ALLOWED (Dcm_StatusType)0x04u #define DCM_E_PROTOCOL_NOT_ALLOWED (Dcm_StatusType)0x05u #define DCM_E_ROE_NOT_ACCEPTED (Dcm_StatusType)0x06u #define DCM_E_PERIODICID_NOT_ACCEPTED (Dcm_StatusType)0x07u #define DCM_E_REQUEST_NOT_ACCEPTED (Dcm_StatusType)0x08u #define DCM_E_REQUEST_ENV_NOK (Dcm_StatusType)0x09u #define DCM_E_PENDING (Dcm_StatusType)0x0au typedef uint8 Dcm_PeriodicTransmitModeType; #define DCM_PERIODICTRANSMIT_DEFAULT_MODE (Dcm_PeriodicTransmitModeType)0x00u #define DCM_PERIODICTRANSMIT_SLOW_MODE (Dcm_PeriodicTransmitModeType)0x01u #define DCM_PERIODICTRANSMIT_MEDIUM_MODE (Dcm_PeriodicTransmitModeType)0x02u #define DCM_PERIODICTRANSMIT_FAST_MODE (Dcm_PeriodicTransmitModeType)0x03u #define DCM_PERIODICTRANSMIT_STOPSENDING_MODE (Dcm_PeriodicTransmitModeType)0x04u typedef uint8 Dcm_DDDSubfunctionType; #define DCM_DDD_SUBFUNCTION_DEFINEBYDID (Dcm_DDDSubfunctionType)0x01u #define DCM_DDD_SUBFUNCTION_DEFINEBYADDRESS (Dcm_DDDSubfunctionType)0x02u #define DCM_DDD_SUBFUNCTION_CLEAR (Dcm_DDDSubfunctionType)0x03u typedef uint8 Dcm_PeriodicDidStartType; #define DCM_PERIODIC_TRANISMIT_STOP (Dcm_PeriodicDidStartType)0 #define DCM_PERIODIC_TRANISMIT_START (Dcm_PeriodicDidStartType)0x01u typedef uint8 Dcm_DDDSourceStateType; #define DCM_DDDSOURCE_BY_DID (Dcm_DDDSourceStateType)0x00u #define DCM_DDDSOURCE_BY_ADDRESS (Dcm_DDDSourceStateType)0x01u typedef uint8 Dcm_IOControlParameterType; #define DCM_RETURN_CONTROL_TO_ECU (Dcm_IOControlParameterType)0x0 #define DCM_RESET_TO_DEFAULT (Dcm_IOControlParameterType)0x01 #define DCM_FREEZE_CURRENT_STATE (Dcm_IOControlParameterType)0x02 #define DCM_SHORT_TERM_ADJUSTMENT (Dcm_IOControlParameterType)0x03 typedef struct { uint8 ProtocolId; uint8 TesterSourceAdd; uint8 Sid; uint8 SubFncId; boolean ReprogramingRequest; boolean ApplUpdated; boolean ResponseRequired; } Dcm_ProgConditionsType; #define DCM_PERIODIC_ON_CAN DCM_PERIODICTRANS_ON_CAN #define DCM_PERIODIC_ON_FLEXRAY DCM_PERIODICTRANS_ON_FLEXRAY #define DCM_PERIODIC_ON_IP DCM_PERIODICTRANS_ON_IP typedef uint8 Dcm_MsgItemType; typedef Dcm_MsgItemType* Dcm_MsgType; typedef uint32 Dcm_MsgLenType; //dont know what is bit type typedef struct{ boolean reqType:1; boolean suppressPosResponse:1; }Dcm_MsgAddInfoType; typedef uint8 Dcm_IdContextType; typedef struct { Dcm_MsgType reqData; Dcm_MsgLenType reqDataLen; Dcm_MsgType resData; Dcm_MsgLenType resDataLen; Dcm_MsgAddInfoType msgAddInfo; Dcm_MsgLenType resMaxDataLen; Dcm_IdContextType idContext; PduIdType dcmRxPduId; } Dcm_MsgContextType; typedef uint8 Dcm_CommunicationModeType; #define DCM_ENABLE_RX_TX_NORM (Dcm_CommunicationModeType)0x00 #define DCM_ENABLE_RX_DISABLE_TX_NORM (Dcm_CommunicationModeType)0x01 #define DCM_DISABLE_RX_ENABLE_TX_NORM (Dcm_CommunicationModeType)0x02 #define DCM_DISABLE_RX_TX_NORMAL (Dcm_CommunicationModeType)0x03 #define DCM_ENABLE_RX_TX_NM (Dcm_CommunicationModeType)0x04 #define DCM_ENABLE_RX_DISABLE_TX_NM (Dcm_CommunicationModeType)0x05 #define DCM_DISABLE_RX_ENABLE_TX_NM (Dcm_CommunicationModeType)0x06 #define DCM_DISABLE_RX_TX_NM (Dcm_CommunicationModeType)0x07 #define DCM_ENABLE_RX_TX_NORM_NM (Dcm_CommunicationModeType)0x08 #define DCM_ENABLE_RX_DISABLE_TX_NORM_NM (Dcm_CommunicationModeType)0x09 #define DCM_DISABLE_RX_ENABLE_TX_NORM_NM (Dcm_CommunicationModeType)0x0A #define DCM_DISABLE_RX_TX_NORM_NM (Dcm_CommunicationModeType)0x0B typedef uint8 Dcm_EcuStartModeType; #define DCM_COLD_START (Dcm_EcuStartModeType)0x00 #define DCM_WARM_START (Dcm_EcuStartModeType)0x01 /** Dcm_RoeStateType */ #ifndef DCM_ROE_ACTIVE #define DCM_ROE_ACTIVE 0U #endif #ifndef DCM_ROE_UNACTIVE #define DCM_ROE_UNACTIVE 1U #endif /** DTRStatusType */ #ifndef DCM_DTRSTATUS_VISIBLE #define DCM_DTRSTATUS_VISIBLE (DTRStatusType)0U #endif #ifndef DCM_DTRSTATUS_INVISIBLE #define DCM_DTRSTATUS_INVISIBLE (DTRStatusType)1U #endif #ifndef RTE_MODE_DcmControlDTCSetting_DISABLEDTCSETTING #define RTE_MODE_DcmControlDTCSetting_DISABLEDTCSETTING 0U #endif #ifndef RTE_MODE_DcmControlDTCSetting_ENABLEDTCSETTING #define RTE_MODE_DcmControlDTCSetting_ENABLEDTCSETTING 1U #endif #endif /*DCM_TYPES_H_*/
2301_81045437/classic-platform
diagnostic/Dcm/inc/Dcm_Types.h
C
unknown
18,750
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ // 904 PC-Lint: OK. Allow VALIDATE, VALIDATE_RV and VALIDATE_NO_RV to return value. //lint -emacro(904,VALIDATE_RV,VALIDATE_NO_RV,VALIDATE) /* * General requirements */ /* !req DCM054 Partially */ /* !req DCM055 Partially */ /* @req DCM110 */ /* @req DCM107 */ /* @req DCM012 */ /* @req DCM044 */ /* @req DCM364 */ /* @req DCM041 */ /* @req DCM042 */ /* @req DCM049 */ /* @req DCM033 */ /* @req DCM171 */ /* @req DCM333 */ /* @req DCM334 */ /* @req DCM018 Where is this implemented? */ /* @req DCM048 */ /* !req DCM040 All errors not detected */ /* @req DCM043 */ /* @req DCM048 */ /* !req DCM550 HIS subset MISRA compliance */ /* @req OEM_DCM_10001 Dcm based on AUTOSAR version 4.0.3 */ /* !req OEM_DCM_10004 RfCs only partly implemented */ /* !req OEM_DCM_10006 RfCs only partly implemented */ /* !req OEM_DCM_10014 SID 2A Type need work-around */ /* !req OEM_DCM_10015 SID 2A Type need work-around */ #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #if defined(USE_DEM) #if defined(DCM_USE_SERVICE_CLEARDIAGNOSTICINFORMATION) || defined(DCM_USE_SERVICE_READDTCINFORMATION) || defined(DCM_USE_SERVICE_CONTROLDTCSETTING) #include "Dem.h" /* @req DCM332 */ #endif #endif #include "MemMap.h" //#include "SchM_Dcm.h" //#include "ComM_Dcm.h" #include "PduR_Dcm.h" #include "ComStack_Types.h" // State variable typedef enum { DCM_UNINITIALIZED = 0, DCM_INITIALIZED } Dcm_StateType; //lint -esym(551,dcmState) PC-Lint - Turn of warning of dcmState not accessed when having DCM_DEV_ERROR_DETECT to STD_OFF static Dcm_StateType dcmState = DCM_UNINITIALIZED; static boolean firstMainAfterInit = TRUE; /* Global configuration */ /*lint -e9003 Allow global scope */ const Dcm_ConfigType *Dcm_ConfigPtr; /********************************************* * Interface for upper layer modules (8.3.1) * *********************************************/ /* * Procedure: Dcm_GetVersionInfo * Reentrant: Yes */ // Defined in Dcm.h /* * Procedure: Dcm_Init * Reentrant: No */ void Dcm_Init(const Dcm_ConfigType *ConfigPtr) /* @req DCM037 */ { VALIDATE_NO_RV(((NULL != ConfigPtr) && (NULL != ConfigPtr->Dsl) && (NULL != ConfigPtr->Dsd) && (NULL != ConfigPtr->Dsp)), DCM_INIT_ID, DCM_E_CONFIG_INVALID); Dcm_ConfigPtr = ConfigPtr; #ifdef DCM_USE_SERVICE_RESPONSEONEVENT DCM_ROE_Init(); #endif DslInit(); DsdInit(); DspInit(TRUE); firstMainAfterInit = TRUE; dcmState = DCM_INITIALIZED; return; } #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) void Dcm_MainFunction(void) /* @req DCM362 */ { /* Contradiction between DCM043 and DCM593 */ VALIDATE_NO_RV(dcmState == DCM_INITIALIZED, DCM_MAIN_ID, DCM_E_UNINIT); if( DCM_INITIALIZED == dcmState ) { if( firstMainAfterInit ) { DcmSetProtocolStartRequestsAllowed(TRUE); #ifdef DCM_USE_SERVICE_RESPONSEONEVENT DcmRoeCheckProtocolStartRequest(); #endif DspCheckProtocolStartRequests(); DcmSetProtocolStartRequestsAllowed(FALSE); DcmExecuteStartProtocolRequest(); firstMainAfterInit = FALSE; } DslMain(); DspTimerMain(); } else { /* @req DCM593 */ } } void Dcm_MainFunction_LowPrio(void) /* @req DCM362 */ { /* Contradiction between DCM043 and DCM593 */ VALIDATE_NO_RV(dcmState == DCM_INITIALIZED, DCM_MAIN_ID, DCM_E_UNINIT); if( DCM_INITIALIZED == dcmState ) { DspPreDsdMain(); DsdMain(); DspMain(); #ifdef DCM_USE_SERVICE_RESPONSEONEVENT Dcm_ROE_MainFunction(); #endif } else { /* @req DCM593 */ } } #else /* * Interface for basic software scheduler */ void Dcm_MainFunction(void) /* @req DCM362 */ { /* Contradiction between DCM043 and DCM593 */ VALIDATE_NO_RV((dcmState == DCM_INITIALIZED), DCM_MAIN_ID, DCM_E_UNINIT); if( DCM_INITIALIZED == dcmState ) { if( firstMainAfterInit ) { /*lint !e9036 firstMainAfterInit is boolean */ DcmSetProtocolStartRequestsAllowed(TRUE); #ifdef DCM_USE_SERVICE_RESPONSEONEVENT DcmRoeCheckProtocolStartRequest(); #endif DspCheckProtocolStartRequests(); DcmSetProtocolStartRequestsAllowed(FALSE); DcmExecuteStartProtocolRequest(); firstMainAfterInit = FALSE; } DspPreDsdMain(); DsdMain(); DspMain(); DspTimerMain(); DslMain(); #ifdef DCM_USE_SERVICE_RESPONSEONEVENT Dcm_ROE_MainFunction(); #endif } else { /* @req DCM593 */ } } #endif /*********************************************** * Interface for BSW modules and SW-Cs (8.3.2) * ***********************************************/ BufReq_ReturnType Dcm_StartOfReception(PduIdType dcmRxPduId, PduLengthType tpSduLength, PduLengthType *rxBufferSizePtr) { BufReq_ReturnType returnCode; VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_START_OF_RECEPTION_ID, DCM_E_UNINIT, BUFREQ_NOT_OK); VALIDATE_RV(dcmRxPduId < DCM_DSL_RX_PDU_ID_LIST_LENGTH, DCM_START_OF_RECEPTION_ID, DCM_E_PARAM, BUFREQ_NOT_OK); returnCode = DslStartOfReception(dcmRxPduId, tpSduLength, rxBufferSizePtr, FALSE); return returnCode; } BufReq_ReturnType Dcm_CopyRxData(PduIdType dcmRxPduId, PduInfoType *pduInfoPtr, PduLengthType *rxBufferSizePtr) { VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_COPY_RX_DATA_ID, DCM_E_UNINIT, BUFREQ_NOT_OK); VALIDATE_RV(dcmRxPduId < DCM_DSL_RX_PDU_ID_LIST_LENGTH, DCM_COPY_RX_DATA_ID, DCM_E_PARAM, BUFREQ_NOT_OK); return DslCopyDataToRxBuffer(dcmRxPduId, pduInfoPtr, rxBufferSizePtr); /*lint -e{818} this defined as per autosar api cannot be changed */ } void Dcm_TpRxIndication(PduIdType dcmRxPduId, NotifResultType result) { VALIDATE_NO_RV(dcmState == DCM_INITIALIZED, DCM_TP_RX_INDICATION_ID, DCM_E_UNINIT); VALIDATE_NO_RV(dcmRxPduId < DCM_DSL_RX_PDU_ID_LIST_LENGTH, DCM_TP_RX_INDICATION_ID, DCM_E_PARAM); DslTpRxIndicationFromPduR(dcmRxPduId, result, FALSE, FALSE); } Std_ReturnType Dcm_GetActiveProtocol(Dcm_ProtocolType *activeProtocol) { Std_ReturnType returnCode; VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_GET_ACTIVE_PROTOCOL_ID, DCM_E_UNINIT, E_NOT_OK); /* According to 4.0.3 spec. E_OK should always be returned. * But if there is no active protocol? */ returnCode = DslGetActiveProtocol(activeProtocol); return returnCode; } Std_ReturnType Dcm_GetSecurityLevel(Dcm_SecLevelType *secLevel) { VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_GET_SECURITY_LEVEL_ID, DCM_E_UNINIT, E_NOT_OK); /* According to 4.0.3 spec. E_OK should always be returned. * So if we cannot get the current security level using DslGetSecurityLevel, * and this probably due to that there is no active protocol, * we report the default security level according to DCM033 */ if( E_OK != DslGetSecurityLevel(secLevel) ) { *secLevel = DCM_SEC_LEV_LOCKED; } return E_OK; } Std_ReturnType Dcm_GetSesCtrlType(Dcm_SesCtrlType *sesCtrlType) { VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_GET_SES_CTRL_TYPE_ID, DCM_E_UNINIT, E_NOT_OK); /* According to 4.0.3 spec. E_OK should always be returned. * So if we cannot get the current session using DslGetSesCtrlType, * and this probably due to that there is no active protocol, * we report the default session according to DCM034 */ if( E_OK != DslGetSesCtrlType(sesCtrlType) ) { *sesCtrlType = DCM_DEFAULT_SESSION; } return E_OK; } void Dcm_TpTxConfirmation(PduIdType dcmTxPduId, NotifResultType result) { VALIDATE_NO_RV(dcmState == DCM_INITIALIZED, DCM_TP_TX_CONFIRMATION_ID, DCM_E_UNINIT); VALIDATE_NO_RV((dcmTxPduId < DCM_DSL_TX_PDU_ID_LIST_LENGTH) || IS_PERIODIC_TX_PDU(dcmTxPduId), DCM_TP_TX_CONFIRMATION_ID, DCM_E_PARAM); DslTpTxConfirmation(dcmTxPduId, result); } BufReq_ReturnType Dcm_CopyTxData(PduIdType dcmTxPduId, PduInfoType *pduInfoPtr, RetryInfoType *periodData, PduLengthType *txDataCntPtr) { VALIDATE_RV(dcmState == DCM_INITIALIZED, DCM_COPY_TX_DATA_ID, DCM_E_UNINIT, BUFREQ_NOT_OK); VALIDATE_RV((dcmTxPduId < DCM_DSL_TX_PDU_ID_LIST_LENGTH) || IS_PERIODIC_TX_PDU(dcmTxPduId), DCM_COPY_TX_DATA_ID, DCM_E_PARAM, BUFREQ_NOT_OK); return DslCopyTxData(dcmTxPduId, pduInfoPtr, periodData, txDataCntPtr); } /** * Used to reset to default session from the application. * @return E_OK is always returned according to AUTOSAR */ Std_ReturnType Dcm_ResetToDefaultSession( void ) { VALIDATE_RV((DCM_INITIALIZED == dcmState), DCM_RESETTODEFAULTSESSION_ID, DCM_E_UNINIT, E_NOT_OK); DslSetSesCtrlType(DCM_DEFAULT_SESSION); return E_OK; } /* @req DCM356 */ void Dcm_ComM_NoComModeEntered( uint8 NetworkId ) { VALIDATE_NO_RV((DCM_INITIALIZED == dcmState), DCM_COMM_NO_COM_MODE_ENTERED_ID, DCM_E_UNINIT); /* !req DCM148 */ /* !req DCM149 */ /* !req DCM150 */ /* !req DCM151 */ /* !req DCM152 */ #if defined(USE_COMM) DslComModeEntered(NetworkId, DCM_NO_COM); #else (void)NetworkId; #endif } /* @req DCM358 */ void Dcm_ComM_SilentComModeEntered( uint8 NetworkId ) { VALIDATE_NO_RV((DCM_INITIALIZED == dcmState), DCM_COMM_SILENT_COM_MODE_ENTERED_ID, DCM_E_UNINIT); /* !req DCM153 */ /* !req DCM154 */ /* !req DCM155 */ /* !req DCM156 */ #if defined(USE_COMM) DslComModeEntered(NetworkId, DCM_SILENT_COM); #else (void)NetworkId; #endif } /* @req DCM360 */ void Dcm_ComM_FullComModeEntered( uint8 NetworkId ) { VALIDATE_NO_RV((DCM_INITIALIZED == dcmState), DCM_COMM_FULL_COM_MODE_ENTERED_ID, DCM_E_UNINIT); /* !req DCM157 */ /* !req DCM159 */ /* !req DCM160 */ /* !req DCM161 */ /* !req DCM162 */ #if defined(USE_COMM) DslComModeEntered(NetworkId, DCM_FULL_COM); #else (void)NetworkId; #endif } /** * Used by service interpreter outside of DCM to indicate that a the final response * shall be a negative one. Dcm_ExternalSetNegResponse will not finalize the response processing. * @param pMsgContext * @param ErrorCode */ /* @req DCM761 */ /*lint --e{818} ARGUMENT CHECK pMsgContext is ASR specific cannot modify decleration*/ void Dcm_ExternalSetNegResponse(Dcm_MsgContextType* pMsgContext, Dcm_NegativeResponseCodeType ErrorCode) { VALIDATE_NO_RV((DCM_INITIALIZED == dcmState), DCM_EXTERNALSETNEGRESPONSE_ID, DCM_E_UNINIT); VALIDATE_NO_RV((NULL != pMsgContext), DCM_EXTERNALSETNEGRESPONSE_ID, DCM_E_PARAM); DsdExternalSetNegResponse(pMsgContext, ErrorCode); } /** * Used by service interpreter outside of DCM to indicate that a final response can be sent. * @param pMsgContext */ /* @req DCM762 */ /*lint --e{818} ARGUMENT CHECK pMsgContext is ASR specific cannot modify decleration*/ void Dcm_ExternalProcessingDone(Dcm_MsgContextType* pMsgContext) { VALIDATE_NO_RV((DCM_INITIALIZED == dcmState), DCM_EXTERNALPROCESSINGDONE_ID, DCM_E_UNINIT); VALIDATE_NO_RV((NULL != pMsgContext), DCM_EXTERNALPROCESSINGDONE_ID, DCM_E_PARAM); DsdExternalProcessingDone(pMsgContext); }
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm.c
C
unknown
12,066
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* Ecum Callout Stubs - generic version */ #include "Dcm.h" #if defined(USE_MCU) #include "Mcu.h" #endif /* @req DCM540 */ Dcm_ReturnWriteMemoryType Dcm_WriteMemory(Dcm_OpStatusType OpStatus, uint8 MemoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8* MemoryData) { (void)OpStatus; (void)MemoryIdentifier; (void)MemoryAddress; (void)MemorySize; (void)*MemoryData; return DCM_WRITE_FAILED; } /* @req DCM539 */ Dcm_ReturnReadMemoryType Dcm_ReadMemory(Dcm_OpStatusType OpStatus, uint8 MemoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8* MemoryData) { (void)OpStatus; (void)MemoryIdentifier; (void)MemoryAddress; (void)MemorySize; (void)*MemoryData; return DCM_READ_FAILED; } #ifdef DCM_NOT_SERVICE_COMPONENT Std_ReturnType Rte_Switch_DcmDiagnosticSessionControl_DcmDiagnosticSessionControl(Dcm_SesCtrlType session) { (void)session; return E_OK; } Std_ReturnType Rte_Switch_DcmEcuReset_DcmEcuReset(uint8 resetMode) { switch(resetMode) { case RTE_MODE_DcmEcuReset_NONE: case RTE_MODE_DcmEcuReset_HARD: case RTE_MODE_DcmEcuReset_KEYONOFF: case RTE_MODE_DcmEcuReset_SOFT: case RTE_MODE_DcmEcuReset_JUMPTOBOOTLOADER: case RTE_MODE_DcmEcuReset_JUMPTOSYSSUPPLIERBOOTLOADER: break; case RTE_MODE_DcmEcuReset_EXECUTE: #if defined(USE_MCU) && ( MCU_PERFORM_RESET_API == STD_ON ) Mcu_PerformReset(); #endif break; default: break; } return E_OK; } Std_ReturnType Rte_Switch_DcmControlDTCSetting_DcmControlDTCSetting(uint8 mode) { (void)mode; return E_OK; } #endif /* @req DCM754 */ Std_ReturnType Dcm_ProcessRequestDownload(Dcm_OpStatusType OpStatus, uint8 DataFormatIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint32 *BlockLength, Dcm_NegativeResponseCodeType* ErrorCode) { (void)OpStatus; (void)DataFormatIdentifier; (void)MemoryAddress; (void)MemorySize; (void)*BlockLength; *ErrorCode = DCM_E_GENERALPROGRAMMINGFAILURE; return E_NOT_OK; } /* @req DCM756 */ Std_ReturnType Dcm_ProcessRequestUpload(Dcm_OpStatusType OpStatus, uint8 DataFormatIdentifier, uint32 MemoryAddress, uint32 MemorySize, Dcm_NegativeResponseCodeType* ErrorCode) { (void)OpStatus; (void)DataFormatIdentifier; (void)MemoryAddress; (void)MemorySize; *ErrorCode = DCM_E_GENERALPROGRAMMINGFAILURE; return E_NOT_OK; } /* @req DCM755 */ Std_ReturnType Dcm_ProcessRequestTransferExit(Dcm_OpStatusType OpStatus, uint8 *ParameterRecord, uint32 ParameterRecordSize, Dcm_NegativeResponseCodeType* ErrorCode) { (void)OpStatus; (void)*ParameterRecord; (void)ParameterRecordSize; *ErrorCode = DCM_E_GENERALPROGRAMMINGFAILURE; return E_NOT_OK; } /** * * @param Data * @param ParameterRecordLength: In: The available buffer size, Out: Number of bytes written to Data */ void Dcm_Arc_GetDownloadResponseParameterRecord(uint8 *Data, uint16 *ParameterRecordLength) { (void)*Data; *ParameterRecordLength = 0; } /** * * @param Data * @param ParameterRecordLength: In: The available buffer size, Out: Number of bytes written to Data */ void Dcm_Arc_GetTransferExitResponseParameterRecord(uint8 *Data, uint16 *ParameterRecordLength) { (void)*Data; *ParameterRecordLength = 0; } /* @req DCM543 */ Std_ReturnType Dcm_SetProgConditions(Dcm_ProgConditionsType *ProgConditions) { (void)*ProgConditions; return E_OK; } /* @req DCM544 */ Dcm_EcuStartModeType Dcm_GetProgConditions(Dcm_ProgConditionsType *ProgConditions) { (void)*ProgConditions; return DCM_COLD_START; } /* @req DCM547 */ void Dcm_Confirmation(Dcm_IdContextType idContext,PduIdType dcmRxPduId,Dcm_ConfirmationStatusType status) { (void)idContext; (void)dcmRxPduId; (void)status; } #ifdef DCM_USE_SERVICE_RESPONSEONEVENT /** * * @param ROEPreConfigPtr * @return E_OK: PreConfig available, E_NOT_OK: PreConfig not available */ Std_ReturnType Dcm_Arc_GetROEPreConfig(const Dcm_ArcROEDidPreconfigType **ROEPreConfigPtr) { (void)ROEPreConfigPtr; //lint !e920 cast from pointer to void return E_NOT_OK; } #endif
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Callout_Stubs.c
C
unknown
5,467
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ //lint -w2 Static code analysis warning level /* * General requirements */ /* @req DCM738 DCM_E_FORCE_RCRRP_OK never used in external service processing */ #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #include "MemMap.h" typedef struct { const PduInfoType *pduRxData; PduInfoType *pduTxData; const Dcm_DsdServiceTableType *serviceTable; Dcm_ProtocolAddrTypeType addrType; PduIdType pdurTxPduId; PduIdType rxPduId; Dcm_ProtocolTransTypeType txType; boolean internalRequest; boolean sendRespPendOnTransToBoot; boolean startupResponseRequest; } MsgDataType; // In "queue" to DSD static boolean dsdDslDataIndication = FALSE; static MsgDataType msgData; static uint8 currentSid; static boolean suppressPosRspMsg; #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) static uint16 Dcm_Dsd_sourceAddress; static Dcm_ProtocolAddrTypeType Dcm_Dsd_requestType; #endif static Dcm_MsgContextType GlobalMessageContext; typedef enum { DCM_SERVICE_IDLE, DCM_SERVICE_PENDING, DCM_SERVICE_WAIT_DONE, DCM_SERVICE_DONE, DCM_SERVICE_WAIT_TX_CONFIRM }ServicePendingStateType; typedef struct { Dcm_NegativeResponseCodeType NRC; ServicePendingStateType state; boolean isSubFnc; uint8 subFncId; }ExternalServiceStateType; static ExternalServiceStateType ExternalService = {.NRC = DCM_E_POSITIVERESPONSE, .state = DCM_SERVICE_IDLE, .isSubFnc = FALSE, .subFncId=0}; /* * Local functions */ #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) /* @req DCM218 */ static Std_ReturnType ServiceIndication(uint8 sid, uint8 *requestData, uint16 dataSize, Dcm_ProtocolAddrTypeType reqType, uint16 sourceAddress, Dcm_NegativeResponseCodeType* errorCode) { Std_ReturnType returnCode = E_OK; const Dcm_DslServiceRequestNotificationType *serviceRequestNotification = Dcm_ConfigPtr->Dsl->DslServiceRequestNotification; /* If any indcation returns E_REQUEST_NOT_ACCEPTED it shall be returned. * If all indcations returns E_OK it shall be returned * Otherwise, E_NOT_OK shall be returned. */ while ((!serviceRequestNotification->Arc_EOL) && (returnCode != E_REQUEST_NOT_ACCEPTED)) { if (serviceRequestNotification->Indication != NULL) { Std_ReturnType result = serviceRequestNotification->Indication(sid, requestData + 1, dataSize - 1, reqType, sourceAddress, errorCode); if ((result == E_REQUEST_NOT_ACCEPTED) || (result == E_NOT_OK)) { returnCode = result; } else if (result != E_OK) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } else { /* E_OK */ } } serviceRequestNotification++; } return returnCode; } static void ServiceConfirmation(uint8 sid, Dcm_ProtocolAddrTypeType reqType, uint16 sourceAddress, NotifResultType result) { Std_ReturnType returnCode = E_OK; const Dcm_DslServiceRequestNotificationType *serviceRequestNotification= Dcm_ConfigPtr->Dsl->DslServiceRequestNotification; /* The values of Dcm_ConfirmationStatusType are not specified, using the following */ Dcm_ConfirmationStatusType status; if (msgData.pduTxData->SduDataPtr[0] == SID_NEGATIVE_RESPONSE) { status = (result == NTFRSLT_OK) ? DCM_RES_NEG_OK: DCM_RES_NEG_NOT_OK; } else { status = (result == NTFRSLT_OK) ? DCM_RES_POS_OK: DCM_RES_POS_NOT_OK; } /* If all indcations returns E_OK it shall be returned * Otherwise, E_NOT_OK shall be returned. */ /* @req DCM770 */ /* @req DCM741 */ while ((!serviceRequestNotification->Arc_EOL) && (returnCode != E_NOT_OK)) { if (serviceRequestNotification->Confirmation != NULL) { /* No way to terminate response like since it is already done */ (void)serviceRequestNotification->Confirmation(sid, reqType, sourceAddress, status); } serviceRequestNotification++; } } #endif #define IS_SUPRESSED_NRC_ON_FUNC_ADDR(_x) ((DCM_E_SERVICENOTSUPPORTED == (_x)) || (DCM_E_SUBFUNCTIONNOTSUPPORTED == (_x)) || (DCM_E_REQUESTOUTOFRANGE == (_x))) static void createAndSendNcr(Dcm_NegativeResponseCodeType responseCode) { PduIdType dummyId = 0; boolean flagdsl; /* Suppress reponse if DCM001 is fulfilled or if it is a type2 response and a NRC */ /* @req DCM001 */ flagdsl = DslPduRPduUsedForType2Tx(msgData.pdurTxPduId, &dummyId); /* Suppress reponse if DCM001 is fulfilled or if it is a type2 response and a NRC */ /* @req DCM001 */ if(((msgData.addrType == DCM_PROTOCOL_FUNCTIONAL_ADDR_TYPE)&&IS_SUPRESSED_NRC_ON_FUNC_ADDR(responseCode))|| ((responseCode != DCM_E_POSITIVERESPONSE )&& (TRUE == flagdsl))){ DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_SUPPRESSED); } else { msgData.pduTxData->SduDataPtr[0] = SID_NEGATIVE_RESPONSE; msgData.pduTxData->SduDataPtr[1] = currentSid; msgData.pduTxData->SduDataPtr[2] = responseCode; msgData.pduTxData->SduLength = 3; DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_READY); /* @req DCM114 */ /* @req DCM232 Ncr */ } } static void setCurrentMessageContext(boolean isSubFunction) { uint8 offset = (TRUE == isSubFunction) ? 2u:1u; GlobalMessageContext.dcmRxPduId = msgData.rxPduId; GlobalMessageContext.idContext = (uint8)msgData.rxPduId; GlobalMessageContext.msgAddInfo.reqType = (msgData.addrType == DCM_PROTOCOL_FUNCTIONAL_ADDR_TYPE)? TRUE: FALSE; GlobalMessageContext.msgAddInfo.suppressPosResponse = suppressPosRspMsg; GlobalMessageContext.reqData = &msgData.pduRxData->SduDataPtr[offset]; GlobalMessageContext.reqDataLen = (Dcm_MsgLenType)(msgData.pduRxData->SduLength - offset); GlobalMessageContext.resData = &msgData.pduTxData->SduDataPtr[offset]; GlobalMessageContext.resDataLen = 0; GlobalMessageContext.resMaxDataLen = (Dcm_MsgLenType)(msgData.pduTxData->SduLength - offset); } /** * Starts processing an external sub service * @param SidCfgPtr */ static void startExternalSubServiceProcessing(const Dcm_DsdSubServiceType *SubCfgPtr) { setCurrentMessageContext(TRUE); ExternalService.NRC = DCM_E_POSITIVERESPONSE; ExternalService.state = DCM_SERVICE_WAIT_DONE; ExternalService.isSubFnc = TRUE; ExternalService.subFncId = SubCfgPtr->DsdSubServiceId; if( (E_PENDING == SubCfgPtr->DsdSubServiceFnc(DCM_INITIAL, &GlobalMessageContext)) && (DCM_SERVICE_WAIT_DONE == ExternalService.state) ) { ExternalService.state = DCM_SERVICE_PENDING; } } /** * Starts processing an external service * @param SidCfgPtr */ static void startExternalServiceProcessing(const Dcm_DsdServiceType *SidCfgPtr) { setCurrentMessageContext(FALSE); ExternalService.NRC = DCM_E_POSITIVERESPONSE; ExternalService.state = DCM_SERVICE_WAIT_DONE; ExternalService.isSubFnc = FALSE; /* @req DCM732 */ /* @req DCM760 */ if( (E_PENDING == SidCfgPtr->DspSidTabFnc(DCM_INITIAL, &GlobalMessageContext)) && (DCM_SERVICE_WAIT_DONE == ExternalService.state) ) { ExternalService.state = DCM_SERVICE_PENDING; } } /** * Runs an internal diagnostic service * @param SID */ static void runInternalService(uint8 SID) { switch(SID) { #ifdef DCM_USE_SERVICE_DIAGNOSTICSESSIONCONTROL case SID_DIAGNOSTIC_SESSION_CONTROL: DspUdsDiagnosticSessionControl(msgData.pduRxData, msgData.pdurTxPduId, msgData.pduTxData, msgData.sendRespPendOnTransToBoot, msgData.internalRequest); break; #endif #ifdef DCM_USE_SERVICE_LINKCONTROL case SID_LINK_CONTROL: DspUdsLinkControl(msgData.pduRxData, msgData.pdurTxPduId, msgData.pduTxData, msgData.sendRespPendOnTransToBoot); break; #endif #ifdef DCM_USE_SERVICE_ECURESET case SID_ECU_RESET: DspUdsEcuReset(msgData.pduRxData, msgData.pdurTxPduId, msgData.pduTxData, msgData.startupResponseRequest); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CLEARDIAGNOSTICINFORMATION) case SID_CLEAR_DIAGNOSTIC_INFORMATION: DspUdsClearDiagnosticInformation(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_READDTCINFORMATION) case SID_READ_DTC_INFORMATION: DspUdsReadDtcInformation(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_READDATABYIDENTIFIER case SID_READ_DATA_BY_IDENTIFIER: DspUdsReadDataByIdentifier(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_READMEMORYBYADDRESS case SID_READ_MEMORY_BY_ADDRESS: DspUdsReadMemoryByAddress(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_WRITEMEMORYBYADDRESS case SID_WRITE_MEMORY_BY_ADDRESS: DspUdsWriteMemoryByAddress(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_READSCALINGDATABYIDENTIFIER case SID_READ_SCALING_DATA_BY_IDENTIFIER: DspUdsReadScalingDataByIdentifier(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_SECURITYACCESS case SID_SECURITY_ACCESS: DspUdsSecurityAccess(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER case SID_WRITE_DATA_BY_IDENTIFIER: DspUdsWriteDataByIdentifier(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_ROUTINECONTROL case SID_ROUTINE_CONTROL: DspUdsRoutineControl(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_TESTERPRESENT case SID_TESTER_PRESENT: DspUdsTesterPresent(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) case SID_CONTROL_DTC_SETTING: DspUdsControlDtcSetting(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_RESPONSEONEVENT case SID_RESPONSE_ON_EVENT: DspResponseOnEvent(msgData.pduRxData, msgData.rxPduId, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER case SID_READ_DATA_BY_PERIODIC_IDENTIFIER: DspReadDataByPeriodicIdentifier(msgData.pduRxData, msgData.pduTxData, msgData.rxPduId, msgData.txType, msgData.internalRequest); break; #endif #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER case SID_DYNAMICALLY_DEFINE_DATA_IDENTIFIER: DspDynamicallyDefineDataIdentifier(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER case SID_INPUT_OUTPUT_CONTROL_BY_IDENTIFIER: DspIOControlByDataIdentifier(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL case SID_COMMUNICATION_CONTROL: DspCommunicationControl(msgData.pduRxData, msgData.pduTxData, msgData.rxPduId, msgData.pdurTxPduId); break; #endif #ifdef DCM_USE_SERVICE_REQUESTDOWNLOAD case SID_REQUEST_DOWNLOAD: DspUdsRequestDownload(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_REQUESTUPLOAD case SID_REQUEST_UPLOAD: DspUdsRequestUpload(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_TRANSFERDATA case SID_TRANSFER_DATA: DspUdsTransferData(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_REQUESTTRANSFEREXIT case SID_REQUEST_TRANSFER_EXIT: DspUdsRequestTransferExit(msgData.pduRxData, msgData.pduTxData); break; #endif /* OBD */ #ifdef DCM_USE_SERVICE_REQUESTCURRENTPOWERTRAINDIAGNOSTICDATA case SID_REQUEST_CURRENT_POWERTRAIN_DIAGNOSTIC_DATA: DspObdRequestCurrentPowertrainDiagnosticData(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTPOWERTRAINFREEZEFRAMEDATA) case SID_REQUEST_POWERTRAIN_FREEZE_FRAME_DATA: DspObdRequestPowertrainFreezeFrameData(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CLEAREMISSIONRELATEDDIAGNOSTICDATA) case SID_CLEAR_EMISSION_RELATED_DIAGNOSTIC_INFORMATION: DspObdClearEmissionRelatedDiagnosticData(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDIAGNOSTICTROUBLECODES) case SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES: DspObdRequestEmissionRelatedDiagnosticTroubleCodes(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(DCM_USE_SERVICE_ONBOARDMONITORINGTESTRESULTSSPECIFICMONITOREDSYSTEMS) case SID_REQUEST_ON_BOARD_MONITORING_TEST_RESULTS_SPECIFIC_MONITORED_SYSTEMS: DspObdRequestOnBoardMonitoringTestResultsService06(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSDETECTEDDURINGCURRENTORLASTCOMPLETEDDRIVINGCYCLE) case SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES_DETECTED_DURING_CURRENT_OR_LAST_COMPLETED_DRIVING_CYCLE: DspObdRequestEmissionRelatedDiagnosticTroubleCodesService07(msgData.pduRxData, msgData.pduTxData); break; #endif #ifdef DCM_USE_SERVICE_REQUESTVEHICLEINFORMATION case SID_REQUEST_VEHICLE_INFORMATION: DspObdRequestVehicleInformation(msgData.pduRxData, msgData.pduTxData); break; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSWITHPERMANENTSTATUS) case SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES_WITH_PERMANENT_STATUS: DspObdRequestEmissionRelatedDiagnosticTroubleCodesWithPermanentStatus(msgData.pduRxData, msgData.pduTxData); break; #endif /* OBD */ default: /* Non implemented service */ createAndSendNcr(DCM_E_SERVICENOTSUPPORTED); break; } } static void selectServiceFunction(const Dcm_DsdServiceType *sidConfPtr) { /* !req DCM442 Services missing */ /* Check if subfunction supported */ boolean processService = TRUE; const Dcm_DsdSubServiceType *subServicePtr; Dcm_NegativeResponseCodeType respCode; if( sidConfPtr->DsdSidTabSubfuncAvail == TRUE ) { if( msgData.pduRxData->SduLength > 1 ) { /* @req DCM696 */ if( NULL_PTR == sidConfPtr->DsdSubServiceList ) { /* This to be backwards compatible. If no sub-function configured, * behave as all are supported. */ } else if( TRUE == DsdLookupSubService(currentSid, sidConfPtr, msgData.pduRxData->SduDataPtr[1], &subServicePtr, &respCode) ) { if( DCM_E_POSITIVERESPONSE == respCode ) { if( NULL_PTR != subServicePtr->DsdSubServiceFnc ) { startExternalSubServiceProcessing(subServicePtr); processService = FALSE; } } else { /* Sub-function supported but currently not available */ createAndSendNcr(respCode); processService = FALSE; } } else { /* Sub-function not supported */ createAndSendNcr(DCM_E_SUBFUNCTIONNOTSUPPORTED); processService = FALSE; } } else { /* Not enough data for Sub-function */ createAndSendNcr(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); processService = FALSE; } } if(TRUE == processService) { /* @req DCM221 */ runInternalService(sidConfPtr->DsdSidTabServiceId); } } /** * Checks if a service is supported * @param sid * @param sidPtr * @return TRUE: Service supported, FALSE: Service not supported */ static boolean lookupSid(uint8 sid, const Dcm_DsdServiceType **sidPtr) { boolean returnStatus = FALSE; *sidPtr = NULL_PTR; const Dcm_DsdServiceType *service; if(NULL_PTR != msgData.serviceTable) { service = msgData.serviceTable->DsdService; while ((service->DsdSidTabServiceId != sid) && (FALSE == service->Arc_EOL)) { service++; } if (FALSE == service->Arc_EOL) { *sidPtr = service; returnStatus = TRUE; } } return returnStatus; } /** * Runs an external service * @param opStatus * @return */ static Std_ReturnType DslRunExternalServices(Dcm_OpStatusType opStatus) { Std_ReturnType ret = E_NOT_OK; const Dcm_DsdServiceType *sidCfgPtr = NULL_PTR; if(TRUE == lookupSid(currentSid, &sidCfgPtr)) { if( TRUE == ExternalService.isSubFnc ) { const Dcm_DsdSubServiceType *subServicePtr; Dcm_NegativeResponseCodeType resp; if(( TRUE == DsdLookupSubService(currentSid, sidCfgPtr, ExternalService.subFncId, &subServicePtr, &resp)) && (NULL_PTR != subServicePtr->DsdSubServiceFnc)) { ret = subServicePtr->DsdSubServiceFnc(opStatus, NULL_PTR); } } else { if( NULL_PTR != sidCfgPtr->DspSidTabFnc ) { ret = sidCfgPtr->DspSidTabFnc(opStatus, NULL_PTR); } } } return ret; } /** * Main function for external service processing. */ static void externalServiceMainFunction() { /* @req DCM760 */ if( DCM_SERVICE_IDLE != ExternalService.state ) { if( DCM_SERVICE_PENDING == ExternalService.state ) { if((E_PENDING != DslRunExternalServices(DCM_PENDING)) && (DCM_SERVICE_PENDING == ExternalService.state)) { /* Service did not return pending and was not finished within the context of * service function. Wait for it to complete */ ExternalService.state = DCM_SERVICE_WAIT_DONE; } } if( DCM_SERVICE_DONE == ExternalService.state ) { if( DCM_E_POSITIVERESPONSE != ExternalService.NRC ) { DsdDspProcessingDone(ExternalService.NRC); } else { /* Create a positive response */ msgData.pduTxData->SduLength++; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } ExternalService.state = DCM_SERVICE_WAIT_TX_CONFIRM; } } } /* * Exported functions */ /** * Cancels a pending external service */ void DsdCancelPendingExternalServices(void) { if( (DCM_SERVICE_PENDING == ExternalService.state) || (DCM_SERVICE_WAIT_DONE == ExternalService.state) ) { /* @req DCM735 */ (void)DslRunExternalServices(DCM_CANCEL); } ExternalService.state = DCM_SERVICE_IDLE; } /** * Sets negative response of external service * @param pMsgContext * @param ErrorCode */ void DsdExternalSetNegResponse(const Dcm_MsgContextType* pMsgContext, Dcm_NegativeResponseCodeType ErrorCode) { if(pMsgContext->dcmRxPduId == GlobalMessageContext.dcmRxPduId) { ExternalService.NRC = ErrorCode; } } /** * Sets external service processing to done * @param pMsgContext */ void DsdExternalProcessingDone(const Dcm_MsgContextType* pMsgContext) { if(pMsgContext->dcmRxPduId == GlobalMessageContext.dcmRxPduId) { ExternalService.state = DCM_SERVICE_DONE; if( DCM_E_POSITIVERESPONSE == ExternalService.NRC ) { if(TRUE == ExternalService.isSubFnc) { memcpy(&msgData.pduTxData->SduDataPtr[2], pMsgContext->resData, pMsgContext->resDataLen); msgData.pduTxData->SduLength = (PduLengthType)pMsgContext->resDataLen; msgData.pduTxData->SduDataPtr[1] = ExternalService.subFncId; msgData.pduTxData->SduLength++; } else { memcpy(&msgData.pduTxData->SduDataPtr[1], pMsgContext->resData, pMsgContext->resDataLen); msgData.pduTxData->SduLength =(PduLengthType)pMsgContext->resDataLen; } } } } /** * Confirms transmission of response to externally processed service * @param result */ static void DcmConfirmation(NotifResultType result) { Dcm_ConfirmationStatusType status; if( DCM_SERVICE_WAIT_TX_CONFIRM == ExternalService.state) { if( NTFRSLT_OK == result ) { status = (DCM_E_POSITIVERESPONSE == ExternalService.NRC) ? DCM_RES_POS_OK:DCM_RES_NEG_OK; } else { status = (DCM_E_POSITIVERESPONSE == ExternalService.NRC) ? DCM_RES_POS_NOT_OK:DCM_RES_NEG_NOT_OK; } Dcm_Confirmation(GlobalMessageContext.idContext, GlobalMessageContext.dcmRxPduId, status); ExternalService.state = DCM_SERVICE_IDLE; } } void DsdInit(void) { } void DsdMain(void) { if (TRUE == dsdDslDataIndication) { dsdDslDataIndication = FALSE; DsdHandleRequest(); } /* @req DCM734 */ externalServiceMainFunction(); } /** * Checks if a sub-function for a service is supported and available in the current session and security level * @param sidConfPtr * @param subService * @param subServicePtr * @param respCode * @return TRUE: Sub-function supported, FALSE: Sub-function not supported */ #define ROE_STORAGE_STATE (1u<<6u) boolean DsdLookupSubService(uint8 SID, const Dcm_DsdServiceType *sidConfPtr, uint8 subService, const Dcm_DsdSubServiceType **subServicePtr, Dcm_NegativeResponseCodeType *respCode) { boolean found = FALSE; *respCode = DCM_E_POSITIVERESPONSE; if( (NULL_PTR != sidConfPtr) && (TRUE == sidConfPtr->DsdSidTabSubfuncAvail) && (NULL_PTR != sidConfPtr->DsdSubServiceList) ) { uint8 indx = 0; while( FALSE == sidConfPtr->DsdSubServiceList[indx].Arc_EOL ) { if( (subService == sidConfPtr->DsdSubServiceList[indx].DsdSubServiceId) || ((SID_RESPONSE_ON_EVENT == SID) && (subService == (sidConfPtr->DsdSubServiceList[indx].DsdSubServiceId | ROE_STORAGE_STATE))) ) { *subServicePtr = &sidConfPtr->DsdSubServiceList[indx]; if(TRUE == DspCheckSessionLevel(sidConfPtr->DsdSubServiceList[indx].DsdSubServiceSessionLevelRef)) { if(FALSE == DspCheckSecurityLevel(sidConfPtr->DsdSubServiceList[indx].DsdSubServiceSecurityLevelRef) ) { /* @req DCM617 */ *respCode = DCM_E_SECURITYACCESSDENIED; } } else { *respCode = DCM_E_SUBFUNCTIONNOTSUPPORTEDINACTIVESESSION; } found = TRUE; } indx++; } } return found; } void DsdHandleRequest(void) { Std_ReturnType result = E_OK; const Dcm_DsdServiceType *sidConfPtr = NULL_PTR; Dcm_NegativeResponseCodeType errorCode ; errorCode= DCM_E_POSITIVERESPONSE; if( msgData.pduRxData->SduLength > 0 ) { currentSid = msgData.pduRxData->SduDataPtr[0]; /* @req DCM198 */ #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) /* @req DCM218 */ Dcm_ProtocolType dummyProtocolId; if( E_OK == Arc_DslGetRxConnectionParams(msgData.rxPduId, &Dcm_Dsd_sourceAddress, &Dcm_Dsd_requestType, &dummyProtocolId) ) { result = ServiceIndication(currentSid, msgData.pduRxData->SduDataPtr, msgData.pduRxData->SduLength, Dcm_Dsd_requestType, Dcm_Dsd_sourceAddress, &errorCode); } #endif } if (( 0 == msgData.pduRxData->SduLength) || (E_REQUEST_NOT_ACCEPTED == result)) { /*lint !e845 !e774 result value updated under DCM_MANUFACTURER_NOTIFICATION */ /* Special case with sdu length 0, No service id so we cannot send response. */ /* @req DCM677 */ /* @req DCM462 */ // Do not send any response /* @req DCM462 */ /* @req DCM677 */ DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_SUPPRESSED); } else if (result != E_OK) { /*lint !e774 result value updated under DCM_MANUFACTURER_NOTIFICATION */ /* @req DCM678 */ /* @req DCM463 */ createAndSendNcr(errorCode); /* @req DCM463 */ } /* @req DCM178 */ //lint --e(506, 774) PC-Lint exception Misra 13.7, 14.1 Allow configuration variables in boolean expression else if ((DCM_RESPOND_ALL_REQUEST == STD_ON) || ((currentSid & 0x7Fu) < 0x40)) { /* @req DCM084 */ if (TRUE == lookupSid(currentSid, &sidConfPtr)) { /* @req DCM192 */ /* @req DCM193 */ // SID found! /* Skip checks if service is supported in current session and security level if it is a startup response request * and the request should be handled internally (as the service is performed by bootloader and we should only respond) */ boolean skipSesAndSecChecks = (msgData.startupResponseRequest && (NULL_PTR == sidConfPtr->DspSidTabFnc))? TRUE: FALSE; if ((TRUE == skipSesAndSecChecks) || (TRUE == DspCheckSessionLevel(sidConfPtr->DsdSidTabSessionLevelRef))) { /* @req DCM211 */ if ((TRUE == skipSesAndSecChecks) || (TRUE == DspCheckSecurityLevel(sidConfPtr->DsdSidTabSecurityLevelRef))) { /* @req DCM217 */ //lint --e(506, 774) PC-Lint exception Misra 13.7, 14.1 Allow configuration variables in boolean expression //lint --e(506, 774) PC-Lint exception Misra 13.7, 14.1 Allow configuration variables in boolean expression if ( (TRUE == sidConfPtr->DsdSidTabSubfuncAvail) && (SUPPRESS_POS_RESP_BIT == (msgData.pduRxData->SduDataPtr[1] & SUPPRESS_POS_RESP_BIT) )) { /* @req DCM204 */ suppressPosRspMsg = TRUE; /* @req DCM202 */ msgData.pduRxData->SduDataPtr[1] &= ~SUPPRESS_POS_RESP_BIT; /* @req DCM201 */ } else { suppressPosRspMsg = FALSE; /* @req DCM202 */ } #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) DslSetDspProcessingActive(msgData.rxPduId, TRUE); #endif if( NULL_PTR != sidConfPtr->DspSidTabFnc ) { /* @req DCM196 */ startExternalServiceProcessing(sidConfPtr); } else { selectServiceFunction(sidConfPtr); } #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) DslSetDspProcessingActive(msgData.rxPduId, FALSE); #endif } else { createAndSendNcr(DCM_E_SECURITYACCESSDENIED); /* @req DCM217 */ } } else { createAndSendNcr(DCM_E_SERVICENOTSUPPORTEDINACTIVESESSION); /* @req DCM211 */ } } else { createAndSendNcr(DCM_E_SERVICENOTSUPPORTED); /* @req DCM197 */ } } else { // Inform DSL that message has been discard DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_SUPPRESSED); } /*lint -e{438} errorCode last value assigned not used because value updated under DCM_MANUFACTURER_NOTIFICATION */ } void DsdDspProcessingDone(Dcm_NegativeResponseCodeType responseCode) { PduIdType dummyId = 0; if (responseCode == DCM_E_POSITIVERESPONSE) { if (suppressPosRspMsg == FALSE) { /* @req DCM200 */ /* @req DCM231 */ /* @req DCM222 */ if( FALSE == DslPduRPduUsedForType2Tx(msgData.pdurTxPduId, &dummyId) ) { /* @req DCM223 */ /* @req DCM224 */ msgData.pduTxData->SduDataPtr[0] = currentSid | SID_RESPONSE_BIT; } /* @req DCM114 */ /* @req DCM225 */ /* @req DCM232 Ok */ DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_READY); } else { /* @req DCM236 */ /* @req DCM240 */ DspDcmConfirmation(msgData.pdurTxPduId, NTFRSLT_OK); DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_SUPPRESSED); DcmConfirmation(NTFRSLT_OK); } } else { /* @req DCM228 */ createAndSendNcr(responseCode); } } #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) /** * Gets the tester source address of the current request * @return Tester source address */ uint16 DsdDspGetTesterSourceAddress(void) { uint16 testerSrcAddr; Dcm_ProtocolAddrTypeType reqType; Dcm_ProtocolType dummyProtocolId; if(E_OK != Arc_DslGetRxConnectionParams(msgData.rxPduId, &testerSrcAddr, &reqType, &dummyProtocolId) ) { testerSrcAddr = 0xFFFF; } return testerSrcAddr; } /** * Used to determine if a response is required to the current request * @return TRUE: Response required, FALSE: Response not required */ boolean DsdDspGetResponseRequired(void) { return (FALSE == suppressPosRspMsg)? TRUE: FALSE; } #endif /** * Forces out a negative response 0x78 (requestCorrectlyReceivedResponsePending) */ void DsdDspForceResponsePending(void) { DslDsdSendResponsePending(msgData.rxPduId); } void DsdDspProcessingDone_ReadDataByPeriodicIdentifier(Dcm_NegativeResponseCodeType responseCode, boolean supressNRC) { if((TRUE == supressNRC) && (DCM_E_POSITIVERESPONSE != responseCode)) { DslDsdProcessingDone(msgData.rxPduId, DSD_TX_RESPONSE_SUPPRESSED); } else { DsdDspProcessingDone(responseCode); } } void DsdDataConfirmation(PduIdType confirmPduId, NotifResultType result) { DspDcmConfirmation(confirmPduId, result); /* @req DCM236 */ #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) /* @req DCM742 */ ServiceConfirmation(currentSid, Dcm_Dsd_requestType, Dcm_Dsd_sourceAddress, result); #endif DcmConfirmation(result); } #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) /** * Forwards a tx confirmation of NRC 0x78 to Dsp * @param confirmPduId * @param result */ void DsdResponsePendingConfirmed(PduIdType confirmPduId, NotifResultType result) { if(NTFRSLT_OK == result) { DspResponsePendingConfirmed(confirmPduId); } } #endif void DsdDslDataIndication(const PduInfoType *pduRxData, const Dcm_DsdServiceTableType *protocolSIDTable, Dcm_ProtocolAddrTypeType addrType, PduIdType txPduId, PduInfoType *pduTxData, PduIdType rxContextPduId, Dcm_ProtocolTransTypeType txType, boolean internalRequest, boolean sendRespPendOnTransToBoot, boolean startupResponseRequest) { msgData.rxPduId = rxContextPduId; msgData.pdurTxPduId = txPduId; msgData.pduRxData = pduRxData; msgData.pduTxData = pduTxData; msgData.addrType = addrType; msgData.serviceTable = protocolSIDTable; /* @req DCM195 */ msgData.txType = txType; msgData.internalRequest = internalRequest; msgData.sendRespPendOnTransToBoot = sendRespPendOnTransToBoot; msgData.startupResponseRequest = startupResponseRequest; dsdDslDataIndication = TRUE; } //OBD: called by DSL to get the current Tx PduId //IMPROVEMENT: Perhaps remove this? PduIdType DsdDslGetCurrentTxPduId(void) { return msgData.pdurTxPduId; } #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) || defined(DCM_USE_SERVICE_COMMUNICATIONCONTROL) || defined(DCM_USE_CONTROL_DIDS) || (defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING)) boolean DsdDspCheckServiceSupportedInActiveSessionAndSecurity(uint8 sid) { boolean ret = FALSE; boolean flagSecuLevl; boolean flagSessionLevl; boolean flaglukupsid; const Dcm_DsdServiceType *sidConfPtr = NULL; flaglukupsid =lookupSid(sid, &sidConfPtr); if(TRUE == flaglukupsid ){ flagSessionLevl = DspCheckSessionLevel(sidConfPtr->DsdSidTabSessionLevelRef); flagSecuLevl = DspCheckSecurityLevel(sidConfPtr->DsdSidTabSecurityLevelRef); if((TRUE == flagSessionLevl) && (TRUE == flagSecuLevl)){ /* Service is supported for the active protocol in the * current session and security level */ ret = TRUE; } } return ret; } #endif #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) void DsdSetDspProcessingActive(boolean state) { DslSetDspProcessingActive(msgData.rxPduId, state); } #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL /** * Function used by Dsp to get the current protocol * @param protocolRx * @return */ Std_ReturnType DsdDspGetCurrentProtocolRx(PduIdType rxPduId, const Dcm_DslProtocolRxType **protocolRx) { return DslDsdGetProtocolRx(rxPduId, protocolRx); } #endif /** * Clears suppress positive message bit */ void DsdClearSuppressPosRspMsg(void) { suppressPosRspMsg = FALSE; }
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Dsd.c
C
unknown
34,893
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ //lint -w2 Static code analysis warning level /* * General requirements */ /* @req DCM030 */ /* @req DCM027 */ /* @req DCM143 P2min and P2*min not used, responses sent a soon as available. S3Server set to 5s by generator */ #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #include "MemMap.h" #if defined(USE_COMM) #include "ComM_Dcm.h" #endif #include "PduR_Dcm.h" #include "PduR_Types.h" // OBD: for preemption cancel PDUR tx #include "PduR.h" // OBD: for cancel #include "ComStack_Types.h" #include "Cpu.h" #include "debug.h" #ifndef DCM_NOT_SERVICE_COMPONENT #include "Rte_Dcm.h" #endif #include "SchM_Dcm.h" #define DECREMENT(timer) { if (timer > 0){timer--;} } #define DCM_CONVERT_MS_TO_MAIN_CYCLES(x) ((x)/DCM_MAIN_FUNCTION_PERIOD_TIME_MS) #if (DCM_PAGEDBUFFER_ENABLED) #error "DCM_PAGEDBUFFER_ENABLED is set to STD_ON, this is not supported by the code." #endif #define DCM_TYPE2_TX_ROUTED_TO_IF #if DCM_NOF_PERIODIC_TX_PDU > 0 #define DCM_USE_TYPE2_PERIODIC_TRANSMISSION #endif /* * Type definitions. */ typedef struct { boolean initRun; const Dcm_DslProtocolRowType *activeProtocol; // Points to the currently active protocol. } DcmDsl_RunTimeDataType; static DcmDsl_RunTimeDataType DcmDslRunTimeData = { .initRun = FALSE, .activeProtocol = NULL }; #ifdef DCM_USE_TYPE2_PERIODIC_TRANSMISSION typedef struct { PduIdType diagReqRxPduId; boolean pduInUse; }PeriodicPduStatusType; static PeriodicPduStatusType PeriodicPduStatus[DCM_NOF_PERIODIC_TX_PDU]; #endif #if defined(USE_COMM) static DcmComModeType NetWorkComMode[DCM_NOF_COMM_CHANNELS]; #endif // OBD: define the status flag of processing done when preemption happens. static boolean PreemptionNotProcessingDone = FALSE; static boolean BusySent = FALSE; static void DslReleaseType2TxPdu(PduIdType txPduId); static void DslReleaseAllType2TxPdus(void); static boolean DslCheckType2TxPduAvailable(const Dcm_DslMainConnectionType *mainConnection); // ################# HELPER FUNCTIONS START ################# // // This function reset/stars the session (S3) timer. See requirement // DCM141 when that action should be taken. // static inline void startS3SessionTimer(Dcm_DslRunTimeProtocolParametersType *runtime, const Dcm_DslProtocolRowType *protocolRow) { const Dcm_DslProtocolTimingRowType *timeParams; timeParams = protocolRow->DslProtocolTimeLimit; runtime->S3ServerTimeoutCount = DCM_CONVERT_MS_TO_MAIN_CYCLES(timeParams->TimStrS3Server); runtime->S3ServerStarted = TRUE; } // - - - - - - - - - - - const Dcm_DspSessionRowType *getActiveSessionRow(const Dcm_DslRunTimeProtocolParametersType *runtime); // // This function reset/stars the session (S3) timer. See requirement // DCM141 when that action should be taken. // static inline void stopS3SessionTimer(Dcm_DslRunTimeProtocolParametersType *runtime) { runtime->S3ServerStarted = FALSE; } // - - - - - - - - - - - // OBD: This function reset/stars the preempt timer. // static inline void startPreemptTimer(Dcm_DslRunTimeProtocolParametersType *runtime, const Dcm_DslProtocolRowType *protocolRow) { runtime->preemptTimeoutCount= DCM_CONVERT_MS_TO_MAIN_CYCLES(protocolRow->DslProtocolPreemptTimeout); } #if defined(USE_COMM) static boolean findProtocolRx(PduIdType dcmRxPduId, const Dcm_DslProtocolRxType **protocolRx) { boolean ret = FALSE; if (dcmRxPduId < DCM_DSL_RX_PDU_ID_LIST_LENGTH) { *protocolRx = &Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRxGlobalList[dcmRxPduId]; ret = TRUE; } return ret; } #endif const Dcm_DspSessionRowType *getActiveSessionRow(const Dcm_DslRunTimeProtocolParametersType *runtime) { const Dcm_DspSessionRowType *sessionRow = Dcm_ConfigPtr->Dsp->DspSession->DspSessionRow; while ((sessionRow->DspSessionLevel != runtime->sessionControl) && (FALSE == sessionRow->Arc_EOL) ) { sessionRow++; } if( TRUE == sessionRow->Arc_EOL ) { /* Since we are in a session with no configuration - take any session configuration and report error */ DCM_DET_REPORTERROR(DCM_CHANGE_DIAGNOSTIC_SESSION_ID, DCM_E_CONFIG_INVALID); sessionRow = Dcm_ConfigPtr->Dsp->DspSession->DspSessionRow; } return sessionRow; } // - - - - - - - - - - - // // This function implements the requirement DCM139 when // transition from one session to another. // static void changeDiagnosticSession(Dcm_DslRunTimeProtocolParametersType *runtime, Dcm_SesCtrlType newSession) { /* @req DCM139 */ #if defined(USE_COMM) const Dcm_DslProtocolRxType *protocolRx = NULL; boolean flagprotoRx; #endif if( DCM_DEFAULT_SESSION == runtime->sessionControl ) { /* to set the dsp buffer to default*/ DspInit(FALSE); } else { runtime->securityLevel = DCM_SEC_LEV_LOCKED; // "0x00". } if( DCM_DEFAULT_SESSION == newSession ) { #if defined(USE_COMM) if(DCM_DEFAULT_SESSION != runtime->sessionControl) { flagprotoRx = findProtocolRx(runtime->diagReqestRxPduId, &protocolRx); if( TRUE == flagprotoRx ) { /* Changing from non-default session to default session */ if( runtime->diagnosticActiveComM == TRUE) { /* @req DCM168 */ ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); runtime->diagnosticActiveComM = FALSE; } } } #endif } else { #if defined(USE_COMM) flagprotoRx = findProtocolRx(runtime->diagReqestRxPduId, &protocolRx); if( (newSession != runtime->sessionControl) && (TRUE == flagprotoRx) ) { /* Changing session */ if( runtime->diagnosticActiveComM == FALSE ) { /* @req DCM167 */ ComM_DCM_ActiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); runtime->diagnosticActiveComM = TRUE; } } #endif } runtime->sessionControl = newSession; /* @req DCM628 */ DcmResetDiagnosticActivityOnSessionChange(newSession); /* IMPROVEMENT: Should be a call to SchM */ const Dcm_DspSessionRowType *sessionRow = getActiveSessionRow(runtime); (void)Rte_Switch_DcmDiagnosticSessionControl_DcmDiagnosticSessionControl(sessionRow->ArcDspRteSessionLevelName); } // - - - - - - - - - - - void DslResetSessionTimeoutTimer(void) { const Dcm_DslProtocolRowType *activeProtocol; Dcm_DslRunTimeProtocolParametersType *runtime; activeProtocol = DcmDslRunTimeData.activeProtocol; if( NULL != activeProtocol ) { runtime = activeProtocol->DslRunTimeProtocolParameters; startS3SessionTimer(runtime, activeProtocol); /* @req DCM141 */ } } // - - - - - - - - - - - Std_ReturnType DslGetActiveProtocol(Dcm_ProtocolType *protocolId) { /* @req DCM340 */ Std_ReturnType ret = E_NOT_OK; const Dcm_DslProtocolRowType *activeProtocol; activeProtocol = DcmDslRunTimeData.activeProtocol; if (activeProtocol != NULL) { *protocolId = activeProtocol->DslProtocolID; ret = E_OK; } return ret; } // - - - - - - - - - - - void DslInternal_SetSecurityLevel(Dcm_SecLevelType secLevel) { /* @req DCM020 */ const Dcm_DslProtocolRowType *activeProtocol; Dcm_DslRunTimeProtocolParametersType *runtime; activeProtocol = DcmDslRunTimeData.activeProtocol; runtime = activeProtocol->DslRunTimeProtocolParameters; runtime->securityLevel = secLevel; } // - - - - - - - - - - - Std_ReturnType DslGetSecurityLevel(Dcm_SecLevelType *secLevel) { /* @req DCM020 */ /* @req DCM338 */ Std_ReturnType ret = E_NOT_OK; const Dcm_DslProtocolRowType *activeProtocol; const Dcm_DslRunTimeProtocolParametersType *runtime = NULL; activeProtocol = DcmDslRunTimeData.activeProtocol; if (activeProtocol != NULL) { runtime = activeProtocol->DslRunTimeProtocolParameters; *secLevel = runtime->securityLevel; ret = E_OK; } return ret; } // - - - - - - - - - - - /* @req DCM022 */ void DslSetSesCtrlType(Dcm_SesCtrlType sesCtrl) { const Dcm_DslProtocolRowType *activeProtocol; Dcm_DslRunTimeProtocolParametersType *runtime; runtime = NULL; activeProtocol = DcmDslRunTimeData.activeProtocol; if (activeProtocol != NULL) { /* This also checks that the module is initiated */ runtime = activeProtocol->DslRunTimeProtocolParameters; changeDiagnosticSession(runtime, sesCtrl); DslResetSessionTimeoutTimer(); } } // - - - - - - - - - - - /* @req DCM022 */ /* @req DCM339 */ Std_ReturnType DslGetSesCtrlType(Dcm_SesCtrlType *sesCtrlType) { Std_ReturnType ret = E_NOT_OK; const Dcm_DslProtocolRowType *activeProtocol; const Dcm_DslRunTimeProtocolParametersType *runtime; runtime = NULL; activeProtocol = DcmDslRunTimeData.activeProtocol; if (activeProtocol != NULL) { runtime = activeProtocol->DslRunTimeProtocolParameters; *sesCtrlType = runtime->sessionControl; ret = E_OK; } return ret; } // - - - - - - - - - - - static boolean findRxPduIdParentConfigurationLeafs(PduIdType dcmRxPduId, const Dcm_DslProtocolRxType **protocolRx, const Dcm_DslMainConnectionType **mainConnection, const Dcm_DslConnectionType **connection, const Dcm_DslProtocolRowType **protocolRow, Dcm_DslRunTimeProtocolParametersType **runtime) { boolean ret = FALSE; if (dcmRxPduId < DCM_DSL_RX_PDU_ID_LIST_LENGTH) { *protocolRx = &Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRxGlobalList[dcmRxPduId]; *mainConnection = (*protocolRx)->DslMainConnectionParent; *connection = (*mainConnection)->DslConnectionParent; *protocolRow = (*connection)->DslProtocolRow; *runtime = (*protocolRow)->DslRunTimeProtocolParameters; ret = TRUE; } return ret; } // - - - - - - - - - - - static boolean findTxPduIdParentConfigurationLeafs(PduIdType dcmTxPduId, const Dcm_DslProtocolRowType **protocolRow, Dcm_DslRunTimeProtocolParametersType **runtime) { boolean ret = FALSE; if (dcmTxPduId < DCM_DSL_TX_PDU_ID_LIST_LENGTH) { const Dcm_DslMainConnectionType *mainConnection; mainConnection = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolTxGlobalList[dcmTxPduId].DslMainConnectionParent; *protocolRow = mainConnection->DslConnectionParent->DslProtocolRow; *runtime = (*protocolRow)->DslRunTimeProtocolParameters; ret = TRUE; } else if(IS_PERIODIC_TX_PDU(dcmTxPduId)) { *protocolRow = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolPeriodicTxGlobalList[TO_INTERNAL_PERIODIC_PDU(dcmTxPduId)].DslProtocolRow; *runtime = (*protocolRow)->DslRunTimeProtocolParameters; ret = TRUE; }else{ /* do nothing */ } return ret; } // - - - - - - - - - - - static inline void releaseExternalRxTxBuffers(const Dcm_DslProtocolRowType *protocolRow, Dcm_DslRunTimeProtocolParametersType *runtime) { #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) SchM_Enter_Dcm_EA_0(); if( !protocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->dspProcessingActive ) { protocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; protocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->DcmRxPduId = DCM_INVALID_PDU_ID; runtime->externalTxBufferStatus = NOT_IN_USE; // We are waiting for DSD to return the buffer. qqq. } else { runtime->externalTxBufferStatus = PENDING_BUFFER_RELEASE; } if( NULL != protocolRow->DslProtocolRxBufferID ) { if(!protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->dspProcessingActive) { runtime->externalRxBufferStatus = NOT_IN_USE; // We are waiting for DSD to return the buffer. qqq. protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } else { runtime->externalRxBufferStatus = PENDING_BUFFER_RELEASE; } } SchM_Exit_Dcm_EA_0(); #else protocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; if(NULL != protocolRow->DslProtocolRxBufferID) { protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } runtime->externalTxBufferStatus = NOT_IN_USE; // We are waiting for DSD to return the buffer. qqq. runtime->externalRxBufferStatus = NOT_IN_USE; // We are waiting for DSD to return the buffer. qqq. protocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->DcmRxPduId = DCM_INVALID_PDU_ID; #endif if(TRUE == runtime->isType2Tx) { /* Release xx buffer for the periodic protocol */ const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *rxProtocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *rxRuntime = NULL; if(TRUE == findRxPduIdParentConfigurationLeafs(runtime->diagReqestRxPduId, &protocolRx, &mainConnection, &connection, &rxProtocolRow, &rxRuntime)) { #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) if( !mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->dspProcessingActive ) { mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters->externalTxBufferStatus = NOT_IN_USE; } else { mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters->externalTxBufferStatus = PENDING_BUFFER_RELEASE; } #else mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslProtocolTxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters->externalTxBufferStatus = NOT_IN_USE; #endif } } runtime->isType2Tx = FALSE; } // - - - - - - - - - - - static inline void releaseExternalRxTxBuffersHelper(PduIdType rxPduIdRef) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; if (TRUE == findRxPduIdParentConfigurationLeafs(rxPduIdRef, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { releaseExternalRxTxBuffers(protocolRow, runtime); } } // - - - - - - - - - - - /* * This function is called from the DSD module to the DSL when * a response to a diagnostic request has been copied into the * given TX-buffer and is ready for transmission. */ void DslDsdProcessingDone(PduIdType rxPduIdRef, DsdProcessingDoneResultType responseResult) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; DEBUG( DEBUG_MEDIUM, "DslDsdProcessingDone rxPduIdRef=%d\n", rxPduIdRef); Dcm_DslBufferUserType *bufferStatus = NULL; if (TRUE == findRxPduIdParentConfigurationLeafs(rxPduIdRef, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { SchM_Enter_Dcm_EA_0(); switch (responseResult) { case DSD_TX_RESPONSE_READY: if(TRUE == runtime->isType2Tx) { bufferStatus = &mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters->externalTxBufferStatus; } else { bufferStatus = &runtime->externalTxBufferStatus; } #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) if( *bufferStatus != PENDING_BUFFER_RELEASE ) { *bufferStatus = DSD_PENDING_RESPONSE_SIGNALED; /* @req DCM114 */ } #else *bufferStatus = DSD_PENDING_RESPONSE_SIGNALED; /* @req DCM114 */ #endif break; case DSD_TX_RESPONSE_SUPPRESSED: /* @req DCM238 */ DEBUG( DEBUG_MEDIUM, "DslDsdProcessingDone called with DSD_TX_RESPONSE_SUPPRESSED.\n"); if(TRUE == runtime->isType2Tx) { /* Release the tx pdu */ PduIdType dcmTxPduId = 0xffff; if(TRUE == DslPduRPduUsedForType2Tx(runtime->diagResponseTxPduId, &dcmTxPduId)) { /* Release the tx pdu */ DslReleaseType2TxPdu(dcmTxPduId); } } /* IMPROVEMENT: Problem with dspProcessing flag */ releaseExternalRxTxBuffersHelper(rxPduIdRef); #if defined(USE_COMM) if( DCM_DEFAULT_SESSION == runtime->sessionControl ) { if( runtime->diagnosticActiveComM == TRUE ) { /* @req DCM166 */ /* @req DCM697 */ ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); runtime->diagnosticActiveComM = FALSE; } } #endif break; default: DEBUG( DEBUG_MEDIUM, "Unknown response result from DslDsdProcessingDone!\n"); break; } SchM_Exit_Dcm_EA_0(); } } // - - - - - - - - - - - static Std_ReturnType sendResponseWithStatus(const Dcm_DslProtocolRowType *protocol, Dcm_NegativeResponseCodeType responseCode) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; Std_ReturnType transmitResult = E_NOT_OK; SchM_Enter_Dcm_EA_0(); /* @req DCM119 */ if (TRUE == findRxPduIdParentConfigurationLeafs(protocol->DslRunTimeProtocolParameters->diagReqestRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { if (runtime->localTxBuffer.status == NOT_IN_USE) { runtime->localTxBuffer.responseCode = responseCode; runtime->localTxBuffer.status = PROVIDED_TO_DSD; runtime->localTxBuffer.buffer[0] = SID_NEGATIVE_RESPONSE; runtime->localTxBuffer.buffer[1] = protocol->DslProtocolRxBufferID->pduInfo.SduDataPtr[0]; runtime->localTxBuffer.buffer[2] = responseCode; runtime->localTxBuffer.PduInfo.SduDataPtr = runtime->localTxBuffer.buffer; runtime->localTxBuffer.PduInfo.SduLength = 3; runtime->localTxBuffer.status = DCM_TRANSMIT_SIGNALED; // In the DslProvideTxBuffer 'callback' this state signals it is the local buffer we are interested in sending. if( DCM_E_RESPONSEPENDING == responseCode) { /* @req DCM203 */ DsdClearSuppressPosRspMsg(); } /* @req DCM115 Partially The P2ServerMin has not been implemented. */ transmitResult = PduR_DcmTransmit(mainConnection->DslProtocolTx->DcmDslProtocolTxPduId, &(runtime->localTxBuffer.PduInfo)); if (transmitResult != E_OK) { // IMPROVEMENT: What to do here? } } } SchM_Exit_Dcm_EA_0(); return transmitResult; } /* * This function preparing transmission of response * pending message to tester. */ static void sendResponse(const Dcm_DslProtocolRowType *protocol, Dcm_NegativeResponseCodeType responseCode) { (void)sendResponseWithStatus(protocol, responseCode); } /** * Adjusts P2 timer value * @param maxValue * @param adjustValue * @return */ static uint32 AdjustP2Timing(uint32 maxValue, uint32 adjustValue) { uint32 result = 0u; if( maxValue > adjustValue ) { result = maxValue - adjustValue; } return result; } void DslDsdSendResponsePending(PduIdType rxPduId) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *rxRuntime = NULL; const Dcm_DspSessionRowType *sessionRow; if (TRUE == findRxPduIdParentConfigurationLeafs(rxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &rxRuntime)) { sendResponse(protocolRow, DCM_E_RESPONSEPENDING); sessionRow = getActiveSessionRow(rxRuntime); /* NOTE: + DCM_MAIN_FUNCTION_PERIOD_TIME_MS is used below due to that timeout is decremented once within the same mainfunction as request is processed. */ rxRuntime->stateTimeoutCount = DCM_CONVERT_MS_TO_MAIN_CYCLES(AdjustP2Timing(sessionRow->DspSessionP2StarServerMax + DCM_MAIN_FUNCTION_PERIOD_TIME_MS, protocolRow->DslProtocolTimeLimit->TimStrP2StarServerAdjust)); /* Reinitiate timer, see 9.2.2. */ DECREMENT( rxRuntime->responsePendingCount ); } } // - - - - - - - - - - - static Std_ReturnType StartProtocolHelper(Dcm_ProtocolType protocolId) { Std_ReturnType res = E_OK; Std_ReturnType ret = E_OK; uint16 i; for (i = 0; FALSE == Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i].Arc_EOL; i++) { if (Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i].StartProtocol != NULL) { res = Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i]. StartProtocol(protocolId); if ((res == E_NOT_OK) || (res == E_PROTOCOL_NOT_ALLOWED)) { ret = E_NOT_OK; break; } } } return ret; } // OBD: add stop protocol for stack preempting static Std_ReturnType StopProtocolHelper(Dcm_ProtocolType protocolId) { Std_ReturnType res = E_OK; Std_ReturnType ret = E_OK; uint16 i; for (i = 0; FALSE == Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i].Arc_EOL; i++) { if (Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i].StopProtocol != NULL) { res = Dcm_ConfigPtr->Dsl->DslCallbackDCMRequestService[i].StopProtocol(protocolId); if ((res == E_NOT_OK )|| (res == E_PROTOCOL_NOT_ALLOWED)) { ret = E_NOT_OK; break; } } } return ret; } // - - - - - - - - - - - static boolean isTesterPresentCommand(const PduInfoType *rxPdu) { boolean ret = FALSE; if ((rxPdu->SduDataPtr[0] == SID_TESTER_PRESENT) && ((rxPdu->SduDataPtr[1] & SUPPRESS_POS_RESP_BIT)==SUPPRESS_POS_RESP_BIT)) { ret = TRUE; } return ret; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'void Dcm_Init(void)' for DSL. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DslInit(void) { const Dcm_DslProtocolRowType *listEntry; #if defined(USE_COMM) const Dcm_DslProtocolRxType *protocolRx; #endif Dcm_DslRunTimeProtocolParametersType *runtime = NULL; listEntry = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRowList; while (listEntry->Arc_EOL == FALSE) { runtime = listEntry->DslRunTimeProtocolParameters; runtime->externalRxBufferStatus = NOT_IN_USE; runtime->externalTxBufferStatus = NOT_IN_USE; runtime->localRxBuffer.status = NOT_IN_USE; runtime->localTxBuffer.status = NOT_IN_USE; runtime->securityLevel = DCM_SEC_LEV_LOCKED; /* @req DCM033 */ runtime->sessionControl = DCM_DEFAULT_SESSION; /* @req DCM034 */ runtime->diagnosticActiveComM = FALSE; runtime->protocolStarted = FALSE;// OBD: close the protocol /* Check that there is an rx buffer. * Will not be in case of periodic transmission protocol */ if(NULL != listEntry->DslProtocolRxBufferID) { listEntry->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } listEntry->DslProtocolTxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; listEntry->DslProtocolTxBufferID->externalBufferRuntimeData->DcmRxPduId = DCM_INVALID_PDU_ID; runtime->localRxBuffer.DcmRxPduId = DCM_INVALID_PDU_ID; runtime->isType2Tx = FALSE; runtime->S3ServerStarted = FALSE; runtime->S3ServerTimeoutCount = 0u; listEntry++; }; #if defined(USE_COMM) protocolRx = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRxGlobalList; while(FALSE == protocolRx->Arc_EOL) { NetWorkComMode[protocolRx->ComMChannelInternalIndex] = DCM_NO_COM; protocolRx++; } #endif DcmDslRunTimeData.initRun = TRUE; // NOTE: Why? DcmDslRunTimeData.activeProtocol = NULL;// OBD: close the current active protocol DslReleaseAllType2TxPdus(); } static boolean DslCheckType2TxPduAvailable(const Dcm_DslMainConnectionType *mainConnection) { #ifdef DCM_USE_TYPE2_PERIODIC_TRANSMISSION boolean ret = false; const Dcm_DslPeriodicTransmissionType *periodicTrans = mainConnection->DslPeriodicTransmissionConRef; /* Find a pdu to use */ uint8 i = 0; while(( FALSE == periodicTrans->TxPduList[i].Arc_EOL) && (FALSE == ret)) { if(FALSE == PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(periodicTrans->TxPduList[i].DcmTxPduId)].pduInUse) { /* Pdu available */ ret = TRUE; } i++; } return ret; #else (void)mainConnection; return FALSE; #endif } static void DslReleaseAllType2TxPdus(void) { #ifdef DCM_USE_TYPE2_PERIODIC_TRANSMISSION for(uint16 i = 0; i < DCM_NOF_PERIODIC_TX_PDU; i++) { PeriodicPduStatus[i].diagReqRxPduId = 0xFFFF; PeriodicPduStatus[i].pduInUse = FALSE; } #endif } static void DslReleaseType2TxPdu(PduIdType txPduId) { #ifdef DCM_USE_TYPE2_PERIODIC_TRANSMISSION if(IS_PERIODIC_TX_PDU(txPduId)) { PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(txPduId)].pduInUse = FALSE; PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(txPduId)].diagReqRxPduId = 0xffff; } #else (void)txPduId; #endif } #if defined(DCM_USE_TYPE2_PERIODIC_TRANSMISSION) && defined(DCM_TYPE2_TX_ROUTED_TO_IF) static Std_ReturnType DslGetType2TxUserRxPdu(PduIdType type2TxPduId, PduIdType *rxPduId) { Std_ReturnType ret = E_NOT_OK; if(IS_PERIODIC_TX_PDU(type2TxPduId) && (PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(type2TxPduId)].pduInUse == TRUE)) { *rxPduId = PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(type2TxPduId)].diagReqRxPduId; ret = E_OK; } return ret; } #endif static Std_ReturnType DslLockType2TxPdu(const Dcm_DslMainConnectionType *mainConnection, PduIdType requestRxPDuId, PduIdType *txPduId) { #if defined(DCM_USE_TYPE2_PERIODIC_TRANSMISSION) Std_ReturnType ret = E_NOT_OK; if(mainConnection->DslPeriodicTransmissionConRef != NULL){ const Dcm_DslPeriodicTransmissionType *periodicTrans = mainConnection->DslPeriodicTransmissionConRef; /* Find a pdu to use */ uint8 i = 0; while((FALSE == periodicTrans->TxPduList[i].Arc_EOL) && (E_OK != ret)) { if(FALSE == PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(periodicTrans->TxPduList[i].DcmTxPduId)].pduInUse ) { /* Pdu available */ PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(periodicTrans->TxPduList[i].DcmTxPduId)].pduInUse = TRUE; PeriodicPduStatus[TO_INTERNAL_PERIODIC_PDU(periodicTrans->TxPduList[i].DcmTxPduId)].diagReqRxPduId = requestRxPDuId; *txPduId = periodicTrans->TxPduList[i].PduRTxPduId; ret = E_OK; } i++; } } return ret; #else (void)mainConnection; (void)requestRxPDuId; (void)txPduId; return E_NOT_OK; #endif } boolean DslPduRPduUsedForType2Tx(PduIdType pdurTxPduId, PduIdType *dcmTxPduId) { #if defined(DCM_USE_TYPE2_PERIODIC_TRANSMISSION) boolean isUsed = FALSE; const Dcm_DslPeriodicTxType *periodicTx = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolPeriodicTxGlobalList; while((FALSE == periodicTx->Arc_EOL) && (FALSE == isUsed)) { isUsed = (pdurTxPduId == periodicTx->PduRTxPduId); *dcmTxPduId = periodicTx->DcmTxPduId; periodicTx++; } return isUsed; #else (void)pdurTxPduId; (void)dcmTxPduId; return FALSE; #endif } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'void DslInternal_ResponseOnOneDataByPeriodicId(uint8 PericodID)' for simulator a periodic did data. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Std_ReturnType DslInternal_ResponseOnOneDataByPeriodicId(uint8 PericodID, PduIdType rxPduId) { Std_ReturnType ret = E_NOT_OK; const Dcm_DslRunTimeProtocolParametersType *runtime; runtime = NULL; if( NULL != DcmDslRunTimeData.activeProtocol ) { runtime = DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters; if(runtime != NULL) // find the runtime { PduLengthType rxBufferSize; if( BUFREQ_OK == DslStartOfReception(rxPduId, 3, &rxBufferSize, TRUE)){ PduInfoType periodData; uint8 data[3]; periodData.SduDataPtr = data; periodData.SduDataPtr[0] = SID_READ_DATA_BY_PERIODIC_IDENTIFIER; periodData.SduDataPtr[1] = DCM_PERIODICTRANSMIT_DEFAULT_MODE; periodData.SduDataPtr[2] = PericodID; periodData.SduLength = 3; if( BUFREQ_OK == DslCopyDataToRxBuffer(rxPduId, &periodData, &rxBufferSize) ) { DslTpRxIndicationFromPduR(rxPduId, NTFRSLT_OK, TRUE, FALSE); } else { /* Something went wrong. Indicate that the reception was * not ok. */ DslTpRxIndicationFromPduR(rxPduId, NTFRSLT_E_NOT_OK, TRUE, FALSE); } ret = E_OK; } } } return ret; } Std_ReturnType DslInternal_ResponseOnOneEvent(PduIdType rxPduId, uint8* request, uint8 requestLength) { Std_ReturnType ret = E_NOT_OK; const Dcm_DslRunTimeProtocolParametersType *runtime; runtime = NULL; if( NULL != DcmDslRunTimeData.activeProtocol ) { runtime = DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters; if(runtime != NULL) // find the runtime { PduLengthType rxBufferSize; if( BUFREQ_OK == DslStartOfReception(rxPduId, requestLength, &rxBufferSize, TRUE)){ PduInfoType requestPdu; requestPdu.SduDataPtr = request; requestPdu.SduLength = requestLength; if( BUFREQ_OK == DslCopyDataToRxBuffer(rxPduId, &requestPdu, &rxBufferSize) ) { DslTpRxIndicationFromPduR(rxPduId, NTFRSLT_OK, TRUE, FALSE); } else { /* Something went wrong. Indicate that the reception was * not ok. */ DslTpRxIndicationFromPduR(rxPduId, NTFRSLT_E_NOT_OK, TRUE, FALSE); } ret = E_OK; } } } return ret; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'void Dcm_MainFunction(void)' for DSL. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DslMain(void) { const Dcm_DslProtocolRowType *protocolRowEntry; const Dcm_DspSessionRowType *sessionRow; Dcm_DslRunTimeProtocolParametersType *runtime; sessionRow = NULL; runtime = NULL; protocolRowEntry = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRowList; while (protocolRowEntry->Arc_EOL == FALSE) { runtime = protocolRowEntry->DslRunTimeProtocolParameters; if (runtime != NULL) { // #### HANDLE THE TESTER PRESENT PRESENCE #### if (runtime->sessionControl != DCM_DEFAULT_SESSION) { // Timeout if tester present is lost. if( TRUE == runtime->S3ServerStarted ) { DECREMENT(runtime->S3ServerTimeoutCount); } if (runtime->S3ServerTimeoutCount == 0) { DslReleaseAllType2TxPdus(); /* @req DCM626 Changing session to default will stop control */ changeDiagnosticSession(runtime, DCM_DEFAULT_SESSION); /* @req DCM140 */ if(DCM_OBD_ON_CAN == protocolRowEntry->DslProtocolID){ runtime->protocolStarted = FALSE; if(DCM_OBD_ON_CAN == DcmDslRunTimeData.activeProtocol->DslProtocolID){ DcmDslRunTimeData.activeProtocol = NULL; } } } } switch (runtime->externalTxBufferStatus) { // #### TX buffer state. #### case NOT_IN_USE: DEBUG( DEBUG_MEDIUM, "state NOT_IN_USE!\n"); break; case PROVIDED_TO_DSD: { DECREMENT(runtime->stateTimeoutCount); if (runtime->stateTimeoutCount == 0) { sessionRow = getActiveSessionRow(runtime); runtime->stateTimeoutCount = DCM_CONVERT_MS_TO_MAIN_CYCLES(AdjustP2Timing(sessionRow->DspSessionP2StarServerMax,protocolRowEntry->DslProtocolTimeLimit->TimStrP2StarServerAdjust)); /* Reinitiate timer, see 9.2.2. */ if (Dcm_ConfigPtr->Dsl->DslDiagResp != NULL) { if (Dcm_ConfigPtr->Dsl->DslDiagResp->DslDiagRespForceRespPendEn == TRUE) { if (runtime->responsePendingCount != 0) { sendResponse(protocolRowEntry, DCM_E_RESPONSEPENDING); /* @req DCM024 */ DECREMENT( runtime->responsePendingCount ); } else { DcmCancelPendingRequests(); sendResponse(protocolRowEntry, DCM_E_GENERALREJECT); /* @req DCM120 */ releaseExternalRxTxBuffers(protocolRowEntry, runtime); } } else { DEBUG( DEBUG_MEDIUM, "Not configured to send response pending, now sending general reject!\n"); DcmCancelPendingRequests(); sendResponse(protocolRowEntry, DCM_E_GENERALREJECT); releaseExternalRxTxBuffers(protocolRowEntry, runtime); } } } break; } case DSD_PENDING_RESPONSE_SIGNALED: // The DSD has signaled to DSL that the diagnostic response is available in the Tx buffer. // Make sure that response pending or general reject have not been issued, // if so we can not transmit to PduR because we would not know from where // the Tx confirmation resides later. DEBUG( DEBUG_MEDIUM, "state DSD_PENDING_RESPONSE_SIGNALED!\n"); if (runtime->localTxBuffer.status == NOT_IN_USE) { // Make sure that no TxConfirm could be sent by the local buffer and mixed up with this transmission. const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *rxRuntime = NULL; Std_ReturnType transmitResult; if (TRUE == findRxPduIdParentConfigurationLeafs(runtime->diagReqestRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &rxRuntime)) { Dcm_DslRunTimeProtocolParametersType *txRuntime; if(TRUE == rxRuntime->isType2Tx) { txRuntime = mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters; } else { txRuntime = rxRuntime; } const PduIdType txPduId = txRuntime->diagResponseTxPduId; DEBUG( DEBUG_MEDIUM, "runtime->externalTxBufferStatus enter state DCM_TRANSMIT_SIGNALED.\n" ); txRuntime->externalTxBufferStatus = DCM_TRANSMIT_SIGNALED; /* @req DCM237 Will trigger PduR (CanTP) to call DslProvideTxBuffer(). */ transmitResult = PduR_DcmTransmit(txPduId, &txRuntime->diagnosticResponseFromDsd); PduIdType dcmType2TxPduId = 0xffff; if( E_OK != transmitResult ) { /* Transmit failed. * If it is a type2 transmit, release the pdu. */ if(TRUE == DslPduRPduUsedForType2Tx(txPduId, &dcmType2TxPduId)) { DslReleaseType2TxPdu(dcmType2TxPduId); } else { /* Not a periodic pdu. Start s3 timer since there will be * no tx confirmation of this transmit request */ startS3SessionTimer(rxRuntime, protocolRow); } /* Release buffers */ releaseExternalRxTxBuffers(protocolRow, rxRuntime); /* @req DCM118 */ } #if defined(DCM_TYPE2_TX_ROUTED_TO_IF) /* Assuming that the transmit was routed directly to lower If. * This means that data is copied directly on transmit request * and we can drop the buffers. */ else if( TRUE == DslPduRPduUsedForType2Tx(txPduId, &dcmType2TxPduId) ) { /* It is a type2 transmit. Release buffers. */ releaseExternalRxTxBuffers(protocolRow, rxRuntime); }else{ /* do nothing */ } #endif } else { DEBUG( DEBUG_MEDIUM, "***** WARNING, THIS IS UNEXPECTED !!! ********.\n" ); const PduIdType txPduId = protocolRowEntry->DslConnections->DslMainConnection->DslProtocolTx->DcmDslProtocolTxPduId; DEBUG( DEBUG_MEDIUM, "runtime->externalTxBufferStatus enter state DSD_PENDING_RESPONSE_SIGNALED.\n", txPduId); runtime->externalTxBufferStatus = DCM_TRANSMIT_SIGNALED; DEBUG( DEBUG_MEDIUM, "Calling PduR_DcmTransmit with txPduId = %d from DslMain\n", txPduId); /* @req DCM237 Will trigger PduR (CanTP) to call DslProvideTxBuffer(). */ transmitResult = PduR_DcmTransmit(txPduId, &runtime->diagnosticResponseFromDsd); if (transmitResult != E_OK) { /* Transmit request failed, release the buffers */ releaseExternalRxTxBuffers(protocolRow, runtime);/* @req DCM118 */ PduIdType dcmTxPduId = 0xffff; if(TRUE == DslPduRPduUsedForType2Tx(txPduId, &dcmTxPduId)) { DslReleaseType2TxPdu(dcmTxPduId); } /* Start s3 timer since there will be no tx confirmation of this transmit request */ startS3SessionTimer(rxRuntime, protocolRow); } } } break; case DCM_TRANSMIT_SIGNALED: DEBUG( DEBUG_MEDIUM, "state DSD_PENDING_RESPONSE_SIGNALED!\n"); break; case PROVIDED_TO_PDUR: // The valid data is being transmitted by TP-layer. DEBUG( DEBUG_MEDIUM, "state DSD_PENDING_RESPONSE_SIGNALED!\n"); break; //IMPROVEMENT: Fix OBD stuff case PREEMPT_TRANSMIT_NRC: /* preemption has happened,send NRC 0x21 to OBD tester */ if (TRUE == PreemptionNotProcessingDone){ /*sent NRC 0x21 till timeout or processing done*/ if( FALSE == BusySent ) { if( E_OK == sendResponseWithStatus(protocolRowEntry, DCM_E_BUSYREPEATREQUEST) ) { BusySent = TRUE; /* Release the rx buffer. Will allow accepting another request. */ runtime->externalRxBufferStatus = NOT_IN_USE; protocolRowEntry->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } } /*decrease preempt timeout count*/ DECREMENT(runtime->preemptTimeoutCount); /*if processing done is finished,clear the flag*/ if (DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->externalTxBufferStatus == NOT_IN_USE){ /*if processing done is finished,clear the flag*/ PreemptionNotProcessingDone = FALSE; /*close the preempted protocol*/ DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->protocolStarted = FALSE; /*remove the active protocol and waiting for second OBD request*/ DcmDslRunTimeData.activeProtocol = NULL; /*release current protocol buffer*/ releaseExternalRxTxBuffers(protocolRowEntry, runtime); /* @req DCM627 */ DcmResetDiagnosticActivity(); } else if(runtime->preemptTimeoutCount == 0){ /*if preempt timeout,clear the flag*/ PreemptionNotProcessingDone = FALSE; /*close the preempted protocol*/ DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->protocolStarted = FALSE; /*release the extrnal Rx and Tx buffters of the preempted protocol*/ releaseExternalRxTxBuffers(DcmDslRunTimeData.activeProtocol, DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters); /*remove the active protocol and waiting for second OBD request*/ DcmDslRunTimeData.activeProtocol = NULL; /*release the external Rx and Tx buffers of the preempting protocol*/ releaseExternalRxTxBuffers(protocolRowEntry, runtime); /* @req DCM627 */ DcmResetDiagnosticActivity(); /*initialize DSP*/ /* NOTE: Is this correct? */ DspInit(FALSE); } else { } } break; #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) case PENDING_BUFFER_RELEASE: releaseExternalRxTxBuffers(protocolRowEntry, runtime); break; #endif default: break; } } protocolRowEntry++; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'BufReq_ReturnType Dcm_StartOfReception(PduIdType dcmRxPduId, // PduLengthType tpSduLength, PduLengthType *rxBufferSizePtr)'. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // This function is called called by the PduR typically when CanTp has // received a FF or a single frame and needs to obtain a buffer from the // receiver so that received data can be forwarded. BufReq_ReturnType DslStartOfReception(PduIdType dcmRxPduId, PduLengthType tpSduLength, PduLengthType *rxBufferSizePtr, boolean internalRequest) { /* !req DCM788 */ /* !req DCM789 */ /* !req DCM790 */ /* !req DCM655 */ /* !req DCM656 */ /* @req DCM733 Buffers locked until service processing done */ BufReq_ReturnType ret = BUFREQ_NOT_OK; const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; boolean intType2Request = FALSE; DEBUG( DEBUG_MEDIUM, "DslProvideRxBufferToPdur(dcmRxPduId=%d) called!\n", dcmRxPduId); SchM_Enter_Dcm_EA_0(); if (TRUE == findRxPduIdParentConfigurationLeafs(dcmRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { const Dcm_DslBufferType *externalRxBuffer = protocolRow->DslProtocolRxBufferID; intType2Request = (TRUE == internalRequest) && (DCM_PROTOCOL_TRANS_TYPE_2 == protocolRow->DslProtocolTransType); if( !((TRUE == internalRequest) && (DCM_PROTOCOL_TRANS_TYPE_2 == protocolRow->DslProtocolTransType)) || (TRUE == DslCheckType2TxPduAvailable(mainConnection))) { if (externalRxBuffer->pduInfo.SduLength >= tpSduLength) { /* @req DCM443 */ /* @req DCM121 */ /* @req DCM137 */ if ((runtime->externalRxBufferStatus == NOT_IN_USE) && (externalRxBuffer->externalBufferRuntimeData->status == BUFFER_AVAILABLE)) { DEBUG( DEBUG_MEDIUM, "External buffer available!\n"); // ### EXTERNAL BUFFER IS AVAILABLE; GRAB IT AND REMEBER THAT WE OWN IT! ### externalRxBuffer->externalBufferRuntimeData->status = BUFFER_BUSY; runtime->diagnosticRequestFromTester.SduDataPtr = externalRxBuffer->pduInfo.SduDataPtr; runtime->diagnosticRequestFromTester.SduLength = tpSduLength; externalRxBuffer->externalBufferRuntimeData->nofBytesHandled = 0; runtime->externalRxBufferStatus = PROVIDED_TO_PDUR; /* @req DCM342 */ //If external buffer is provided memorize DcmPduId externalRxBuffer->externalBufferRuntimeData->DcmRxPduId = dcmRxPduId; *rxBufferSizePtr = externalRxBuffer->pduInfo.SduLength; ret = BUFREQ_OK; } else { if ((NOT_IN_USE == runtime->localRxBuffer.status) && #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) (PENDING_BUFFER_RELEASE != runtime->externalRxBufferStatus) && #endif (FALSE == internalRequest)) { /* ### EXTERNAL BUFFER IS IN USE BY THE DSD OR PDUR, TRY TO USE LOCAL BUFFER ONLY FOR FUNCTIONAL REQUEST ( ONLY FOR TESTER PRESENT)! ### * Note: There is no way to predict that request is Tester present because pduInfoPtr->SduDataPtr not available. * This is handled in DslTpRxIndicationFromPduR(). * But if it is an internal request we now that it is not Tester present. */ if (tpSduLength <= DCM_DSL_LOCAL_BUFFER_LENGTH) { /* !req DCM557 */ runtime->localRxBuffer.status = PROVIDED_TO_PDUR; runtime->localRxBuffer.PduInfo.SduDataPtr = runtime->localRxBuffer.buffer; runtime->localRxBuffer.PduInfo.SduLength = tpSduLength; runtime->localRxBuffer.nofBytesHandled = 0; //If local buffer is provided memorize DcmPduId runtime->localRxBuffer.DcmRxPduId = dcmRxPduId; *rxBufferSizePtr = DCM_DSL_LOCAL_BUFFER_LENGTH; ret = BUFREQ_OK; } else if (externalRxBuffer->externalBufferRuntimeData->DcmRxPduId == dcmRxPduId) { /* This case avoids receiving a new FF is received while MF transmission is ongoing as a response to previous SF request. * Half Duplex case - runtime->externalRxBufferStatus == PROVIDED_TO_DSD */ ret = BUFREQ_E_NOT_OK; } else { /* Half duplex - This case avoids a condition where External buffer is locked by a * Functional request and we receive a FF as a physical request */ ret = BUFREQ_E_NOT_OK; /** This is a multi-frame reception and discard request. */ } } else { /* Internal request or there is no buffer available, wait until it is free. */ ret = BUFREQ_BUSY; } } } else { ret = BUFREQ_OVFL; /* @req DCM444 */ } } else { /* Internal request for type2 transmission and no pdu available right now */ ret = BUFREQ_BUSY; } /* Do not stop s3 timer on internal type2 request. */ if ((FALSE == intType2Request) && (ret == BUFREQ_OK)) { stopS3SessionTimer(runtime); /* @req DCM141 */ } } SchM_Exit_Dcm_EA_0(); return ret; } BufReq_ReturnType DslCopyDataToRxBuffer(PduIdType dcmRxPduId, const PduInfoType *pduInfoPtr, PduLengthType *rxBufferSizePtr) { BufReq_ReturnType returnCode = BUFREQ_NOT_OK; const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; SchM_Enter_Dcm_EA_0(); if (TRUE == findRxPduIdParentConfigurationLeafs(dcmRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { const Dcm_DslBufferType *externalRxBuffer = protocolRow->DslProtocolRxBufferID; if ((PROVIDED_TO_PDUR == runtime->externalRxBufferStatus ) && (externalRxBuffer->externalBufferRuntimeData->DcmRxPduId == dcmRxPduId)){ /* Buffer is provided to PDUR. Copy data to buffer */ uint8 *destPtr = &(runtime->diagnosticRequestFromTester.SduDataPtr[externalRxBuffer->externalBufferRuntimeData->nofBytesHandled]); if( 0 == pduInfoPtr->SduLength ) { /* Just polling remaining buffer size */ /* @req DCM642 */ returnCode = BUFREQ_OK; } else if( pduInfoPtr->SduLength <= (externalRxBuffer->pduInfo.SduLength - externalRxBuffer->externalBufferRuntimeData->nofBytesHandled) ) { /* Enough room in buffer. Copy data. */ /* @req DCM443 */ memcpy(destPtr, pduInfoPtr->SduDataPtr, pduInfoPtr->SduLength); /* Inc nof bytes handled byte */ externalRxBuffer->externalBufferRuntimeData->nofBytesHandled += pduInfoPtr->SduLength; returnCode = BUFREQ_OK; } else { /* Length exceeds number of bytes left in buffer */ DCM_DET_REPORTERROR(DCM_COPY_RX_DATA_ID, DCM_E_INTERFACE_BUFFER_OVERFLOW); returnCode = BUFREQ_NOT_OK; } *rxBufferSizePtr = externalRxBuffer->pduInfo.SduLength - externalRxBuffer->externalBufferRuntimeData->nofBytesHandled; } else if ((runtime->localRxBuffer.status == PROVIDED_TO_PDUR) && (runtime->localRxBuffer.DcmRxPduId == dcmRxPduId)){ /* Local buffer provided to pdur */ if(0 == pduInfoPtr->SduLength) { /* Just polling remaining buffer size */ returnCode = BUFREQ_OK; } else if(pduInfoPtr->SduLength <= (DCM_DSL_LOCAL_BUFFER_LENGTH - runtime->localRxBuffer.nofBytesHandled)) { uint8 *destPtr = &(runtime->localRxBuffer.PduInfo.SduDataPtr[runtime->localRxBuffer.nofBytesHandled]); memcpy(destPtr, pduInfoPtr->SduDataPtr, pduInfoPtr->SduLength); runtime->localRxBuffer.nofBytesHandled += pduInfoPtr->SduLength; returnCode = BUFREQ_OK; } else { /* Length exceeds buffer size */ DCM_DET_REPORTERROR(DCM_COPY_RX_DATA_ID, DCM_E_INTERFACE_BUFFER_OVERFLOW); returnCode = BUFREQ_NOT_OK; } *rxBufferSizePtr = DCM_DSL_LOCAL_BUFFER_LENGTH - runtime->localRxBuffer.nofBytesHandled; }else{ /* do nothing */ } } SchM_Exit_Dcm_EA_0(); return returnCode; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'void Dcm_TpRxIndication(PduIdType dcmRxPduId, NotifResultType result)'. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // This function is called called by the PduR typically when CanTp has // received the diagnostic request, copied it to the provided buffer and need to indicate // this to the DCM (DSL) module via proprietary API. void DslTpRxIndicationFromPduR(PduIdType dcmRxPduId, NotifResultType result, boolean internalRequest, boolean startupResponseRequest) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; const Dcm_DspSessionRowType *sessionRow = NULL; Dcm_DslRunTimeProtocolParametersType *rxRuntime = NULL; Std_ReturnType higherLayerResp; /* @req DCM345 this needs to be verified when connection to CanIf works. */ if (TRUE == findRxPduIdParentConfigurationLeafs(dcmRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &rxRuntime)) { /* We need to find out in what buffer we can find our Rx data (it can * be either in the normal RX-buffer or the 'extra' buffer for implementing * the Concurrent "Test Present" functionality. */ const Dcm_DslBufferType *externalRxBuffer = protocolRow->DslProtocolRxBufferID; SchM_Enter_Dcm_EA_0(); if ((rxRuntime->externalRxBufferStatus == PROVIDED_TO_PDUR) && (externalRxBuffer->externalBufferRuntimeData->DcmRxPduId == dcmRxPduId)) { boolean receivedLenOK = (externalRxBuffer->externalBufferRuntimeData->nofBytesHandled == rxRuntime->diagnosticRequestFromTester.SduLength) || (0 == rxRuntime->diagnosticRequestFromTester.SduLength); PduIdType type2TxPduId = 0xffff; boolean type2Tx = (DCM_PROTOCOL_TRANS_TYPE_2 == protocolRow->DslProtocolTransType) && (TRUE == internalRequest); Std_ReturnType retval; retval = E_OK; if (TRUE == type2Tx) { retval = DslLockType2TxPdu(mainConnection, dcmRxPduId, &type2TxPduId); } if ( (result == NTFRSLT_OK) && (TRUE == receivedLenOK) && (E_OK == retval )) { /* @req DCM111 */ if (TRUE == isTesterPresentCommand(&(protocolRow->DslProtocolRxBufferID->pduInfo))) { /* @req DCM141 */ /* @req DCM112 */ /* @req DCM113 */ startS3SessionTimer(rxRuntime, protocolRow); rxRuntime->externalRxBufferStatus = NOT_IN_USE; externalRxBuffer->externalBufferRuntimeData->DcmRxPduId = DCM_INVALID_PDU_ID; protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; #if defined(USE_COMM) /* @req DCM169 Not calling ComM_DCM_InactiveDiagnostic when not in default session */ if( DCM_DEFAULT_SESSION == rxRuntime->sessionControl ) { if( FALSE == rxRuntime->diagnosticActiveComM ) { ComM_DCM_ActiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); /* @req DCM163 */ ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); /* @req DCM166 */ rxRuntime->diagnosticActiveComM = FALSE; } } #endif } else { if (rxRuntime->protocolStarted == FALSE) { /* if there is no active protocol,then start the current protocol */ if(DcmDslRunTimeData.activeProtocol == NULL){ higherLayerResp = StartProtocolHelper(protocolRow->DslProtocolID); /* @req DCM036 */ if (higherLayerResp == E_OK) { /* !req DCM674 */ /* @req DCM146 Reset security state */ /* @req DCM147 Reset to default session and switch mode */ changeDiagnosticSession(rxRuntime, DCM_DEFAULT_SESSION); rxRuntime->protocolStarted = TRUE; DcmDslRunTimeData.activeProtocol = protocolRow; /* if it's OBD diagnostic,change session to DCM_OBD_SESSION */ if(DCM_OBD_ON_CAN == protocolRow->DslProtocolID){ rxRuntime->sessionControl = DCM_OBD_SESSION; //startS3SessionTimer(runtime, protocolRow); /* init s3. */ } } } else { /* if there is a active protocol and the priority of the current protocol is higher than * the priority of the active protocol, then preemption will happen.*/ /* @req DCM015 */ /* !req DCM728 */ /* !req DCM727 */ /* !req DCM729 */ /* @req DCM625 */ if((protocolRow->DslProtocolPriority < DcmDslRunTimeData.activeProtocol->DslProtocolPriority) || (DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->sessionControl == DCM_DEFAULT_SESSION)) { /*@req OBD_DCM_REQ_31*/ higherLayerResp = StopProtocolHelper(DcmDslRunTimeData.activeProtocol->DslProtocolID);/* @req DCM459 */ if (higherLayerResp == E_OK) { if (DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->externalTxBufferStatus == NOT_IN_USE) { higherLayerResp = StartProtocolHelper(protocolRow->DslProtocolID); /* @req DCM036 */ if (higherLayerResp == E_OK) { /* !req DCM674 */ DcmDslRunTimeData.activeProtocol->DslRunTimeProtocolParameters->protocolStarted = FALSE; /* Close the last protocol*/ rxRuntime->protocolStarted = TRUE; /* !req DCM144 */ /* @req DCM145 */ DcmDslRunTimeData.activeProtocol = protocolRow; /* @req DCM146 Reset security state */ /* @req DCM147 Reset to default session and switch mode */ changeDiagnosticSession(rxRuntime, DCM_DEFAULT_SESSION);/* !req DCM559 no call to Dem made */ /*if it's OBD diagnostic,change session to DCM_OBD_SESSION*/ if(DCM_OBD_ON_CAN == protocolRow->DslProtocolID){ rxRuntime->sessionControl = DCM_OBD_SESSION; } } } else { /*set the flag,activate preemption mechanism*/ PreemptionNotProcessingDone = TRUE; BusySent = FALSE; /*set Tx buffer status PREEMPT_TRANSMIT_NRC*/ if(PREEMPT_TRANSMIT_NRC != rxRuntime->externalTxBufferStatus) { /*start preemption timer*/ startPreemptTimer(rxRuntime, protocolRow); } rxRuntime->externalTxBufferStatus = PREEMPT_TRANSMIT_NRC; rxRuntime->responsePendingCount = Dcm_ConfigPtr->Dsl->DslDiagResp->DslDiagRespMaxNumRespPend; rxRuntime->diagReqestRxPduId = dcmRxPduId; /*request PduR to cancel transmit of preempted protocol*/ /*@req OBD_DCM_REQ_32*//*@req OBD_DCM_REQ_33*/ /* @req DCM079 */ /* @req DCM460 */ /* @req DCM461 no new cancel is done */ (void)PduR_DcmCancelTransmit(DsdDslGetCurrentTxPduId()); } } } else { /*if the priority of the current protocol is lower than the priority of the active protocol, we do nothing.*/ rxRuntime->externalRxBufferStatus = NOT_IN_USE; protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } } } if (rxRuntime->protocolStarted == TRUE) { #if defined(USE_COMM) if( DCM_DEFAULT_SESSION == rxRuntime->sessionControl ) { if( FALSE == rxRuntime->diagnosticActiveComM ) { ComM_DCM_ActiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); /* @req DCM163 */ rxRuntime->diagnosticActiveComM = TRUE; } } #endif sessionRow = getActiveSessionRow(rxRuntime); rxRuntime->externalRxBufferStatus = PROVIDED_TO_DSD; /* @req DCM241 */ const Dcm_DslBufferType *txBuffer = NULL; rxRuntime->isType2Tx = type2Tx; Dcm_DslRunTimeProtocolParametersType *txRuntime; uint32 P2ServerAdjust; if( TRUE == type2Tx ) { /* @req DCM122 */ txRuntime = mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslRunTimeProtocolParameters; txBuffer = mainConnection->DslPeriodicTransmissionConRef->DslProtocolRow->DslProtocolTxBufferID; txRuntime->diagResponseTxPduId = type2TxPduId; txRuntime->diagReqestRxPduId = dcmRxPduId; P2ServerAdjust = 0u; } else { txRuntime = rxRuntime; txRuntime->diagResponseTxPduId = mainConnection->DslProtocolTx->DcmDslProtocolTxPduId; txBuffer = protocolRow->DslProtocolTxBufferID; P2ServerAdjust = protocolRow->DslProtocolTimeLimit->TimStrP2ServerAdjust; } rxRuntime->diagResponseTxPduId = txRuntime->diagResponseTxPduId; txRuntime->stateTimeoutCount = DCM_CONVERT_MS_TO_MAIN_CYCLES(AdjustP2Timing(sessionRow->DspSessionP2ServerMax, P2ServerAdjust)); if (txRuntime->externalTxBufferStatus == NOT_IN_USE) { DEBUG( DEBUG_MEDIUM, "External Tx buffer available, we can pass it to DSD.\n"); } else { DEBUG( DEBUG_MEDIUM, "External buffer not available, a response is being transmitted?\n"); } if( 0 == rxRuntime->diagnosticRequestFromTester.SduLength ) { /* The original transfer request on call of Dcm_StartOfReception was 0. Set length * of diagnostic request to the number of bytes received. */ rxRuntime->diagnosticRequestFromTester.SduLength = externalRxBuffer->externalBufferRuntimeData->nofBytesHandled; } txRuntime->externalTxBufferStatus = PROVIDED_TO_DSD; /* @req DCM241 */ txRuntime->responsePendingCount = Dcm_ConfigPtr->Dsl->DslDiagResp->DslDiagRespMaxNumRespPend; txRuntime->diagnosticResponseFromDsd.SduDataPtr = txBuffer->pduInfo.SduDataPtr; txRuntime->diagnosticResponseFromDsd.SduLength = txBuffer->pduInfo.SduLength; DEBUG( DEBUG_MEDIUM, "DsdDslDataIndication(DcmDslProtocolTxPduId=%d, dcmRxPduId=%d)\n", mainConnection->DslProtocolTx->DcmDslProtocolTxPduId, dcmRxPduId); rxRuntime->diagReqestRxPduId = dcmRxPduId; DEBUG(DEBUG_MEDIUM,"\n\n runtime->diagnosticRequestFromTester.SduDataPtr[2] %x\n\n ",rxRuntime->diagnosticRequestFromTester.SduDataPtr[2]); DsdDslDataIndication( // qqq: We are inside a critical section. &(rxRuntime->diagnosticRequestFromTester), protocolRow->DslProtocolSIDTable, /* @req DCM035 */ protocolRx->DslProtocolAddrType, txRuntime->diagResponseTxPduId, &(txRuntime->diagnosticResponseFromDsd), dcmRxPduId, protocolRow->DslProtocolTransType, internalRequest, protocolRow->DslSendRespPendOnTransToBoot, startupResponseRequest); } } } else { /* @req DCM344 */ /* The indication was not equal to NTFRSLT_OK, the length did not match or no type2 pdu was available, * release the resources and no forward to DSD.*/ if( FALSE == receivedLenOK ) { /* Number of bytes received does not match the original request */ DCM_DET_REPORTERROR(DCM_TP_RX_INDICATION_ID, DCM_E_TP_LENGTH_MISMATCH); } DslResetSessionTimeoutTimer(); /* @req DCM141 */ rxRuntime->externalRxBufferStatus = NOT_IN_USE; externalRxBuffer->externalBufferRuntimeData->DcmRxPduId = DCM_INVALID_PDU_ID; protocolRow->DslProtocolRxBufferID->externalBufferRuntimeData->status = BUFFER_AVAILABLE; } } else { /* It is the local buffer that was provided to the PduR, that buffer is only * used for tester present reception in parallel to diagnostic requests */ if ((rxRuntime->localRxBuffer.status == PROVIDED_TO_PDUR) && (rxRuntime->localRxBuffer.DcmRxPduId == dcmRxPduId)) { boolean receivedLenOK = ((0 == rxRuntime->localRxBuffer.PduInfo.SduLength) || (rxRuntime->localRxBuffer.PduInfo.SduLength == rxRuntime->localRxBuffer.nofBytesHandled)); if ( (result == NTFRSLT_OK) && (TRUE == receivedLenOK) ) { // Make sure that the data in buffer is valid. if (TRUE == isTesterPresentCommand(&(rxRuntime->localRxBuffer.PduInfo))) { /* @req DCM141 */ /* @req DCM112 */ /* @req DCM113 */ startS3SessionTimer(rxRuntime, protocolRow); }else{ DCM_DET_REPORTERROR(DCM_TP_RX_INDICATION_ID, DCM_E_WRONG_BUFFER); } } else { if(FALSE == receivedLenOK) { /* Number of bytes received does not match the original request */ DCM_DET_REPORTERROR(DCM_TP_RX_INDICATION_ID, DCM_E_TP_LENGTH_MISMATCH); } DslResetSessionTimeoutTimer(); /* @req DCM141 */ } rxRuntime->localRxBuffer.status = NOT_IN_USE; rxRuntime->localRxBuffer.DcmRxPduId = DCM_INVALID_PDU_ID; } } SchM_Exit_Dcm_EA_0(); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'BufReq_ReturnType Dcm_CopyTxData(PduIdType dcmTxPduId, // PduInfoType *pduInfoPtr, RetryInfoType *retryInfoPtr, PduLengthType *txDataCntPtr)'. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // This TX-buffer request is likely triggered by the transport layer (i.e. CanTp) // after PduR_DcmTransmit() has been called (via PduR to CanTp) indicating that something // is to be sent. The PduR_DcmTransmit() call is done from the DSL main function when // it has detected that the pending request has been answered by DSD // (or any other module?). BufReq_ReturnType DslCopyTxData(PduIdType dcmTxPduId, PduInfoType *pduInfoPtr, RetryInfoType *periodData, PduLengthType *txDataCntPtr) { /* !req DCM350 */ BufReq_ReturnType ret = BUFREQ_NOT_OK; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; //lint -estring(920,pointer) /* cast to void */ (void) periodData;//Not used //lint +estring(920,pointer) /* cast to void */ DEBUG( DEBUG_MEDIUM, "DslProvideTxBuffer=%d\n", dcmTxPduId); if (TRUE == findTxPduIdParentConfigurationLeafs(dcmTxPduId, &protocolRow, &runtime)) { const Dcm_DslBufferType *externalTxBuffer = protocolRow->DslProtocolTxBufferID; ret = BUFREQ_OK; switch (runtime->externalTxBufferStatus) { // ### EXTERNAL TX BUFFER ### case DCM_TRANSMIT_SIGNALED: externalTxBuffer->externalBufferRuntimeData->nofBytesHandled = 0; runtime->externalTxBufferStatus = PROVIDED_TO_PDUR; /* @req DCM349 */ break; case PROVIDED_TO_PDUR: break; default: DEBUG( DEBUG_MEDIUM, "DCM_TRANSMIT_SIGNALED was not signaled in the external buffer\n"); ret = BUFREQ_NOT_OK; break; } if( BUFREQ_OK == ret ) { if( 0 == pduInfoPtr->SduLength ) { /* Just polling size of data left to send */ } else if( pduInfoPtr->SduLength > (runtime->diagnosticResponseFromDsd.SduLength - externalTxBuffer->externalBufferRuntimeData->nofBytesHandled) ) { /* Length exceeds the number of bytes still to be sent. */ ret = BUFREQ_NOT_OK; } else { /* @req DCM346 Length verification is already done if this state is reached. */ memcpy(pduInfoPtr->SduDataPtr, &runtime->diagnosticResponseFromDsd.SduDataPtr[externalTxBuffer->externalBufferRuntimeData->nofBytesHandled], pduInfoPtr->SduLength); externalTxBuffer->externalBufferRuntimeData->nofBytesHandled += pduInfoPtr->SduLength; } *txDataCntPtr = runtime->diagnosticResponseFromDsd.SduLength - externalTxBuffer->externalBufferRuntimeData->nofBytesHandled; } else if (ret == BUFREQ_NOT_OK) { ret = BUFREQ_OK; switch (runtime->localTxBuffer.status) { // ### LOCAL TX BUFFER ### case DCM_TRANSMIT_SIGNALED: { runtime->localTxBuffer.PduInfo.SduDataPtr = runtime->localTxBuffer.buffer; runtime->localTxBuffer.nofBytesHandled = 0; runtime->localTxBuffer.status = PROVIDED_TO_PDUR; // Now the DSL should not touch this Tx-buffer anymore. break; } case PROVIDED_TO_PDUR: break; default: DEBUG( DEBUG_MEDIUM, "DCM_TRANSMIT_SIGNALED was not signaled for the local buffer either\n"); ret = BUFREQ_NOT_OK; break; } if( BUFREQ_OK == ret ) { if( 0 == pduInfoPtr->SduLength ) { /* Just polling size of data left to send */ } else if( pduInfoPtr->SduLength > (runtime->localTxBuffer.PduInfo.SduLength - runtime->localTxBuffer.nofBytesHandled) ) { /* Length exceeds the number of bytes still to be sent. */ ret = BUFREQ_NOT_OK; } else { memcpy(pduInfoPtr->SduDataPtr, &runtime->localTxBuffer.PduInfo.SduDataPtr[runtime->localTxBuffer.nofBytesHandled], pduInfoPtr->SduLength); runtime->localTxBuffer.nofBytesHandled += pduInfoPtr->SduLength; } *txDataCntPtr = runtime->localTxBuffer.PduInfo.SduLength - runtime->localTxBuffer.nofBytesHandled; } }else{ /* do noting */ } } return ret; /*lint --e{818) pduInfoPtr cannot made as const it is used in memcpy and as per Api is autosar standard */ } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Implements 'void Dcm_TpTxConfirmation(PduIdType dcmTxPduId, NotifResultType result))'. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // This function is called by the PduR (which has been trigged by i.e. CanTp) // when a transmission has been successfully finished, have had errors or // is even stopped. void DslTpTxConfirmation(PduIdType dcmTxPduId, NotifResultType result) { /* @req DCM170 Not calling ComM_DCM_InactiveDiagnostic */ /* @req DCM624 */ const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *rxMainConnection = NULL; const Dcm_DslConnectionType *rxConnection = NULL; const Dcm_DslProtocolRowType *txProtocolRow = NULL; const Dcm_DslProtocolRowType *rxProtocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *txRuntime = NULL; Dcm_DslRunTimeProtocolParametersType *rxRuntime = NULL; boolean flagvalueTx; boolean flagvalueRx; DEBUG( DEBUG_MEDIUM, "DslTxConfirmation=%d, result=%d\n", dcmTxPduId, result); if( !IS_PERIODIC_TX_PDU(dcmTxPduId) #if !(defined(DCM_USE_TYPE2_PERIODIC_TRANSMISSION) && defined(DCM_TYPE2_TX_ROUTED_TO_IF)) || TRUE #endif ) { flagvalueTx = findTxPduIdParentConfigurationLeafs(dcmTxPduId, &txProtocolRow, &txRuntime); flagvalueRx = findRxPduIdParentConfigurationLeafs(txRuntime->diagReqestRxPduId, &protocolRx, &rxMainConnection, &rxConnection, &rxProtocolRow, &rxRuntime); if ((TRUE == flagvalueTx) && (TRUE == flagvalueRx) ) { boolean externalBufferReleased = FALSE; const Dcm_DslBufferType *externalTxBuffer = txProtocolRow->DslProtocolTxBufferID; // Free the buffer and free the Pdu runtime data buffer. SchM_Enter_Dcm_EA_0(); switch (txRuntime->externalTxBufferStatus) { // ### EXTERNAL TX BUFFER ### case DCM_TRANSMIT_SIGNALED: //Dcm_CopyTxData has not been called if(result == NTFRSLT_OK){ DCM_DET_REPORTERROR(DCM_TP_TX_CONFIRMATION_ID, DCM_E_UNEXPECTED_EXECUTION); result = NTFRSLT_E_NOT_OK; } /* no break */ case PROVIDED_TO_PDUR:{ if( txRuntime->diagnosticResponseFromDsd.SduLength != externalTxBuffer->externalBufferRuntimeData->nofBytesHandled ) { DCM_DET_REPORTERROR(DCM_TP_TX_CONFIRMATION_ID, DCM_E_TP_LENGTH_MISMATCH); } #if defined(USE_COMM) if( DCM_DEFAULT_SESSION == rxRuntime->sessionControl ) { if( TRUE == findProtocolRx(rxRuntime->diagReqestRxPduId, &protocolRx) ) { if( TRUE == rxRuntime->diagnosticActiveComM ) { ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); /* @req DCM164 */ rxRuntime->diagnosticActiveComM = FALSE; } } } #endif /* @req DCM118 */ /* @req DCM352 */ /* @req DCM353 */ /* @req DCM354 */ releaseExternalRxTxBuffers(rxProtocolRow, rxRuntime); externalBufferReleased = TRUE; if(IS_PERIODIC_TX_PDU(dcmTxPduId)) { DsdDataConfirmation(Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolPeriodicTxGlobalList[TO_INTERNAL_PERIODIC_PDU(dcmTxPduId)].PduRTxPduId, result); DslReleaseType2TxPdu(dcmTxPduId); } else { /* Only start s3 timer if non-periodic */ startS3SessionTimer(rxRuntime, rxProtocolRow); /* @req DCM141 */ /* @req DCM117 */ /* @req DCM235 */ DsdDataConfirmation(rxMainConnection->DslProtocolTx->DcmDslProtocolTxPduId, result); } break; } default: break; } if (FALSE == externalBufferReleased) { switch (txRuntime->localTxBuffer.status) { // ### LOCAL TX BUFFER ### case DCM_TRANSMIT_SIGNALED: //Dcm_CopyTxData has not been called if(result == NTFRSLT_OK){ DCM_DET_REPORTERROR(DCM_TP_TX_CONFIRMATION_ID, DCM_E_UNEXPECTED_EXECUTION); result = NTFRSLT_E_NOT_OK; } /* no break */ case PROVIDED_TO_PDUR: if( txRuntime->localTxBuffer.PduInfo.SduLength != txRuntime->localTxBuffer.nofBytesHandled ) { DCM_DET_REPORTERROR(DCM_TP_TX_CONFIRMATION_ID, DCM_E_TP_LENGTH_MISMATCH); } #if defined(USE_COMM) if( DCM_E_RESPONSEPENDING != txRuntime->localTxBuffer.responseCode ) { if( DCM_DEFAULT_SESSION == rxRuntime->sessionControl ) { if( TRUE == findProtocolRx(rxRuntime->diagReqestRxPduId, &protocolRx) ) { if( TRUE == rxRuntime->diagnosticActiveComM ) { /* @req DCM165 */ ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); rxRuntime->diagnosticActiveComM = FALSE; } } } } #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) else { /* Tx confirmation on response pending */ DsdResponsePendingConfirmed(rxMainConnection->DslProtocolTx->DcmDslProtocolTxPduId, result); } #endif #endif DEBUG( DEBUG_MEDIUM, "Released local buffer buffer OK!\n"); txRuntime->localTxBuffer.status = NOT_IN_USE; break; default: DEBUG( DEBUG_MEDIUM, "WARNING! DslTxConfirmation could not release external or local buffer!\n"); break; } } SchM_Exit_Dcm_EA_0(); } } #if defined(DCM_USE_TYPE2_PERIODIC_TRANSMISSION) && defined(DCM_TYPE2_TX_ROUTED_TO_IF) else { /* It is a periodic pdu. It is assumed that for these the buffers are released as soon as lower layer accepts * transmit request. */ PduIdType requestRxPduId = 0; SchM_Enter_Dcm_EA_0(); boolean flagvalue; flagvalue = findRxPduIdParentConfigurationLeafs(requestRxPduId, &protocolRx, &rxMainConnection, &rxConnection, &rxProtocolRow, &rxRuntime); if( (E_OK == DslGetType2TxUserRxPdu(dcmTxPduId, &requestRxPduId)) && (TRUE == flagvalue)) { #if defined(USE_COMM) if( DCM_DEFAULT_SESSION == rxRuntime->sessionControl ) { if( TRUE == rxRuntime->diagnosticActiveComM ) { ComM_DCM_InactiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle); /* @req DCM164 */ rxRuntime->diagnosticActiveComM = FALSE; } } #endif DsdDataConfirmation(Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolPeriodicTxGlobalList[TO_INTERNAL_PERIODIC_PDU(dcmTxPduId)].PduRTxPduId, result); } SchM_Exit_Dcm_EA_0(); DslReleaseType2TxPdu(dcmTxPduId); } #endif } #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) || (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) || (defined(DCM_USE_SERVICE_RESPONSEONEVENT) && defined(USE_NVM)) Std_ReturnType Arc_DslGetRxConnectionParams(PduIdType rxPduId, uint16* sourceAddress, Dcm_ProtocolAddrTypeType* reqType, Dcm_ProtocolType *protocolId) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; Std_ReturnType ret = E_OK; if (findRxPduIdParentConfigurationLeafs(rxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { *sourceAddress = mainConnection->DslRxTesterSourceAddress; *reqType = protocolRx->DslProtocolAddrType; *protocolId = protocolRow->DslProtocolID; } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); ret = E_NOT_OK; } return ret; } #endif /** * Tries to find a physical protocol given a protocol id and a tester source address * @param protocolId * @param testerSourceAddress * @param protocolRow * @param protocolPhysRx * @return TRUE: Protocol found, FALSE: Protocol not found */ static boolean findPhysRxProtocol(uint8 protocolId, uint16 testerSourceAddress, const Dcm_DslProtocolRowType **protocolRow, const Dcm_DslProtocolRxType **protocolPhysRx) { const Dcm_DslProtocolRowType *protocolRowEntry; const Dcm_DslConnectionType *connection = NULL; boolean found = FALSE; protocolRowEntry = Dcm_ConfigPtr->Dsl->DslProtocol->DslProtocolRowList; while((FALSE == protocolRowEntry->Arc_EOL) && (FALSE == found)) { /* Find matching protocol */ if(protocolId == protocolRowEntry->DslProtocolID) { if( NULL != protocolRowEntry->DslConnections) { /* Find connection with matching source address */ connection = protocolRowEntry->DslConnections; while((FALSE == connection->Arc_EOL) && (FALSE == found)) { if( (NULL != connection->DslMainConnection) && (testerSourceAddress == connection->DslMainConnection->DslRxTesterSourceAddress) && (NULL != connection->DslMainConnection->DslPhysicalProtocolRx)) { /* Match. */ *protocolRow = connection->DslProtocolRow; *protocolPhysRx = connection->DslMainConnection->DslPhysicalProtocolRx; found = TRUE; } connection++; } } } protocolRowEntry++; } return found; } /** * Starts a protocol when starting up as a consequence of jump from bootloader/application. * This function should only be used for that purpose * @param session * @param protocolId * @param testerSourceAddress * @param requestFullComm * @return E_OK: Protocol could be started, E_NOT_OK: Protocol start failed */ Std_ReturnType DslDspSilentlyStartProtocol(uint8 session, uint8 protocolId, uint16 testerSourceAddress, boolean requestFullComm) { /* IMPROVEMENT: Check if session is supported */ const Dcm_DslProtocolRxType *protocolPhysRx = NULL; const Dcm_DslProtocolRowType *rxProtocolRow = NULL; Std_ReturnType ret = E_NOT_OK; if( TRUE == findPhysRxProtocol(protocolId, testerSourceAddress, &rxProtocolRow, &protocolPhysRx) ) { /* Check if the session is supported */ if( TRUE == DspDslCheckSessionSupported(session) ) { rxProtocolRow->DslRunTimeProtocolParameters->protocolStarted = TRUE; rxProtocolRow->DslRunTimeProtocolParameters->sessionControl = session; rxProtocolRow->DslRunTimeProtocolParameters->securityLevel = DCM_SEC_LEV_LOCKED; DcmDslRunTimeData.activeProtocol = rxProtocolRow; if( DCM_DEFAULT_SESSION != session ) { startS3SessionTimer(rxProtocolRow->DslRunTimeProtocolParameters, rxProtocolRow); } } else { /* Session is not supported. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_INTEGRATION_ERROR); } if( TRUE == requestFullComm ) { /* Should request full communication from ComM */ /* @req DCM537 */ #if defined(USE_COMM) ComM_DCM_ActiveDiagnostic(Dcm_ConfigPtr->DcmComMChannelCfg[protocolPhysRx->ComMChannelInternalIndex].NetworkHandle); rxProtocolRow->DslRunTimeProtocolParameters->diagnosticActiveComM = TRUE; #endif } ret = E_OK; } return ret; } /** * Updates communication mode for a network * @param network * @param comMode */ #if defined(USE_COMM) void DslComModeEntered(uint8 network, DcmComModeType comMode) { const Dcm_ComMChannelConfigType *comMChannelcfg; boolean done = FALSE; comMChannelcfg = Dcm_ConfigPtr->DcmComMChannelCfg; while((FALSE == comMChannelcfg->Arc_EOL) && (FALSE == done)) { if( comMChannelcfg->NetworkHandle == network ) { NetWorkComMode[comMChannelcfg->InternalIndex] = comMode; done = TRUE; } comMChannelcfg++; } } #endif /** * Injects diagnostic request on Dcm startup * @param sid * @param subFnc * @param protocolId * @param testerSourceAddress * @return E_OK: Request processed, E_PENDING: Further calls required, E_NOT_OK: request failed */ Std_ReturnType DslDspResponseOnStartupRequest(uint8 sid, uint8 subFnc, uint8 protocolId, uint16 testerSourceAddress) { Std_ReturnType ret = E_NOT_OK; const Dcm_DslProtocolRxType *protocolPhysRx = NULL; const Dcm_DslProtocolRowType *rxProtocolRow = NULL; if( TRUE == findPhysRxProtocol(protocolId, testerSourceAddress, &rxProtocolRow, &protocolPhysRx) ) { ret = E_PENDING; #if defined(USE_COMM) /* @req DCM767 */ if( DCM_FULL_COM == NetWorkComMode[protocolPhysRx->ComMChannelInternalIndex] ) #endif { PduLengthType rxBufferSize; if(BUFREQ_OK == DslStartOfReception(protocolPhysRx->DcmDslProtocolRxPduId, 2, &rxBufferSize, TRUE)) { PduInfoType request; uint8 data[2]; request.SduDataPtr = data; request.SduDataPtr[0] = sid; request.SduDataPtr[1] = subFnc; request.SduLength = 2; if( BUFREQ_OK == DslCopyDataToRxBuffer(protocolPhysRx->DcmDslProtocolRxPduId, &request, &rxBufferSize) ) { DslTpRxIndicationFromPduR(protocolPhysRx->DcmDslProtocolRxPduId, NTFRSLT_OK, TRUE, TRUE); } else { /* Something went wrong. Indicate that the reception was * not ok. */ DslTpRxIndicationFromPduR(protocolPhysRx->DcmDslProtocolRxPduId, NTFRSLT_E_NOT_OK, TRUE, TRUE); } ret = E_OK; } } } return ret; } #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) void DslSetDspProcessingActive(PduIdType dcmRxPduId, boolean state) { const Dcm_DslProtocolRxType *protocolRx = NULL; const Dcm_DslMainConnectionType *mainConnection = NULL; const Dcm_DslConnectionType *connection = NULL; const Dcm_DslProtocolRowType *protocolRow = NULL; Dcm_DslRunTimeProtocolParametersType *runtime = NULL; if (findRxPduIdParentConfigurationLeafs(dcmRxPduId, &protocolRx, &mainConnection, &connection, &protocolRow, &runtime)) { const Dcm_DslBufferType *externalRxBuffer = protocolRow->DslProtocolRxBufferID; const Dcm_DslBufferType *externalTxBuffer = protocolRow->DslProtocolTxBufferID; /* Indication from Dsp that it is currently handling a request */ SchM_Enter_Dcm_EA_0(); externalRxBuffer->externalBufferRuntimeData->dspProcessingActive = state; externalTxBuffer->externalBufferRuntimeData->dspProcessingActive = state; SchM_Exit_Dcm_EA_0(); } } #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL /** * Function used by Dsd to get protocol rx from pdu id * @param rxPduId * @param protocolRx * @return */ Std_ReturnType DslDsdGetProtocolRx(PduIdType rxPduId, const Dcm_DslProtocolRxType **protocolRx) { Std_ReturnType ret = E_NOT_OK; const Dcm_DslMainConnectionType *mainConnection; const Dcm_DslConnectionType *connection; const Dcm_DslProtocolRowType *protocolRow; Dcm_DslRunTimeProtocolParametersType *runtime; if( findRxPduIdParentConfigurationLeafs(rxPduId, protocolRx, &mainConnection, &connection, &protocolRow, &runtime) ) { ret = E_OK; } return ret; } #endif
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Dsl.c
C
unknown
93,208
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* * General requirements */ //lint -w2 Static code analysis warning level /* Disable MISRA 2004 rule 16.2, MISRA 2012 rule 17.2. * This because of recursive calls to readDidData. * */ //lint -estring(974,*recursive*) /* @req DCM273 */ /* @req DCM272 */ /* @req DCM696 */ /* @req DCM039 */ /* @req DCM269 */ /* @req DCM271 */ /* @req DCM275 */ /* !req DCM038 Paged buffer not supported */ /* !req DCM085 */ /* @req DCM531 A jump to bootloader is possible only with services DiagnosticSessionControl and LinkControl services */ /* @req DCM527 At first call of an operation using the Dcm_OpStatusType, OpStatus should be DCM_INITIAL */ /* !req DCM528 E_FORCE_RCRRP not supported return for all operations */ /* !req DCM530 E_PENDING not supported return for all operations */ /* @req DCM077 When calling DEM for OBD services, DCM shall use the following values for the parameter DTCOrigin: Service $0A uses DEM_DTC_ORIGIN_PERMANENT_MEMORY All other services use DEM_DTC_ORIGIN_PRIMARY_MEMORY */ #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #if defined(DCM_USE_SERVICE_CLEARDIAGNOSTICINFORMATION) || defined(DCM_USE_SERVICE_READDTCINFORMATION) || defined(DCM_USE_SERVICE_CONTROLDTCSETTING)\ || defined(DCM_USE_SERVICE_REQUESTPOWERTRAINFREEZEFRAMEDATA) || defined(DCM_USE_SERVICE_CLEAREMISSIONRELATEDDIAGNOSTICDATA)\ || defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDIAGNOSTICTROUBLECODES) || defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSDETECTEDDURINGCURRENTORLASTCOMPLETEDDRIVINGCYCLE)\ || defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSWITHPERMANENTSTATUS) #if defined(USE_DEM) #include "Dem.h"/* @req DCM332 */ #else #warning "Dcm: UDS services 0x14, 0x18 and/or 0x85 will not work without Dem." #warning "Dcm: OBD services $02, $03, $04, $07 and/or $0A will not work without Dem." #endif #endif #include "MemMap.h" #if defined(USE_MCU) #include "Mcu.h" #endif #ifndef DCM_NOT_SERVICE_COMPONENT #include "Rte_Dcm.h" #endif #if defined(USE_BSWM) #include "BswM_DCM.h" #endif #if defined(DCM_USE_SERVICE_REQUESTTRANSFEREXIT) || defined(DCM_USE_SERVICE_TRANSFERDATA) || defined(DCM_USE_SERVICE_REQUESTDOWNLOAD) || defined(DCM_USE_SERVICE_REQUESTUPLOAD) #define DCM_USE_UPLOAD_DOWNLOAD #endif /* * Macros */ #define ZERO_SUB_FUNCTION 0x00 #define DCM_FORMAT_LOW_MASK 0x0F #define DCM_FORMAT_HIGH_MASK 0xF0 #define DCM_MEMORY_ADDRESS_MASK 0x00FFFFFF #define DCM_DID_HIGH_MASK 0xFF00 #define DCM_DID_LOW_MASK 0xFF #define DCM_PERODICDID_HIGH_MASK 0xF200 #define SID_AND_DDDID_LEN 0x4 #define SDI_AND_MS_LEN 0x4 #define SID_AND_SDI_LEN 0x6 #define SID_AND_PISDR_LEN 0x7 /* == Parser macros == */ /* General */ #define SID_INDEX 0 #define SID_LEN 1u #define SF_INDEX 1 #define SF_LEN 1 #define DTC_LEN 3 #define FF_REC_NUM_LEN 1 #define HALF_BYTE 4 #define OFFSET_ONE_BYTE 8 #define OFFSET_TWO_BYTES 16 #define OFFSET_THREE_BYTES 24 /* Read/WriteMemeoryByAddress */ #define ALFID_INDEX 1 #define ALFID_LEN 1 #define ADDR_START_INDEX 2 /* DynamicallyDefineDataByIdentifier */ #define DDDDI_INDEX 2 #define DDDDI_LEN 2 #define DYNDEF_ALFID_INDEX 4 #define DYNDEF_ADDRESS_START_INDEX 5 /* InputOutputControlByIdentifier */ #define IOI_INDEX 1 #define IOI_LEN 2 #define IOCP_INDEX 3 #define IOCP_LEN 1 #define COR_INDEX 4 #define IS_VALID_IOCTRL_PARAM(_x) ((_x) <= DCM_SHORT_TERM_ADJUSTMENT) #define TO_SIGNAL_BIT(_x) (uint8)(1u<<(7u-((_x)%8u))) /*OBD RequestCurrentPowertrainDiagnosticData*/ #define PIDZERO 0 #define DATAZERO 0 #define INFOTYPE_ZERO 0 #define PID_LEN 1 #define RECORD_NUM_ZERO 0 #define SUPPRTED_PIDS_DATA_LEN 4 #define LEAST_BIT_MASK ((uint8)0x01u) #define OBD_DATA_LSB_MASK ((uint32)0x000000FFu) #define OBD_REQ_MESSAGE_LEN_ONE_MIN 2 #define OBD_REQ_MESSAGE_LEN_MAX 7 #define AVAIL_TO_SUPPORTED_PID_OFFSET_MIN 0x01 #define AVAIL_TO_SUPPORTED_PID_OFFSET_MAX 0x20 #define AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MIN 0x01 #define AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MAX 0x20 #define MAX_REQUEST_PID_NUM 6 #define LENGTH_OF_DTC 2 /* CommunicationControl */ #define CC_CTP_INDEX 2 #define IS_SUPPORTED_0x28_SUBFUNCTION(_x) ((_x) < 4u) #define UDS_0x28_NOF_COM_TYPES 3u #define UDS_0x28_NOF_SUB_FUNCTIONS 4u #define IS_VALID_0x28_COM_TYPE(_x) (((_x) > 0u) && ((_x) < 4u)) /*OBD RequestCurrentPowertrainDiagnosticData*/ #define FF_NUM_LEN 1 #define OBD_DTC_LEN 2 #define OBD_SERVICE_TWO ((uint8)0x02u) #define MAX_PID_FFNUM_NUM 3 #define OBD_REQ_MESSAGE_LEN_TWO_MIN 3 #define DATA_ELEMENT_INDEX_OF_PID_NOT_SUPPORTED 0 #define OBD_SERVICE_2_PID_AND_FRAME_SIZE 2u #define OBD_SERVICE_2_PID_INDEX 0u #define OBD_SERVICE_2_FRAME_INDEX 1u /*OBD RequestEmissionRelatedDiagnosticTroubleCodes service03 07*/ #define EMISSION_DTCS_HIGH_BYTE(dtc) (((uint32)(dtc) >> 16) & 0xFFu) #define EMISSION_DTCS_LOW_BYTE(dtc) (((uint32)(dtc) >> 8) & 0xFFu) #define OBD_RESPONSE_DTC_MAX_NUMS 126 /*OBD OnBoardMonitoringTestResultsSpecificMonitoredSystems service06*/ #define OBDMID_LEN 1u #define OBDMID_DATA_START_INDEX 1u #define OBDM_TID_LEN 1u #define OBDM_UASID_LEN 1u #define OBDM_TESTRESULT_LEN 6u #define SUPPORTED_MAX_OBDMID_REQUEST_LEN 1u #define SUPPORTED_OBDM_OUTPUT_LEN (OBDM_TID_LEN + OBDM_UASID_LEN + OBDM_TESTRESULT_LEN) #define SUPPORTED_OBDMIDS_DATA_LEN 4u #define AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MIN 0x01 #define AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MAX 0x20 #define MAX_REQUEST_OBDMID_NUM 6u #define IS_AVAILABILITY_OBDMID(_x) ((0 == ((_x) % 0x20)) && ((_x) <= 0xE0)) #define OBDM_LSB_MASK 0xFFu /*OBD Requestvehicleinformation service09*/ #define OBD_TX_MAXLEN 0xFF #define MAX_REQUEST_VEHINFO_NUM 6 #define OBD_SERVICE_FOUR 0x04 #define OBD_VIN_LENGTH 17 #define IS_AVAILABILITY_PID(_x) ( (0 == ((_x) % 0x20)) && ((_x) <= 0xE0)) #define IS_AVAILABILITY_INFO_TYPE(_x) IS_AVAILABILITY_PID(_x) #define BYTES_TO_DTC(hb, mb, lb) (((uint32)(hb) << 16) | ((uint32)(mb) << 8) | (uint32)(lb)) #define DTC_HIGH_BYTE(dtc) (((uint32)(dtc) >> 16) & 0xFFu) #define DTC_MID_BYTE(dtc) (((uint32)(dtc) >> 8) & 0xFFu) #define DTC_LOW_BYTE(dtc) ((uint32)(dtc) & 0xFFu) /* UDS ReadDataByPeriodicIdentifier */ #define TO_PERIODIC_DID(_x) (DCM_PERODICDID_HIGH_MASK + (uint16)(_x)) /* Maximum length for periodic Dids */ #define MAX_PDID_DATA_SIZE 7 /* CAN */ #define MAX_TYPE2_PERIODIC_DID_LEN_CAN 7 #define MAX_TYPE1_PERIODIC_DID_LEN_CAN 5 /* Flexray */ /* IMPROVEMENT: Maximum length for flexray? */ #define MAX_TYPE2_PERIODIC_DID_LEN_FLEXRAY 0 #define MAX_TYPE1_PERIODIC_DID_LEN_FLEXRAY 0 /* Ip */ /* IMPROVEMENT: Maximum length for ip? */ #define MAX_TYPE2_PERIODIC_DID_LEN_IP 0 #define MAX_TYPE1_PERIODIC_DID_LEN_IP 0 #define TIMER_DECREMENT(timer) \ if (timer >= DCM_MAIN_FUNCTION_PERIOD_TIME_MS) { \ timer = timer - DCM_MAIN_FUNCTION_PERIOD_TIME_MS; \ } \ /* UDS Linkcontrol */ #define LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_FIXED_BAUDRATE 0x01 #define LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_SPECIFIC_BAUDRATE 0x02 #define LINKCONTROL_SUBFUNC_TRANSITION_BAUDRATE 0x03 typedef enum { DCM_READ_MEMORY = 0, DCM_WRITE_MEMORY, } DspMemoryServiceType; typedef enum { DCM_DSP_RESET_NO_RESET, DCM_DSP_RESET_PENDING, DCM_DSP_RESET_WAIT_TX_CONF, } DcmDspResetStateType; typedef struct { DcmDspResetStateType resetPending; PduIdType resetPduId; PduInfoType *pduTxData; Dcm_EcuResetType resetType; } DspUdsEcuResetDataType; typedef enum { DCM_JTB_IDLE, DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM, DCM_JTB_EXECUTE, DCM_JTB_RESAPP_FINAL_RESPONSE_TX_CONFIRM, DCM_JTB_RESAPP_WAIT_RESPONSE_PENDING_TX_CONFIRM, DCM_JTB_RESAPP_ASSEMBLE_FINAL_RESPONSE }DspJumpToBootState; typedef struct { boolean pendingSessionChange; PduIdType sessionPduId; Dcm_SesCtrlType session; DspJumpToBootState jumpToBootState; const PduInfoType* pduRxData; PduInfoType* pduTxData; uint16 P2; uint16 P2Star; Dcm_ProtocolType protocolId; } DspUdsSessionControlDataType; typedef struct { PduIdType confirmPduId; DspJumpToBootState jumpToBootState; const PduInfoType* pduRxData; PduInfoType* pduTxData; } DspUdsLinkControlDataType; typedef struct { ReadDidPendingStateType state; const PduInfoType* pduRxData; PduInfoType* pduTxData; uint16 txWritePos; uint16 nofReadDids; uint16 reqDidIndex; uint16 pendingDid; uint16 pendingDataLength; uint16 pendingSignalIndex; uint16 pendingDataStartPos; } DspUdsReadDidPendingType; typedef enum { DCM_GENERAL_IDLE, DCM_GENERAL_PENDING, DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND, DCM_GENERAL_FORCE_RCRRP, } GeneralPendingStateType; typedef struct { GeneralPendingStateType state; const PduInfoType* pduRxData; PduInfoType* pduTxData; uint8 pendingService; } DspUdsGeneralPendingType; typedef struct { boolean comControlPending; uint8 subFunction; uint8 subnet; uint8 comType; PduIdType confirmPdu; PduIdType rxPdu; } DspUdsCommunicationControlDataType; static DspUdsEcuResetDataType dspUdsEcuResetData; static DspUdsSessionControlDataType dspUdsSessionControlData; #if defined(DCM_USE_SERVICE_LINKCONTROL) static DspUdsLinkControlDataType dspUdsLinkControlData; #endif static DspUdsReadDidPendingType dspUdsReadDidPending; #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER static DspUdsGeneralPendingType dspUdsWriteDidPending; #endif static DspUdsGeneralPendingType dspUdsRoutineControlPending; static DspUdsGeneralPendingType dspUdsSecurityAccessPending; #if defined(DCM_USE_UPLOAD_DOWNLOAD) static DspUdsGeneralPendingType dspUdsUploadDownloadPending; #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL static DspUdsCommunicationControlDataType communicationControlData; #endif typedef enum { DELAY_TIMER_DEACTIVE, DELAY_TIMER_ON_BOOT_ACTIVE, DELAY_TIMER_ON_EXCEEDING_LIMIT_ACTIVE }DelayTimerActivation; typedef struct { uint8 secAcssAttempts; //Counter for number of false attempts uint32 timerSecAcssAttempt; //Timer after exceededNumberOfAttempts DelayTimerActivation startDelayTimer; //Flag to indicate Delay timer is active }DspUdsSecurityAccessChkParam; typedef struct { boolean reqInProgress; Dcm_SecLevelType reqSecLevel; #if (DCM_SECURITY_EOL_INDEX != 0) DspUdsSecurityAccessChkParam secFalseAttemptChk[DCM_SECURITY_EOL_INDEX]; uint8 currSecLevIdx; //Current index for secFalseAttemptChk #endif const Dcm_DspSecurityRowType *reqSecLevelRef; } DspUdsSecurityAccessDataType; static DspUdsSecurityAccessDataType dspUdsSecurityAccesData; typedef enum{ DCM_MEMORY_UNUSED, DCM_MEMORY_READ, DCM_MEMORY_WRITE, DCM_MEMORY_FAILED }Dcm_DspMemoryStateType; Dcm_DspMemoryStateType dspMemoryState; typedef enum{ DCM_DDD_SOURCE_DEFAULT, DCM_DDD_SOURCE_DID, DCM_DDD_SOURCE_ADDRESS }Dcm_DspDDDSourceKindType; typedef enum { PDID_ADDED = 0, PDID_UPDATED, PDID_BUFFER_FULL }PdidEntryStatusType; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) typedef enum { PDID_NOT_SAMPLED = 0, PDID_SAMPLED_OK, PDID_SAMPLED_FAILED }PdidSampleStatus; #endif typedef struct{ uint32 PDidTxCounter; uint32 PDidTxPeriod; PduIdType PDidRxPduID; uint8 PeriodicDid; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) uint8 PdidData[MAX_PDID_DATA_SIZE]; uint8 PdidLength; PdidSampleStatus PdidSampleStatus; #endif }Dcm_pDidType;/* a type to save the periodic DID and cycle */ typedef struct{ Dcm_pDidType dspPDid[DCM_LIMITNUMBER_PERIODDATA]; /*a buffer to save the periodic DID and cycle */ uint8 PDidNofUsed; /* note the number of periodic DID is used */ uint8 nextStartIndex; }Dsp_pDidRefType; #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) static Dsp_pDidRefType dspPDidRef; #endif typedef struct{ uint8 formatOrPosition; /*note the formate of address and size*/ uint8 memoryIdentifier; uint32 SourceAddressOrDid; /*note the memory address */ uint16 Size; /*note the memory size */ Dcm_DspDDDSourceKindType DDDTpyeID; }Dcm_DspDDDSourceType; typedef struct{ uint16 DynamicallyDid; Dcm_DspDDDSourceType DDDSource[DCM_MAX_DDDSOURCE_NUMBER]; }Dcm_DspDDDType; #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER static Dcm_DspDDDType dspDDD[DCM_MAX_DDD_NUMBER]; #endif #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) typedef uint8 Dcm_DspIOControlVector[(DCM_MAX_IOCONTROL_DID_SIGNALS + 7) / 8]; typedef struct { uint16 did; boolean controlActive; Dcm_DspIOControlVector activeSignalBitfield; }Dcm_DspIOControlStateType; static Dcm_DspIOControlStateType IOControlStateList[DCM_NOF_IOCONTROL_DIDS]; typedef struct { const PduInfoType* pduRxData; PduInfoType* pduTxData; uint16 pendingSignalIndex; boolean pendingControl; GeneralPendingStateType state; Dcm_DspIOControlVector signalAffected; boolean controlActivated; }DspUdsIOControlPendingType; static DspUdsIOControlPendingType IOControlData; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) typedef struct { Dem_DTCGroupType dtcGroup; Dem_DTCKindType dtcKind; boolean settingDisabled; }Dcm_DspControlDTCSettingsType; static Dcm_DspControlDTCSettingsType DspDTCSetting; #endif #if defined(DCM_USE_UPLOAD_DOWNLOAD) typedef enum { DCM_NO_DATA_TRANSFER, DCM_UPLOAD, DCM_DOWNLOAD }DcmDataTransferType; typedef struct { uint32 nextAddress; uint8 blockSequenceCounter; DcmDataTransferType transferType; boolean firstBlockReceived; uint32 uplBytesLeft; /* Bytes left to be uploaded */ uint32 uplMemBlockSize; /* block length is maxNumberOfBlockLength (ISO14229) minus SID and lengthFormatIdentifier */ }DcmTransferStatusType; static DcmTransferStatusType TransferStatus; #endif static Dcm_ProgConditionsType GlobalProgConditions; static GeneralPendingStateType ProgConditionStartupResponseState; static boolean ProtocolStartRequested = FALSE; #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL static Dcm_CommunicationModeType DspChannelComMode[DCM_NOF_COMM_CHANNELS]; #endif /* * * static Function */ #ifndef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER #define LookupDDD(_x, _y ) FALSE #define readDDDData(_x, _y, _z, _v) DCM_E_GENERALREJECT #else static boolean LookupDDD(uint16 didNr, const Dcm_DspDDDType **DDid); #endif static Dcm_NegativeResponseCodeType checkAddressRange(DspMemoryServiceType serviceType, uint8 memoryIdentifier, uint32 memoryAddress, uint32 length); static const Dcm_DspMemoryRangeInfo* findRange(const Dcm_DspMemoryRangeInfo *memoryRangePtr, uint32 memoryAddress, uint32 length); static Dcm_NegativeResponseCodeType writeMemoryData(Dcm_OpStatusType* OpStatus, uint8 memoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8 *SourceData); static void DspCancelPendingDid(uint16 didNr, uint16 signalIndex, ReadDidPendingStateType pendingState, PduInfoType *pduTxData ); static void DspCancelPendingRoutine(const PduInfoType *pduRxData, PduInfoType *pduTxData); static void DspCancelPendingSecurityAccess(const PduInfoType *pduRxData, PduInfoType *pduTxData); static Dcm_NegativeResponseCodeType DspUdsSecurityAccessCompareKeySubFnc (const PduInfoType *pduRxData, PduInfoType *pduTxData, Dcm_SecLevelType requestedSecurityLevel, boolean isCancel); static Dcm_NegativeResponseCodeType DspUdsSecurityAccessGetSeedSubFnc (const PduInfoType *pduRxData, PduInfoType *pduTxData, Dcm_SecLevelType requestedSecurityLevel, boolean isCancel); #if defined(DCM_USE_UPLOAD_DOWNLOAD) static void DspCancelPendingUploadDownload(uint8 SID); #endif #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) static void DspStopInputOutputControl(boolean checkSessionAndSecLevel); static void DspIOControlStopActivated(uint16 didNr, Dcm_DspIOControlVector signalActivated); static Std_ReturnType FunctionInputOutputControl(const Dcm_DspDataType *DataPtr, Dcm_IOControlParameterType action, Dcm_OpStatusType opStatus, uint8* controlOptionRecord, Dcm_NegativeResponseCodeType* responseCode); #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER static boolean checkPDidSupported(uint16 pDid, uint16 *didLength, Dcm_NegativeResponseCodeType *responseCode); static void DspPdidRemove(uint8 pDid, PduIdType rxPduId); static void DspStopPeriodicDids(boolean checkSessionAndSecLevel); static Dcm_NegativeResponseCodeType getPDidData(uint16 did, uint8 *data, uint16 bufSize, uint16 *dataLength); #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) static void DspSamplePDids(uint32 period, PduIdType rxPduId); #endif #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) static void DspEnableDTCSetting(void); #endif static void SetOpStatusDependingOnState(DspUdsGeneralPendingType *pGeneralPending,Dcm_OpStatusType *opStatus, boolean isCancel); #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL static Dcm_NegativeResponseCodeType DspInternalCommunicationControl(uint8 subFunction, uint8 subNet, uint8 comType, PduIdType rxPduId, boolean executeModeSwitch); static void DspStopCommunicationControl(boolean checkSessionAndSecLevel); #endif /* * end */ // // This function reset diagnostic activity on session transition. //This function should be called after the session and security level have been changed // // void DspResetDiagnosticActivityOnSessionChange(Dcm_SesCtrlType newSession) { (void)newSession; #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) /* DCM628 says that active control should be stopped on transition * to default session only. But stop it if active control is not * supported in the new session (which should be the current session * as it is assumed that session is changed before calling this function) or * in the new security level. */ DspStopInputOutputControl(TRUE); IOControlData.state = DCM_GENERAL_IDLE; #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER DspStopPeriodicDids(TRUE); #endif #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && (DCM_ROE_INIT_ON_DSC == STD_ON) /* Stop the response on event service */ /* NOTE: ROE actually already stopped it this function * is called due to session change on service request. * But stop it here since this function is called when * resetting to default session due to s3 timeout. */ /* @req DCM618 */ if (DCM_ROE_IsActive()) { (void)Dcm_StopROE(); } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) DspEnableDTCSetting(); #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL DspStopCommunicationControl(TRUE); #endif dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; dspUdsSessionControlData.pendingSessionChange = FALSE; ProgConditionStartupResponseState = DCM_GENERAL_IDLE; } /* Resets active diagnostics on protocol preemtion */ void DcmDspResetDiagnosticActivity(void) { #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) DspStopInputOutputControl(FALSE); IOControlData.state = DCM_GENERAL_IDLE; #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER DspStopPeriodicDids(FALSE); #endif #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && (DCM_ROE_INIT_ON_DSC == STD_ON) /* NOTE: Actually not mentioned in spec. that ROE should be stopped * on protocol preemption. But it is reasonable to do it. */ /* Stop the response on event service */ if (DCM_ROE_IsActive()) { (void)Dcm_StopROE(); } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) DspEnableDTCSetting(); #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL DspStopCommunicationControl(FALSE); #endif dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; dspUdsSessionControlData.pendingSessionChange = FALSE; ProgConditionStartupResponseState = DCM_GENERAL_IDLE; } #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER typedef struct { PduIdType rxPduId; uint8 pDid; }pDidType; /** * Stops periodic Dids not supported in current session or security level * @param checkSessionAndSecLevel */ static void DspStopPeriodicDids(boolean checkSessionAndSecLevel) { uint16 didLength; Dcm_NegativeResponseCodeType resp; pDidType pDidsToRemove[DCM_LIMITNUMBER_PERIODDATA]; uint8 nofPDidsToRemove = 0; memset(pDidsToRemove, 0, sizeof(pDidsToRemove)); if( checkSessionAndSecLevel && DsdDspCheckServiceSupportedInActiveSessionAndSecurity(SID_READ_DATA_BY_PERIODIC_IDENTIFIER) ) { for(uint8 i = 0; i < dspPDidRef.PDidNofUsed; i++) { resp = DCM_E_REQUESTOUTOFRANGE; if( !(checkPDidSupported(TO_PERIODIC_DID(dspPDidRef.dspPDid[i].PeriodicDid), &didLength, &resp) && (DCM_E_POSITIVERESPONSE == resp)) ) { /* Not supported */ pDidsToRemove[nofPDidsToRemove].pDid = dspPDidRef.dspPDid[i].PeriodicDid; pDidsToRemove[nofPDidsToRemove++].rxPduId = dspPDidRef.dspPDid[i].PDidRxPduID; } } for( uint8 i = 0; i < nofPDidsToRemove; i++ ) { DspPdidRemove(pDidsToRemove[i].pDid, pDidsToRemove[i].rxPduId); } } else { /* Should not check session and security or service not supported in the current session or security. * Clear all. */ memset(&dspPDidRef,0,sizeof(dspPDidRef)); } } #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL static void DspStopCommunicationControl(boolean checkSessionAndSecLevel) { const Dcm_ComMChannelConfigType * comMChannelCfg = Dcm_ConfigPtr->DcmComMChannelCfg; if( (FALSE == checkSessionAndSecLevel) || (FALSE == DsdDspCheckServiceSupportedInActiveSessionAndSecurity(SID_COMMUNICATION_CONTROL)) ) { while( TRUE != comMChannelCfg->Arc_EOL ) { if( DCM_ENABLE_RX_TX_NORM_NM != DspChannelComMode[comMChannelCfg->InternalIndex] ) { (void)comMChannelCfg->ModeSwitchFnc(RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM_NM); #if defined(USE_BSWM) BswM_Dcm_CommunicationMode_CurrentState(comMChannelCfg->NetworkHandle, DCM_ENABLE_RX_TX_NORM_NM); #endif DspChannelComMode[comMChannelCfg->InternalIndex] = DCM_ENABLE_RX_TX_NORM_NM; } comMChannelCfg++; } } } #endif /** * Init function for Dsp * @param firstCall */ void DspInit(boolean firstCall) { dspUdsSecurityAccesData.reqInProgress = FALSE; dspUdsEcuResetData.resetPending = DCM_DSP_RESET_NO_RESET; dspUdsSessionControlData.pendingSessionChange = FALSE; #if defined(DCM_USE_SERVICE_LINKCONTROL) dspUdsLinkControlData.jumpToBootState = DCM_JTB_IDLE; #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) if( firstCall ) { DspDTCSetting.settingDisabled = FALSE; } #endif dspMemoryState = DCM_MEMORY_UNUSED; /* clear periodic send buffer */ #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) memset(&dspPDidRef,0,sizeof(dspPDidRef)); #endif #ifdef DCM_USE_CONTROL_DIDS if(firstCall) { memset(IOControlStateList, 0, sizeof(IOControlStateList)); IOControlData.state = DCM_GENERAL_IDLE; } #endif #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER /* clear dynamically Did buffer */ memset(&dspDDD[0],0,sizeof(dspDDD)); #endif #if (DCM_SECURITY_EOL_INDEX != 0) uint8 temp = 0; if (firstCall) { //Reset the security access attempts do { dspUdsSecurityAccesData.secFalseAttemptChk[temp].secAcssAttempts = 0; if (Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[temp].DspSecurityDelayTimeOnBoot >= DCM_MAIN_FUNCTION_PERIOD_TIME_MS) { dspUdsSecurityAccesData.secFalseAttemptChk[temp].timerSecAcssAttempt = Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[temp].DspSecurityDelayTimeOnBoot; dspUdsSecurityAccesData.secFalseAttemptChk[temp].startDelayTimer = DELAY_TIMER_ON_BOOT_ACTIVE; } else { dspUdsSecurityAccesData.secFalseAttemptChk[temp].startDelayTimer = DELAY_TIMER_DEACTIVE; } temp++; } while (temp < DCM_SECURITY_EOL_INDEX); dspUdsSecurityAccesData.currSecLevIdx = 0; } #else (void)firstCall; #endif #if defined(DCM_USE_UPLOAD_DOWNLOAD) TransferStatus.blockSequenceCounter = 0; TransferStatus.firstBlockReceived = FALSE; TransferStatus.transferType = DCM_NO_DATA_TRANSFER; dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; #endif dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; ProgConditionStartupResponseState = DCM_GENERAL_IDLE; #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL communicationControlData.comControlPending = FALSE; if (firstCall) { memset(DspChannelComMode, DCM_ENABLE_RX_TX_NORM_NM, sizeof(DspChannelComMode)); } #endif } /** * Function called first main function after init to allow Dsp to request * protocol start request */ void DspCheckProtocolStartRequests(void) { /* @req DCM536 */ if(DCM_WARM_START == Dcm_GetProgConditions(&GlobalProgConditions)) { /* Jump from bootloader */ #if 0 /* !req DCM768 */ #if defined(USE_BSWM) if( progConditions.ApplUpdated ) { BswM_Dcm_ApplicationUpdated(); } #endif #endif GlobalProgConditions.ApplUpdated = FALSE; if( (SID_DIAGNOSTIC_SESSION_CONTROL == GlobalProgConditions.Sid) || (SID_ECU_RESET == GlobalProgConditions.Sid)) { uint8 session = (SID_DIAGNOSTIC_SESSION_CONTROL == GlobalProgConditions.Sid) ? GlobalProgConditions.SubFncId : DCM_DEFAULT_SESSION; if( E_OK == DcmRequestStartProtocol(DCM_REQ_DSP, session, GlobalProgConditions.ProtocolId, GlobalProgConditions.TesterSourceAdd, GlobalProgConditions.ResponseRequired) ) { ProtocolStartRequested = TRUE; } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } } } } /** * Protocol start notification * @param started */ void DcmDspProtocolStartNotification(boolean started) { if( ProtocolStartRequested ) { if(started) { if( GlobalProgConditions.ResponseRequired ) { /* Wait until full communication has been indicated, then send a response to service */ ProgConditionStartupResponseState = DCM_GENERAL_PENDING; } } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } } else { /* Have not requested a start.. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } /** * Get the rte mode corresponding to a reset type * @param resetType * @param rteMode * @return E_OK: rte mode found, E_NOT_OK: rte mode not found */ static Std_ReturnType getResetRteMode(Dcm_EcuResetType resetType, uint8 *rteMode) { Std_ReturnType ret = E_OK; switch(resetType) { case DCM_HARD_RESET: *rteMode = RTE_MODE_DcmEcuReset_HARD; break; case DCM_KEY_OFF_ON_RESET: *rteMode = RTE_MODE_DcmEcuReset_KEYONOFF; break; case DCM_SOFT_RESET: *rteMode = RTE_MODE_DcmEcuReset_SOFT; break; default: ret = E_NOT_OK; break; } return ret; } /** * Main function for executing ECU reset */ void DspResetMainFunction(void) { Std_ReturnType result = E_NOT_OK; uint8 rteMode; if( (DCM_DSP_RESET_PENDING == dspUdsEcuResetData.resetPending) && (E_OK == getResetRteMode(dspUdsEcuResetData.resetType, &rteMode)) ) { /* IMPROVEMENT: Should be a call to SchM */ result = Rte_Switch_DcmEcuReset_DcmEcuReset(rteMode); switch( result ) { case E_OK: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_WAIT_TX_CONF; // Create positive response dspUdsEcuResetData.pduTxData->SduDataPtr[1] = dspUdsEcuResetData.resetType; dspUdsEcuResetData.pduTxData->SduLength = 2; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); break; case E_PENDING: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_PENDING; break; case E_NOT_OK: default: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_NO_RESET; DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); break; } } } #if defined(DCM_USE_SERVICE_READMEMORYBYADDRESS) || defined(DCM_USE_SERVICE_WRITEMEMORYBYADDRESS) /** * Main function for write/read memory */ void DspMemoryMainFunction(void) { /* IMPROVEMENT: DCM_WRITE_FORCE_RCRRP */ Dcm_ReturnWriteMemoryType WriteRet; Dcm_ReturnReadMemoryType ReadRet; switch(dspMemoryState) { case DCM_MEMORY_UNUSED: break; case DCM_MEMORY_READ: ReadRet = Dcm_ReadMemory(DCM_PENDING,0,0,0,0); if(ReadRet == DCM_READ_OK) {/*asynchronous writing is ok*/ DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); dspMemoryState = DCM_MEMORY_UNUSED; } else if(ReadRet == DCM_READ_FAILED) { /* @req DCM644 */ DsdDspProcessingDone(DCM_E_GENERALPROGRAMMINGFAILURE); dspMemoryState = DCM_MEMORY_UNUSED; } break; case DCM_MEMORY_WRITE: WriteRet = Dcm_WriteMemory(DCM_PENDING,0,0,0,0); if(WriteRet == DCM_WRITE_OK) {/*asynchronous writing is ok*/ DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); dspMemoryState = DCM_MEMORY_UNUSED; } else if(WriteRet == DCM_WRITE_FAILED) { /* @req DCM643 */ DsdDspProcessingDone(DCM_E_GENERALPROGRAMMINGFAILURE); dspMemoryState = DCM_MEMORY_UNUSED; } break; default: break; } } #endif #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) /** * Main function for reading periodic DIDs */ void DspPeriodicDIDMainFunction() { boolean sentResponseThisLoop = FALSE; uint8 pDidIndex = dspPDidRef.nextStartIndex; if( 0 != dspPDidRef.PDidNofUsed ) { dspPDidRef.nextStartIndex %= dspPDidRef.PDidNofUsed; } for(uint8 i = 0; i < dspPDidRef.PDidNofUsed; i++) { if(dspPDidRef.dspPDid[pDidIndex].PDidTxPeriod > dspPDidRef.dspPDid[pDidIndex].PDidTxCounter) { dspPDidRef.dspPDid[pDidIndex].PDidTxCounter++; } if( dspPDidRef.dspPDid[pDidIndex].PDidTxPeriod <= dspPDidRef.dspPDid[pDidIndex].PDidTxCounter ) { if( sentResponseThisLoop == FALSE ) { #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) if( PDID_NOT_SAMPLED == dspPDidRef.dspPDid[pDidIndex].PdidSampleStatus ) { DspSamplePDids(dspPDidRef.dspPDid[pDidIndex].PDidTxPeriod, dspPDidRef.dspPDid[pDidIndex].PDidRxPduID); } #endif if (E_OK == DslInternal_ResponseOnOneDataByPeriodicId(dspPDidRef.dspPDid[pDidIndex].PeriodicDid, dspPDidRef.dspPDid[pDidIndex].PDidRxPduID)){ dspPDidRef.dspPDid[pDidIndex].PDidTxCounter = 0; /*AutoSar DCM 8.10.5 */ sentResponseThisLoop = TRUE; dspPDidRef.nextStartIndex = (pDidIndex + 1) % dspPDidRef.PDidNofUsed; } } else { /* Don't do anything - PDid will be sent next loop */ } } pDidIndex++; pDidIndex %= dspPDidRef.PDidNofUsed; } } #endif /** * Main function for reading DIDs */ void DspReadDidMainFunction(void) { if( DCM_READ_DID_IDLE != dspUdsReadDidPending.state ) { DspUdsReadDataByIdentifier(dspUdsReadDidPending.pduRxData, dspUdsReadDidPending.pduTxData); } #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER if( DCM_GENERAL_PENDING == dspUdsWriteDidPending.state ) { DspUdsWriteDataByIdentifier(dspUdsWriteDidPending.pduRxData, dspUdsWriteDidPending.pduTxData); } #endif } /** * Main function for routine control */ void DspRoutineControlMainFunction(void) { if( DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND == dspUdsRoutineControlPending.state){ /* !req DCM528 */ /* !req DCM529 Should wait until transmit has been confirmed */ dspUdsRoutineControlPending.state = DCM_GENERAL_FORCE_RCRRP; // Do not try again until next main loop } else if( (DCM_GENERAL_PENDING == dspUdsRoutineControlPending.state) || (DCM_GENERAL_FORCE_RCRRP == dspUdsRoutineControlPending.state)) { DspUdsRoutineControl(dspUdsRoutineControlPending.pduRxData, dspUdsRoutineControlPending.pduTxData); } } /** * Main function for security access */ void DspSecurityAccessMainFunction(void) { if( DCM_GENERAL_PENDING == dspUdsSecurityAccessPending.state ) { DspUdsSecurityAccess(dspUdsSecurityAccessPending.pduRxData, dspUdsSecurityAccessPending.pduTxData); } } #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) /** * Main function for IO control */ void DspIOControlMainFunction(void) { if( DCM_GENERAL_PENDING == IOControlData.state ) { DspIOControlByDataIdentifier(IOControlData.pduRxData, IOControlData.pduTxData); } } /** * Function for canceling a pending IOControl * @param pduRxData * @param pduTxData */ static void DspCancelPendingIOControlByDataIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData ) { Dcm_NegativeResponseCodeType responseCode; const Dcm_DspDidType *didPtr = NULL_PTR; uint16 didNr = (pduRxData->SduDataPtr[IOI_INDEX] << 8 & DCM_DID_HIGH_MASK) + (pduRxData->SduDataPtr[IOI_INDEX+1] & DCM_DID_LOW_MASK); if( lookupNonDynamicDid(didNr, &didPtr) ) { /* First of all return control to ECU on the ones already a activated */ DspIOControlStopActivated(didNr, IOControlData.signalAffected); /* And cancel the pending one. */ if( IOControlData.pendingSignalIndex < didPtr->DspNofSignals ) { const Dcm_DspDataType *dataPtr = didPtr->DspSignalRef[IOControlData.pendingSignalIndex].DspSignalDataRef; if( DCM_GENERAL_PENDING == IOControlData.state ) { if( TRUE == IOControlData.pendingControl ) { /* Pending control */ if ( dataPtr->DspDataUsePort == DATA_PORT_ASYNCH) { (void)FunctionInputOutputControl(dataPtr, pduRxData->SduDataPtr[IOCP_INDEX], DCM_CANCEL, NULL_PTR, &responseCode); } } else { /* It is a pending read. */ if( dataPtr->DspDataReadDataFnc.AsynchDataReadFnc != NULL_PTR ) { if( DATA_PORT_ASYNCH == dataPtr->DspDataUsePort ) { (void)dataPtr->DspDataReadDataFnc.AsynchDataReadFnc(DCM_CANCEL, NULL_PTR); } } } } else { /* Not in a pending state */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } else { /* Invalid signal index */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } } #endif #ifdef DCM_USE_UPLOAD_DOWNLOAD /** * Cancels pending upload/download service * @param SID */ static void DspCancelPendingUploadDownload(uint8 SID) { Dcm_NegativeResponseCodeType respCode; uint32 blockSize; switch(SID) { case SID_REQUEST_DOWNLOAD: (void)Dcm_ProcessRequestDownload(DCM_CANCEL, 0, 0, 0, &blockSize, &respCode); break; case SID_REQUEST_UPLOAD: (void)Dcm_ProcessRequestUpload(DCM_CANCEL, 0, 0, 0, &respCode); break; case SID_TRANSFER_DATA: if (DCM_DOWNLOAD == TransferStatus.transferType) { (void)Dcm_WriteMemory(DCM_CANCEL, 0, 0, 0, 0); } if (DCM_UPLOAD == TransferStatus.transferType) { (void)Dcm_ReadMemory(DCM_CANCEL, 0, 0, 0, 0); } break; case SID_REQUEST_TRANSFER_EXIT: (void)Dcm_ProcessRequestTransferExit(DCM_CANCEL, 0, 0, &respCode); break; default: break; } } /** * Runs pending upload/download service * @param SID * @param pduRxData * @param pduTxData */ static void DspUploadDownload(uint8 SID, const PduInfoType *pduRxData, PduInfoType *pduTxData) { switch(SID) { #if defined(DCM_USE_SERVICE_REQUESTDOWNLOAD) case SID_REQUEST_DOWNLOAD: DspUdsRequestDownload(pduRxData, pduTxData); break; #endif #if defined(DCM_USE_SERVICE_REQUESTUPLOAD) case SID_REQUEST_UPLOAD: DspUdsRequestUpload(pduRxData, pduTxData); break; #endif #if defined(DCM_USE_SERVICE_TRANSFERDATA) case SID_TRANSFER_DATA: DspUdsTransferData(pduRxData, pduTxData); break; #endif #if defined(DCM_USE_SERVICE_REQUESTTRANSFEREXIT) case SID_REQUEST_TRANSFER_EXIT: DspUdsRequestTransferExit(pduRxData, pduTxData); break; #endif default: break; } } /** * Main function for pending upload/download services */ void DspUploadDownloadMainFunction(void) { if( DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND == dspUdsUploadDownloadPending.state) { /* !req DCM528 */ /* !req DCM529 Should wait until transmit has been confirmed */ dspUdsUploadDownloadPending.state = DCM_GENERAL_FORCE_RCRRP; // Do not try again until next main loop } else if( (DCM_GENERAL_PENDING == dspUdsUploadDownloadPending.state) || (DCM_GENERAL_FORCE_RCRRP == dspUdsUploadDownloadPending.state)) { DspUploadDownload(dspUdsUploadDownloadPending.pendingService, dspUdsUploadDownloadPending.pduRxData, dspUdsUploadDownloadPending.pduTxData); } } #endif #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) /** * Main function for jump to boot */ void DspJumpToBootMainFunction(void) { if( (DCM_JTB_RESAPP_ASSEMBLE_FINAL_RESPONSE == dspUdsSessionControlData.jumpToBootState) || ( DCM_JTB_EXECUTE == dspUdsSessionControlData.jumpToBootState )) { DspUdsDiagnosticSessionControl(dspUdsSessionControlData.pduRxData, dspUdsSessionControlData.sessionPduId,dspUdsSessionControlData.pduTxData, FALSE, FALSE); } #if defined(DCM_USE_SERVICE_LINKCONTROL) if(DCM_JTB_EXECUTE == dspUdsLinkControlData.jumpToBootState) { DspUdsLinkControl(dspUdsLinkControlData.pduRxData, dspUdsLinkControlData.confirmPduId, dspUdsLinkControlData.pduTxData, FALSE); } #endif } #endif /** * Main function for sending response to service as a result to jump from boot */ void DspStartupServiceResponseMainFunction(void) { if(DCM_GENERAL_PENDING == ProgConditionStartupResponseState) { Std_ReturnType reqRet = DslDspResponseOnStartupRequest(GlobalProgConditions.Sid, GlobalProgConditions.SubFncId, GlobalProgConditions.ProtocolId, (uint16)GlobalProgConditions.TesterSourceAdd); if(E_PENDING != reqRet) { if(E_OK != reqRet) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } ProgConditionStartupResponseState = DCM_GENERAL_IDLE; } } } void DspPreDsdMain(void) { /* Should be called before DsdMain so that an internal request * may be processed directly */ #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) DspPeriodicDIDMainFunction(); #endif #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && (DCM_ROE_INTERNAL_DIDS == STD_ON) DCM_ROE_PollDataIdentifiers(); #endif /* Should be done before DsdMain so that we can fulfill * DCM719 (mode switch DcmEcuReset to EXECUTE next main function) */ #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) DspJumpToBootMainFunction(); #endif DspStartupServiceResponseMainFunction(); } void DspMain(void) { #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) DsdSetDspProcessingActive(TRUE); #endif DspResetMainFunction(); #if defined(DCM_USE_SERVICE_READMEMORYBYADDRESS) || defined(DCM_USE_SERVICE_WRITEMEMORYBYADDRESS) DspMemoryMainFunction(); #endif DspReadDidMainFunction(); DspRoutineControlMainFunction(); #ifdef DCM_USE_UPLOAD_DOWNLOAD DspUploadDownloadMainFunction(); #endif DspSecurityAccessMainFunction(); #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) DspIOControlMainFunction(); #endif #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) DsdSetDspProcessingActive(FALSE); #endif } void DspTimerMain(void) { #if (DCM_SECURITY_EOL_INDEX != 0) for (uint8 i = 0; i < DCM_SECURITY_EOL_INDEX; i++) { //Check if a wait is required before accepting a request switch (dspUdsSecurityAccesData.secFalseAttemptChk[i].startDelayTimer) { case DELAY_TIMER_ON_BOOT_ACTIVE: case DELAY_TIMER_ON_EXCEEDING_LIMIT_ACTIVE: TIMER_DECREMENT(dspUdsSecurityAccesData.secFalseAttemptChk[i].timerSecAcssAttempt); if (dspUdsSecurityAccesData.secFalseAttemptChk[i].timerSecAcssAttempt < DCM_MAIN_FUNCTION_PERIOD_TIME_MS) { dspUdsSecurityAccesData.secFalseAttemptChk[i].startDelayTimer = DELAY_TIMER_DEACTIVE; } break; case DELAY_TIMER_DEACTIVE: default: break; } } #endif } void DspCancelPendingRequests(void) { if( DCM_READ_DID_IDLE != dspUdsReadDidPending.state ) { /* DidRead was in pending state, cancel it */ DspCancelPendingDid(dspUdsReadDidPending.pendingDid, dspUdsReadDidPending.pendingSignalIndex ,dspUdsReadDidPending.state, dspUdsReadDidPending.pduTxData); } dspMemoryState = DCM_MEMORY_UNUSED; dspUdsEcuResetData.resetPending = DCM_DSP_RESET_NO_RESET; dspUdsReadDidPending.state = DCM_READ_DID_IDLE; #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER dspUdsWriteDidPending.state = DCM_GENERAL_IDLE; #endif if( DCM_GENERAL_IDLE != dspUdsRoutineControlPending.state ) { DspCancelPendingRoutine(dspUdsRoutineControlPending.pduRxData, dspUdsRoutineControlPending.pduTxData); } dspUdsRoutineControlPending.state = DCM_GENERAL_IDLE; if( DCM_GENERAL_IDLE != dspUdsSecurityAccessPending.state ) { DspCancelPendingSecurityAccess(dspUdsSecurityAccessPending.pduRxData, dspUdsSecurityAccessPending.pduTxData); } dspUdsSecurityAccessPending.state = DCM_GENERAL_IDLE; #if defined(DCM_USE_UPLOAD_DOWNLOAD) if( DCM_GENERAL_IDLE != dspUdsUploadDownloadPending.state ) { DspCancelPendingUploadDownload(dspUdsUploadDownloadPending.pendingService); } dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; #endif #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) if( DCM_GENERAL_PENDING == IOControlData.state ) { DspCancelPendingIOControlByDataIdentifier(IOControlData.pduRxData, IOControlData.pduTxData); } IOControlData.state = DCM_GENERAL_IDLE; #endif #if (DCM_USE_JUMP_TO_BOOT == STD_ON) dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; #endif #if defined(DCM_USE_SERVICE_LINKCONTROL) dspUdsLinkControlData.jumpToBootState = DCM_JTB_IDLE; #endif } boolean DspCheckSessionLevel(Dcm_DspSessionRowType const* const* sessionLevelRefTable) { Std_ReturnType returnStatus; boolean levelFound = FALSE; Dcm_SesCtrlType currentSession; returnStatus = DslGetSesCtrlType(&currentSession); if (returnStatus == E_OK) { if( (*sessionLevelRefTable)->Arc_EOL ) { /* No session reference configured, no check should be done. */ levelFound = TRUE; } else { while ( ((*sessionLevelRefTable)->DspSessionLevel != DCM_ALL_SESSION_LEVEL) && ((*sessionLevelRefTable)->DspSessionLevel != currentSession) && (!(*sessionLevelRefTable)->Arc_EOL) ) { sessionLevelRefTable++; } if (!(*sessionLevelRefTable)->Arc_EOL) { levelFound = TRUE; } } } return levelFound; } boolean DspCheckSecurityLevel(Dcm_DspSecurityRowType const* const* securityLevelRefTable) { Std_ReturnType returnStatus; boolean levelFound = FALSE; Dcm_SecLevelType currentSecurityLevel; returnStatus = DslGetSecurityLevel(&currentSecurityLevel); if (returnStatus == E_OK) { if( (*securityLevelRefTable)->Arc_EOL ) { /* No security level reference configured, no check should be done. */ levelFound = TRUE; } else { while ( ((*securityLevelRefTable)->DspSecurityLevel != currentSecurityLevel) && (!(*securityLevelRefTable)->Arc_EOL) ) { securityLevelRefTable++; } if (!(*securityLevelRefTable)->Arc_EOL) { levelFound = TRUE; } } } return levelFound; } /** * Checks if a session is supported * @param session * @return TRUE: Session supported, FALSE: Session not supported */ boolean DspDslCheckSessionSupported(uint8 session) { const Dcm_DspSessionRowType *sessionRow = Dcm_ConfigPtr->Dsp->DspSession->DspSessionRow; while ((sessionRow->DspSessionLevel != session) && (!sessionRow->Arc_EOL) ) { sessionRow++; } return (FALSE == sessionRow->Arc_EOL)? TRUE: FALSE; } /** * Sets the timing parameter inresponse to UDS service 0x10 * @param SessionData * @param timingData * @return Length of timing parameters */ static uint8 DspSetSessionControlTiming(const DspUdsSessionControlDataType * SessionData, uint8 *timingData) { uint8 timingLen = 0u; if( DCM_UDS_ON_CAN == SessionData->protocolId ) { timingData[0u] = SessionData->P2 >> 8u; timingData[1u] = SessionData->P2; uint16 p2ServerStarMax10ms = SessionData->P2Star / 10u; timingData[2u] = p2ServerStarMax10ms >> 8u; timingData[3u] = p2ServerStarMax10ms; timingLen = 4u; } return timingLen; } void DspUdsDiagnosticSessionControl(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean respPendOnTransToBoot, boolean internalStartupRequest) { /* @req DCM250 */ const Dcm_DspSessionRowType *sessionRow = Dcm_ConfigPtr->Dsp->DspSession->DspSessionRow; Dcm_SesCtrlType reqSessionType; Std_ReturnType result = E_OK; Dcm_ProtocolType activeProtocolID; uint8 timingParamLen; if( DCM_JTB_IDLE == dspUdsSessionControlData.jumpToBootState ) { #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && (DCM_ROE_INIT_ON_DSC == STD_ON) /* Stop the response on event service */ /* @req DCM597 */ if (DCM_ROE_IsActive()) { (void)Dcm_StopROE(); } #endif if (pduRxData->SduLength == 2) { reqSessionType = pduRxData->SduDataPtr[1]; // Check if type exist in session table while ((sessionRow->DspSessionLevel != reqSessionType) && (!sessionRow->Arc_EOL) ) { sessionRow++; } if (!sessionRow->Arc_EOL) { #if (DCM_USE_JUMP_TO_BOOT == STD_ON) if(!internalStartupRequest) { switch(sessionRow->DspSessionForBoot) { case DCM_OEM_BOOT: case DCM_OEM_BOOT_RESPAPP: /* @req DCM532 */ result = Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_JUMPTOBOOTLOADER); break; case DCM_SYS_BOOT: case DCM_SYS_BOOT_RESPAPP: /* @req DCM592 */ result = Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_JUMPTOSYSSUPPLIERBOOTLOADER); break; case DCM_NO_BOOT: result = E_OK; break; default: result = E_NOT_OK; break; } } #endif if (result == E_OK) { dspUdsSessionControlData.session = reqSessionType; dspUdsSessionControlData.sessionPduId = txPduId; dspUdsSessionControlData.pduRxData = pduRxData; dspUdsSessionControlData.pduTxData = pduTxData; dspUdsSessionControlData.P2 = sessionRow->DspSessionP2ServerMax; dspUdsSessionControlData.P2Star = sessionRow->DspSessionP2StarServerMax; Std_ReturnType activeProtocolStatus = DslGetActiveProtocol(&activeProtocolID); if( E_OK == activeProtocolStatus ) { dspUdsSessionControlData.protocolId = activeProtocolID; } else { dspUdsSessionControlData.protocolId = 0xFF; } if( (DCM_NO_BOOT == sessionRow->DspSessionForBoot) || internalStartupRequest) { dspUdsSessionControlData.pendingSessionChange = TRUE; pduTxData->SduDataPtr[1] = reqSessionType; timingParamLen = DspSetSessionControlTiming(&dspUdsSessionControlData, &pduTxData->SduDataPtr[2]); pduTxData->SduLength = 2u + timingParamLen; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } else { #if (DCM_USE_JUMP_TO_BOOT == STD_ON) GlobalProgConditions.ReprogramingRequest = (DCM_PROGRAMMING_SESSION == reqSessionType); GlobalProgConditions.ResponseRequired = DsdDspGetResponseRequired(); GlobalProgConditions.Sid = SID_DIAGNOSTIC_SESSION_CONTROL; GlobalProgConditions.SubFncId = reqSessionType; if( E_OK == activeProtocolStatus ) { GlobalProgConditions.ProtocolId = activeProtocolID; } uint16 srcAddr = DsdDspGetTesterSourceAddress(); GlobalProgConditions.TesterSourceAdd = (uint8)(srcAddr & 0xFF); if( respPendOnTransToBoot ) { /* @req 4.2.2/SWS_DCM_01177 */ if((sessionRow->DspSessionForBoot == DCM_OEM_BOOT_RESPAPP) || (sessionRow->DspSessionForBoot == DCM_SYS_BOOT_RESPAPP)){ dspUdsSessionControlData.jumpToBootState = DCM_JTB_RESAPP_WAIT_RESPONSE_PENDING_TX_CONFIRM; }else { dspUdsSessionControlData.jumpToBootState = DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM; } /* Force response pending next main function and * wait for tx confirmation*/ /* @req DCM654 */ DsdDspForceResponsePending(); } else { /* Trigger mode switch next main function */ /* @req DCM719 */ /* @req DCM720 */ /* IMPROVEMENT: Add support for pending */ if((sessionRow->DspSessionForBoot == DCM_OEM_BOOT) || (sessionRow->DspSessionForBoot == DCM_SYS_BOOT)){ if(E_OK == Dcm_SetProgConditions(&GlobalProgConditions)) { dspUdsSessionControlData.jumpToBootState = DCM_JTB_EXECUTE; } else { /* @req DCM715 */ DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } } /* @req 4.2.2/SWS_DCM_01178 */ else if((sessionRow->DspSessionForBoot == DCM_OEM_BOOT_RESPAPP) || (sessionRow->DspSessionForBoot == DCM_SYS_BOOT_RESPAPP)){ dspUdsSessionControlData.jumpToBootState = DCM_JTB_RESAPP_FINAL_RESPONSE_TX_CONFIRM; pduTxData->SduDataPtr[1] = reqSessionType; timingParamLen = DspSetSessionControlTiming(&dspUdsSessionControlData, &pduTxData->SduDataPtr[2]); pduTxData->SduLength = 2u + timingParamLen; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } else { /* Avoid compiler message */ } } if( (E_OK != activeProtocolStatus) || (0 != (srcAddr & (uint16)~0xFF)) ) { /* Failed to get the protocol id or the source address was too large */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } #else DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); #endif } } else { // IMPROVEMENT: Add handling of special case of E_FORCE_RCRRP DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } } else { DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); /* @req DCM307 */ } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #if (DCM_USE_JUMP_TO_BOOT == STD_ON) else if(DCM_JTB_EXECUTE == dspUdsSessionControlData.jumpToBootState) { if(E_OK != Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE)) { DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; } else if(DCM_JTB_RESAPP_ASSEMBLE_FINAL_RESPONSE == dspUdsSessionControlData.jumpToBootState) { dspUdsSessionControlData.jumpToBootState = DCM_JTB_RESAPP_FINAL_RESPONSE_TX_CONFIRM; pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; timingParamLen = DspSetSessionControlTiming(&dspUdsSessionControlData, &pduTxData->SduDataPtr[2]); pduTxData->SduLength = 2u + timingParamLen; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } #else (void)respPendOnTransToBoot; #endif } #if defined(DCM_USE_SERVICE_LINKCONTROL) /** * @brief Service 0x87 (Linkcontrol) processing. * * @note This service is only used for jumping to bootloader. For changing baudrate external service processing has to be used. * * @param[in] pdRxData Received PDU data. * @param[in] txPduId Id of the PDU TX. * @param[out] pduTxData PDU data to be transmitted. * @param[in] respPendOnTransToBoot Control flag to send NRC 0x78 when configured in session row. */ void DspUdsLinkControl(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean respPendOnTransToBoot) { /* @req DCM743 */ Std_ReturnType result = E_NOT_OK; Dcm_ProtocolType activeProtocolID; Std_ReturnType activeProtocolStatus; if( DCM_JTB_IDLE == dspUdsLinkControlData.jumpToBootState ) { if (pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_FIXED_BAUDRATE || pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_SPECIFIC_BAUDRATE || pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_TRANSITION_BAUDRATE) { if ( (pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_FIXED_BAUDRATE && pduRxData->SduLength == 3) || (pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_VERIFY_BAUDRATE_TRANS_WITH_SPECIFIC_BAUDRATE && pduRxData->SduLength == 5) || (pduRxData->SduDataPtr[1] == LINKCONTROL_SUBFUNC_TRANSITION_BAUDRATE && pduRxData->SduLength == 2) ) { /* @req DCM533 */ /* @req DCM744 */ result = Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_JUMPTOBOOTLOADER); if (result == E_OK) { dspUdsLinkControlData.confirmPduId = txPduId; dspUdsLinkControlData.pduRxData = pduRxData; dspUdsLinkControlData.pduTxData = pduTxData; GlobalProgConditions.ReprogramingRequest = FALSE; GlobalProgConditions.ResponseRequired = DsdDspGetResponseRequired(); GlobalProgConditions.Sid = SID_LINK_CONTROL; GlobalProgConditions.SubFncId = pduRxData->SduDataPtr[1]; activeProtocolStatus = DslGetActiveProtocol(&activeProtocolID); if( E_OK == activeProtocolStatus ) { GlobalProgConditions.ProtocolId = activeProtocolID; } GlobalProgConditions.TesterSourceAdd = (uint8)(DsdDspGetTesterSourceAddress() & 0xFF); if( respPendOnTransToBoot ) { dspUdsLinkControlData.jumpToBootState = DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM; /* Force response pending next main function and * wait for tx confirmation*/ /* @req DCM654 */ DsdDspForceResponsePending(); } else { /* Trigger mode switch next main function */ /* @req DCM719 */ /* @req DCM720 */ if(E_OK == Dcm_SetProgConditions(&GlobalProgConditions)) { dspUdsLinkControlData.jumpToBootState = DCM_JTB_EXECUTE; } else { /* @req DCM715 */ DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } } } else { DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } } else { /* Wrong length */ DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } else { /* Subfunction not supported */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); } } else if(DCM_JTB_EXECUTE == dspUdsLinkControlData.jumpToBootState) { if(E_OK != Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE)) { DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } dspUdsLinkControlData.jumpToBootState = DCM_JTB_IDLE; } } #endif void DspUdsEcuReset(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean startupResponseRequest) { /* @req DCM260 */ Dcm_EcuResetType reqResetType; uint8 rteMode; if (pduRxData->SduLength == 2) { reqResetType = (Dcm_EcuResetType)pduRxData->SduDataPtr[1]; Std_ReturnType result = E_NOT_OK; /* @req DCM373 */ /* IMPROVEMENT: Should be a call to SchM */ if( FALSE == startupResponseRequest ) { if( (DCM_DISABLE_RAPID_POWER_SHUTDOWN != reqResetType) && (DCM_ENABLE_RAPID_POWER_SHUTDOWN != reqResetType) ) { if( E_OK == getResetRteMode(reqResetType, &rteMode) ) { result = Rte_Switch_DcmEcuReset_DcmEcuReset(rteMode); dspUdsEcuResetData.resetPduId = txPduId; dspUdsEcuResetData.pduTxData = pduTxData; dspUdsEcuResetData.resetType = reqResetType; switch( result ) { case E_OK: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_WAIT_TX_CONF; // Create positive response pduTxData->SduDataPtr[1] = reqResetType; pduTxData->SduLength = 2; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); break; case E_PENDING: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_PENDING; break; case E_NOT_OK: default: dspUdsEcuResetData.resetPending = DCM_DSP_RESET_NO_RESET; DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); break; } } else { /* Not supported */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); } } else { /* Not supported */ /* IMPROVEMENT: Add support for rapid power shutdown */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); } } else { /* Response to jump from boot. Create positive response */ pduTxData->SduDataPtr[1] = reqResetType; pduTxData->SduLength = 2; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CLEARDIAGNOSTICINFORMATION) void DspUdsClearDiagnosticInformation(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM247 */ uint32 dtc; Dem_ReturnClearDTCType result; if (pduRxData->SduLength == 4) { dtc = BYTES_TO_DTC(pduRxData->SduDataPtr[1], pduRxData->SduDataPtr[2], pduRxData->SduDataPtr[3]); result = Dem_ClearDTC(dtc, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY); /* @req DCM005 */ switch (result) { case DEM_CLEAR_OK: /* Create positive response */ /* @req DCM705 */ pduTxData->SduLength = 1; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); break; case DEM_CLEAR_FAILED: DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT);/* @req DCM707 */ break; default: /* @req DCM708 */ /* !req DCM706 */ DsdDspProcessingDone(DCM_E_REQUESTOUTOFRANGE); break; } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_READDTCINFORMATION) static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x01_0x07_0x11_0x12(const PduInfoType *pduRxData, PduInfoType *pduTxData) { typedef struct { uint8 SID; uint8 reportType; uint8 dtcStatusAvailabilityMask; uint8 dtcFormatIdentifier; uint8 dtcCountHighByte; uint8 dtcCountLowByte; } TxDataType; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dem_ReturnSetFilterType setDtcFilterResult; uint16 numberOfFilteredDtc = 0; /* @req DCM700 */ uint8 dtcStatusMask = pduRxData->SduDataPtr[1] == 0x07 ? pduRxData->SduDataPtr[3] : pduRxData->SduDataPtr[2]; if (dtcStatusMask != 0x00) { // Setup the DTC filter switch (pduRxData->SduDataPtr[1]) { /* @req DCM293 */ case 0x01: // reportNumberOfDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(dtcStatusMask, DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x07: // reportNumberOfDTCBySeverityMaskRecord setDtcFilterResult = Dem_SetDTCFilter(dtcStatusMask, DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_YES, pduRxData->SduDataPtr[2], DEM_FILTER_FOR_FDC_NO); break; case 0x11: // reportNumberOfMirrorMemoryDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(dtcStatusMask, DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_MIRROR_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x12: // reportNumberOfEmissionRelatedOBDDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(dtcStatusMask, DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; default: setDtcFilterResult = DEM_WRONG_FILTER; break; } if (setDtcFilterResult == DEM_FILTER_ACCEPTED) { Dem_ReturnGetNumberOfFilteredDTCType getNumerResult; /* @req DCM376 */ getNumerResult = Dem_GetNumberOfFilteredDtc(&numberOfFilteredDtc); if (getNumerResult != DEM_NUMBER_OK) { responseCode = DCM_E_GENERALREJECT; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } if (responseCode == DCM_E_POSITIVERESPONSE) { uint8 dtcAvailablityMask; Std_ReturnType result; TxDataType *txData = (TxDataType*)pduTxData->SduDataPtr; result = Dem_GetDTCStatusAvailabilityMask(&dtcAvailablityMask); if (result != E_OK) { dtcAvailablityMask = 0; } // Create positive response (ISO 14229-1 table 251) txData->reportType = pduRxData->SduDataPtr[1]; // reportType txData->dtcStatusAvailabilityMask = dtcAvailablityMask; // DTCStatusAvailabilityMask txData->dtcFormatIdentifier = Dem_GetTranslationType(); // DTCFormatIdentifier txData->dtcCountHighByte = (numberOfFilteredDtc >> 8); // DTCCount high byte txData->dtcCountLowByte = (numberOfFilteredDtc & 0xFFu); // DTCCount low byte pduTxData->SduLength = 6; } return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x02_0x0A_0x0F_0x13_0x15(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dem_ReturnSetFilterType setDtcFilterResult; uint16 nofFilteredDTCs = 0; if ((pduRxData->SduDataPtr[1] != 0x0A) && (pduRxData->SduDataPtr[1] != 0x15) && (pduRxData->SduDataPtr[2] == 0x00)) { uint16 currIndex = 1; uint8 dtcStatusMask; /* @req DCM377 */ if (Dem_GetDTCStatusAvailabilityMask(&dtcStatusMask) != E_OK) { dtcStatusMask = 0; } // Create positive response (ISO 14229-1 table 252) pduTxData->SduDataPtr[currIndex++] = pduRxData->SduDataPtr[1]; pduTxData->SduDataPtr[currIndex++] = dtcStatusMask; pduTxData->SduLength = currIndex; } else { // Setup the DTC filter /* @req DCM378 */ switch (pduRxData->SduDataPtr[1]) { case 0x02: // reportDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(pduRxData->SduDataPtr[2], DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x0A: // reportSupportedDTC setDtcFilterResult = Dem_SetDTCFilter(DEM_DTC_STATUS_MASK_ALL, DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x0F: // reportMirrorMemoryDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(pduRxData->SduDataPtr[2], DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_MIRROR_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x13: // reportEmissionRelatedOBDDTCByStatusMask setDtcFilterResult = Dem_SetDTCFilter(pduRxData->SduDataPtr[2], DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; case 0x15: // reportDTCWithPermanentStatus setDtcFilterResult = Dem_SetDTCFilter(DEM_DTC_STATUS_MASK_ALL, DEM_DTC_KIND_ALL_DTCS, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PERMANENT_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); break; default: setDtcFilterResult = DEM_WRONG_FILTER; break; } if (setDtcFilterResult == DEM_FILTER_ACCEPTED) { uint8 dtcStatusMask; Dem_ReturnGetNextFilteredDTCType getNextFilteredDtcResult; uint32 dtc; Dem_EventStatusExtendedType dtcStatus; Std_ReturnType result; uint16 currIndex = 1; /* @req DCM377 */ result = Dem_GetDTCStatusAvailabilityMask(&dtcStatusMask); if (result != E_OK) { dtcStatusMask = 0; } // Create positive response (ISO 14229-1 table 252) pduTxData->SduDataPtr[currIndex++] = pduRxData->SduDataPtr[1]; pduTxData->SduDataPtr[currIndex++] = dtcStatusMask; if (dtcStatusMask != 0x00u) { /* @req DCM008 */ if( DEM_NUMBER_OK == Dem_GetNumberOfFilteredDtc(&nofFilteredDTCs) ) { if( ((nofFilteredDTCs * 4u) + currIndex) <= pduTxData->SduLength ) { getNextFilteredDtcResult = Dem_GetNextFilteredDTC(&dtc, &dtcStatus); while (getNextFilteredDtcResult == DEM_FILTERED_OK) { pduTxData->SduDataPtr[currIndex++] = DTC_HIGH_BYTE(dtc); pduTxData->SduDataPtr[currIndex++] = DTC_MID_BYTE(dtc); pduTxData->SduDataPtr[currIndex++] = DTC_LOW_BYTE(dtc); pduTxData->SduDataPtr[currIndex++] = dtcStatus; getNextFilteredDtcResult = Dem_GetNextFilteredDTC(&dtc, &dtcStatus); } if (getNextFilteredDtcResult != DEM_FILTERED_NO_MATCHING_DTC) { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /* Tx buffer too small */ responseCode = DCM_E_RESPONSETOOLONG; } } else { /* Could not read number of filtered DTCs */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } pduTxData->SduLength = currIndex; } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x08(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; (void)pduTxData; //lint +estring(920,pointer) /* cast to void */ // IMPROVEMENT: Not supported yet, (DEM module does not currently support severity). responseCode = DCM_E_REQUESTOUTOFRANGE; return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x09(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; (void)pduTxData; //lint +estring(920,pointer) /* cast to void */ // IMPROVEMENT: Not supported yet, (DEM module does not currently support severity). responseCode = DCM_E_REQUESTOUTOFRANGE; return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x06_0x10(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dem_DTCOriginType dtcOrigin; uint8 startRecNum; uint8 endRecNum; // Switch on sub function switch (pduRxData->SduDataPtr[1]) { /* @req DCM378 */ case 0x06: // reportDTCExtendedDataRecordByDTCNumber dtcOrigin = DEM_DTC_ORIGIN_PRIMARY_MEMORY; break; case 0x10: // reportMirrorMemoryDTCExtendedDataRecordByDTCNumber dtcOrigin = DEM_DTC_ORIGIN_MIRROR_MEMORY; break; default: responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; dtcOrigin = 0; break; } // Switch on record number switch (pduRxData->SduDataPtr[5]) { case 0xFF: // Report all Extended Data Records for a particular DTC startRecNum = 0x00; endRecNum = 0xEF; break; case 0xFE: // Report all OBD Extended Data Records for a particular DTC startRecNum = 0x90; endRecNum = 0xEF; break; default: // Report one specific Extended Data Records for a particular DTC startRecNum = pduRxData->SduDataPtr[5]; endRecNum = startRecNum; break; } if (responseCode == DCM_E_POSITIVERESPONSE) { Dem_EventStatusExtendedType statusOfDtc; uint32 dtc = BYTES_TO_DTC(pduRxData->SduDataPtr[2], pduRxData->SduDataPtr[3], pduRxData->SduDataPtr[4]); /* @req DCM295 */ /* @req DCM475 */ if (DEM_STATUS_OK == Dem_GetStatusOfDTC(dtc, dtcOrigin, &statusOfDtc)) { Dem_ReturnGetExtendedDataRecordByDTCType getExtendedDataRecordByDtcResult; uint16 recLength; uint16 txIndex = 6; boolean foundValidRecordNumber = FALSE; /* @req DCM297 */ /* @req DCM474 */ /* @req DCM386 */ pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; // Sub function pduTxData->SduDataPtr[2] = DTC_HIGH_BYTE(dtc); // DTC high byte pduTxData->SduDataPtr[3] = DTC_MID_BYTE(dtc); // DTC mid byte pduTxData->SduDataPtr[4] = DTC_LOW_BYTE(dtc); // DTC low byte pduTxData->SduDataPtr[5] = statusOfDtc; // DTC status for (uint8 recNum = startRecNum; (recNum <= endRecNum) && (DCM_E_POSITIVERESPONSE == responseCode); recNum++) { // Calculate what's left in buffer recLength = (pduTxData->SduLength > (txIndex + 1)) ? (pduTxData->SduLength - (txIndex + 1)) : 0u; /* @req DCM296 */ /* @req DCM476 */ /* @req DCM382 */ /* !req DCM371 */ getExtendedDataRecordByDtcResult = Dem_GetExtendedDataRecordByDTC(dtc, dtcOrigin, recNum, &pduTxData->SduDataPtr[txIndex+1], &recLength); switch(getExtendedDataRecordByDtcResult) { case DEM_RECORD_OK: foundValidRecordNumber = TRUE; if (recLength > 0) { pduTxData->SduDataPtr[txIndex++] = recNum; /* Instead of calling Dem_GetSizeOfExtendedDataRecordByDTC() the result from Dem_GetExtendedDataRecordByDTC() is used */ /* !req DCM478 */ txIndex += recLength; } break; case DEM_RECORD_BUFFERSIZE: /* Tx buffer not big enough */ responseCode = DCM_E_RESPONSETOOLONG; break; default: break; } } pduTxData->SduLength = txIndex; if (!foundValidRecordNumber) { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /* !req DCM739 */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x03(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint16 numFilteredRecords = 0; uint32 dtc = 0; uint8 recordNumber = 0; uint16 nofBytesCopied = 0; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; //lint +estring(920,pointer) /* cast to void */ /* @req DCM298 */ if( DEM_FILTER_ACCEPTED == Dem_SetFreezeFrameRecordFilter(DEM_DTC_FORMAT_UDS, &numFilteredRecords) ) { if ( (SID_LEN + SF_LEN + (DTC_LEN + FF_REC_NUM_LEN)*numFilteredRecords) <= pduTxData->SduLength ) { for( uint16 i = 0; (i < numFilteredRecords) && (DCM_E_POSITIVERESPONSE == responseCode); i++ ) { /* @req DCM299 */ if( DEM_FILTERED_OK == Dem_GetNextFilteredRecord(&dtc, &recordNumber) ) { /* @req DCM300 */ pduTxData->SduDataPtr[SID_LEN + SF_LEN + nofBytesCopied++] = DTC_HIGH_BYTE(dtc); pduTxData->SduDataPtr[SID_LEN + SF_LEN + nofBytesCopied++] = DTC_MID_BYTE(dtc); pduTxData->SduDataPtr[SID_LEN + SF_LEN + nofBytesCopied++] = DTC_LOW_BYTE(dtc); pduTxData->SduDataPtr[SID_LEN + SF_LEN + nofBytesCopied++] = recordNumber; } else { /* !req DCM740 */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } } else { responseCode = DCM_E_RESPONSETOOLONG; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } pduTxData->SduDataPtr[0] = 0x59; // positive response pduTxData->SduDataPtr[1] = 0x03; // subid pduTxData->SduLength = SID_LEN + SF_LEN + nofBytesCopied; return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x04(const PduInfoType *pduRxData, PduInfoType *pduTxData) { // 1. Only consider Negative Response 0x10 /* @req DCM302 */ /* @req DCM387 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint32 DtcNumber = 0; uint8 RecordNumber = 0; uint16 SizeOfTxBuf = pduTxData->SduLength; Dem_ReturnGetFreezeFrameDataByDTCType GetFFbyDtcReturnCode = DEM_GET_FFDATABYDTC_OK; Dem_ReturnGetStatusOfDTCType GetStatusOfDtc = DEM_STATUS_OK; Dem_EventStatusExtendedType DtcStatus = 0; // Now let's assume DTC has 3 bytes. DtcNumber = (((uint32)pduRxData->SduDataPtr[2])<<16) + (((uint32)pduRxData->SduDataPtr[3])<<8) + ((uint32)pduRxData->SduDataPtr[4]); GetStatusOfDtc = Dem_GetStatusOfDTC(DtcNumber, DEM_DTC_ORIGIN_PRIMARY_MEMORY, &DtcStatus); /* @req DCM383 */ switch (GetStatusOfDtc) { case DEM_STATUS_OK: break; default: /* !req DCM739 */ return DCM_E_REQUESTOUTOFRANGE; } RecordNumber = pduRxData->SduDataPtr[5]; /* !req DCM372 */ /* !req DCM702 */ if( 0xFF == RecordNumber ) { /* Request for all freeze frames */ GetFFbyDtcReturnCode = DEM_GET_FFDATABYDTC_WRONG_DTC; uint16 nofBytesCopied = 0; uint16 bufSizeLeft = 0; Dem_ReturnGetFreezeFrameDataByDTCType ret = DEM_GET_FFDATABYDTC_OK; for(uint8 record = 0; (record < RecordNumber) && (DEM_GET_FFDATABYDTC_BUFFERSIZE != GetFFbyDtcReturnCode); record++) { /* @req DCM385 */ bufSizeLeft = pduTxData->SduLength - 6 - nofBytesCopied; ret = Dem_GetFreezeFrameDataByDTC(DtcNumber, DEM_DTC_ORIGIN_PRIMARY_MEMORY, record, &pduTxData->SduDataPtr[6 + nofBytesCopied], &bufSizeLeft); switch(ret) { case DEM_GET_FFDATABYDTC_OK: nofBytesCopied += bufSizeLeft;/* !req DCM441 */ /* At least one OK! */ GetFFbyDtcReturnCode = DEM_GET_FFDATABYDTC_OK; break; case DEM_GET_FFDATABYDTC_BUFFERSIZE: /* Tx buffer not big enough */ GetFFbyDtcReturnCode = DEM_GET_FFDATABYDTC_BUFFERSIZE; break; default: break; } } SizeOfTxBuf = nofBytesCopied; } else { GetFFbyDtcReturnCode = Dem_GetFreezeFrameDataByDTC(DtcNumber, DEM_DTC_ORIGIN_PRIMARY_MEMORY, RecordNumber, &pduTxData->SduDataPtr[6], &SizeOfTxBuf);/* @req DCM384 */ } // Negative response switch (GetFFbyDtcReturnCode) { case DEM_GET_FFDATABYDTC_OK: // Positive response // See ISO 14229(2006) Table 254 pduTxData->SduDataPtr[0] = 0x59; // positive response pduTxData->SduDataPtr[1] = 0x04; // subid pduTxData->SduDataPtr[2] = pduRxData->SduDataPtr[2]; // DTC pduTxData->SduDataPtr[3] = pduRxData->SduDataPtr[3]; pduTxData->SduDataPtr[4] = pduRxData->SduDataPtr[4]; pduTxData->SduDataPtr[5] = (uint8)DtcStatus; //status pduTxData->SduLength = SizeOfTxBuf + 6; responseCode = DCM_E_POSITIVERESPONSE; break; case DEM_GET_FFDATABYDTC_BUFFERSIZE: responseCode = DCM_E_RESPONSETOOLONG; break; default: responseCode = DCM_E_REQUESTOUTOFRANGE; } return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x05(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; (void)pduTxData; //lint +estring(920,pointer) /* cast to void */ // IMPROVEMENT: Add support responseCode = DCM_E_REQUESTOUTOFRANGE; return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x0B_0x0C_0x0D_0x0E(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; (void)pduTxData; //lint +estring(920,pointer) /* cast to void */ // IMPROVEMENT: Add support responseCode = DCM_E_REQUESTOUTOFRANGE; return responseCode; } static Dcm_NegativeResponseCodeType udsReadDtcInfoSub_0x14(const PduInfoType *pduRxData, PduInfoType *pduTxData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; //lint -estring(920,pointer) /* cast to void */ (void)pduRxData; /* Avoid compiler warning */ (void)pduTxData; /* Avoid compiler warning */ //lint +estring(920,pointer) /* cast to void */ // IMPROVEMENT: Add support /** !464 */ responseCode = DCM_E_REQUESTOUTOFRANGE; return responseCode; } void DspUdsReadDtcInformation(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM248 */ // Sub function number 0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 const uint8 sduLength[0x16] = {0, 3, 3, 2, 6, 3, 6, 4, 4, 5, 2, 2, 2, 2, 2, 3, 6, 3, 3, 3, 2, 2}; /* Sub function number 0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 */ const boolean subFncSupported[0x16] = {0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0,}; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint8 subFunctionNumber = pduRxData->SduDataPtr[1]; // Check length if (subFunctionNumber <= 0x15) { if(subFncSupported[subFunctionNumber]) { if (pduRxData->SduLength == sduLength[subFunctionNumber]) { switch (subFunctionNumber) { case 0x01: // reportNumberOfDTCByStatusMask case 0x07: // reportNumberOfDTCBySeverityMaskRecord case 0x11: // reportNumberOfMirrorMemoryDTCByStatusMask case 0x12: // reportNumberOfEmissionRelatedOBDDTCByStatusMask responseCode = udsReadDtcInfoSub_0x01_0x07_0x11_0x12(pduRxData, pduTxData); break; case 0x02: // reportDTCByStatusMask case 0x0A: // reportSupportedDTC case 0x0F: // reportMirrorMemoryDTCByStatusMask case 0x13: // reportEmissionRelatedOBDDTCByStatusMask case 0x15: // reportDTCWithPermanentStatus responseCode = udsReadDtcInfoSub_0x02_0x0A_0x0F_0x13_0x15(pduRxData, pduTxData); break; case 0x08: // reportDTCBySeverityMaskRecord responseCode = udsReadDtcInfoSub_0x08(pduRxData, pduTxData); break; case 0x09: // reportSeverityInformationOfDTC responseCode = udsReadDtcInfoSub_0x09(pduRxData, pduTxData); break; case 0x06: // reportDTCExtendedDataRecordByDTCNumber case 0x10: // reportMirrorMemoryDTCExtendedDataRecordByDTCNumber responseCode = udsReadDtcInfoSub_0x06_0x10(pduRxData, pduTxData); break; case 0x03: // reportDTCSnapshotIdentidication responseCode = udsReadDtcInfoSub_0x03(pduRxData, pduTxData); break; case 0x04: // reportDTCSnapshotByDtcNumber responseCode = udsReadDtcInfoSub_0x04(pduRxData, pduTxData); break; case 0x05: // reportDTCSnapshotRecordNumber responseCode = udsReadDtcInfoSub_0x05(pduRxData, pduTxData); break; case 0x0B: // reportFirstTestFailedDTC case 0x0C: // reportFirstConfirmedDTC case 0x0D: // reportMostRecentTestFailedDTC case 0x0E: // reportMostRecentConfirmedDTC responseCode = udsReadDtcInfoSub_0x0B_0x0C_0x0D_0x0E(pduRxData, pduTxData); break; case 0x14: // reportDTCFaultDetectionCounter responseCode = udsReadDtcInfoSub_0x14(pduRxData, pduTxData); break; default: // Unknown sub function responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } else { // Wrong length responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { /* Subfunction not supported */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } } else { /* Subfunction not supported */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } DsdDspProcessingDone(responseCode); } #endif /** ** This Function for check the pointer of Dynamically Did Sourced by Did buffer using a didNr **/ #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER static boolean LookupDDD(uint16 didNr, const Dcm_DspDDDType **DDid ) { uint8 i; boolean ret = FALSE; const Dcm_DspDDDType* DDidptr = &dspDDD[0]; if (didNr < DCM_PERODICDID_HIGH_MASK) { return ret; } for(i = 0;((i < DCM_MAX_DDD_NUMBER) && (ret == FALSE)); i++) { if(DDidptr->DynamicallyDid == didNr) { ret = TRUE; } else { DDidptr++; } } if(ret == TRUE) { *DDid = DDidptr; } return ret; } #endif static void DspCancelPendingDid(uint16 didNr, uint16 signalIndex, ReadDidPendingStateType pendingState, PduInfoType *pduTxData ) { const Dcm_DspDidType *didPtr = NULL_PTR; if( lookupNonDynamicDid(didNr, &didPtr) ) { if( signalIndex < didPtr->DspNofSignals ) { const Dcm_DspDataType *dataPtr = didPtr->DspSignalRef[signalIndex].DspSignalDataRef; if( DCM_READ_DID_PENDING_COND_CHECK == pendingState ) { if( dataPtr->DspDataConditionCheckReadFnc != NULL_PTR ) { (void)dataPtr->DspDataConditionCheckReadFnc (DCM_CANCEL, pduTxData->SduDataPtr); } } else if( DCM_READ_DID_PENDING_READ_DATA == pendingState ) { if( dataPtr->DspDataReadDataFnc.AsynchDataReadFnc != NULL_PTR ) { if( DATA_PORT_ASYNCH == dataPtr->DspDataUsePort ) { (void)dataPtr->DspDataReadDataFnc.AsynchDataReadFnc(DCM_CANCEL, pduTxData->SduDataPtr); } } } else { /* Not in a pending state */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } else { /* Invalid signal index */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } } /** ** This Function for read Dynamically Did data buffer Sourced by Memory address using a didNr **/ #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER static Dcm_NegativeResponseCodeType readDDDData(Dcm_DspDDDType *DDidPtr, uint8 *Data, uint16 bufSize, uint16 *Length) { uint8 i; uint8 dataCount; uint16 SourceDataLength = 0u; const Dcm_DspDidType *SourceDidPtr = NULL_PTR; const Dcm_DspSignalType *signalPtr; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; *Length = 0u; uint8* nextDataSlot = Data; for(i = 0;(i < DCM_MAX_DDDSOURCE_NUMBER) && (DDidPtr->DDDSource[i].formatOrPosition != 0) &&(responseCode == DCM_E_POSITIVERESPONSE);i++) { if(DDidPtr->DDDSource[i].DDDTpyeID == DCM_DDD_SOURCE_ADDRESS) { responseCode = checkAddressRange(DCM_READ_MEMORY, DDidPtr->DDDSource[i].memoryIdentifier, DDidPtr->DDDSource[i].SourceAddressOrDid, DDidPtr->DDDSource[i].Size); if( responseCode == DCM_E_POSITIVERESPONSE ) { if( (DDidPtr->DDDSource[i].Size + *Length) <= bufSize ) { (void)Dcm_ReadMemory(DCM_INITIAL,DDidPtr->DDDSource[i].memoryIdentifier, DDidPtr->DDDSource[i].SourceAddressOrDid, DDidPtr->DDDSource[i].Size, nextDataSlot); nextDataSlot += DDidPtr->DDDSource[i].Size; *Length += DDidPtr->DDDSource[i].Size; } else { responseCode = DCM_E_RESPONSETOOLONG; } } } else if(DDidPtr->DDDSource[i].DDDTpyeID == DCM_DDD_SOURCE_DID) { if(lookupNonDynamicDid(DDidPtr->DDDSource[i].SourceAddressOrDid,&SourceDidPtr) && (NULL_PTR != SourceDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead) ) { if(DspCheckSecurityLevel(SourceDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSecurityLevelRef) != TRUE) { responseCode = DCM_E_SECURITYACCESSDENIED; } else { for( uint16 signal = 0; signal < SourceDidPtr->DspNofSignals; signal++ ) { uint8 *didDataStart = nextDataSlot; signalPtr = &SourceDidPtr->DspSignalRef[signal]; if( signalPtr->DspSignalDataRef->DspDataInfoRef->DspDidFixedLength || (DATA_PORT_SR == signalPtr->DspSignalDataRef->DspDataUsePort)) { SourceDataLength = GetNofAffectedBytes(signalPtr->DspSignalDataRef->DspDataEndianess, signalPtr->DspSignalBitPosition, signalPtr->DspSignalDataRef->DspDataBitSize); } else if( NULL_PTR != signalPtr->DspSignalDataRef->DspDataReadDataLengthFnc ) { (void)signalPtr->DspSignalDataRef->DspDataReadDataLengthFnc(&SourceDataLength); } if( (SourceDidPtr->DspDidDataByteSize + *Length) <= bufSize ) { if( (NULL_PTR != signalPtr->DspSignalDataRef->DspDataReadDataFnc.SynchDataReadFnc) && (SourceDataLength != 0) && (DCM_E_POSITIVERESPONSE == responseCode) ) { if((DATA_PORT_SYNCH == signalPtr->DspSignalDataRef->DspDataUsePort) || (DATA_PORT_ECU_SIGNAL == signalPtr->DspSignalDataRef->DspDataUsePort)) { (void)signalPtr->DspSignalDataRef->DspDataReadDataFnc.SynchDataReadFnc(didDataStart + (signalPtr->DspSignalBitPosition / 8)); } else if(DATA_PORT_ASYNCH == signalPtr->DspSignalDataRef->DspDataUsePort) { (void)signalPtr->DspSignalDataRef->DspDataReadDataFnc.AsynchDataReadFnc(DCM_INITIAL, didDataStart + (signalPtr->DspSignalBitPosition / 8)); } else if(DATA_PORT_SR == signalPtr->DspSignalDataRef->DspDataUsePort) { (void)ReadSRSignal(signalPtr->DspSignalDataRef, signalPtr->DspSignalBitPosition, didDataStart); } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /* IMPROVEMENT: Actually response may fit but implementation reads the * complete DID to the buffer. */ responseCode = DCM_E_RESPONSETOOLONG; } } if( DCM_E_POSITIVERESPONSE == responseCode ) { for(dataCount = 0; dataCount < DDidPtr->DDDSource[i].Size; dataCount++) { /* Shifting the data left by position (position 1 means index 0) */ nextDataSlot[dataCount] = nextDataSlot[dataCount + DDidPtr->DDDSource[i].formatOrPosition - 1]; } nextDataSlot += DDidPtr->DDDSource[i].Size; *Length += DDidPtr->DDDSource[i].Size; } } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } return responseCode; } #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER static Dcm_NegativeResponseCodeType checkDDDConditions(Dcm_DspDDDType *DDidPtr, uint16 *Length) { const Dcm_DspDidType *SourceDidPtr = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; *Length = 0u; for(uint8 i = 0u;(i < DCM_MAX_DDDSOURCE_NUMBER) && (DDidPtr->DDDSource[i].formatOrPosition != 0) &&(responseCode == DCM_E_POSITIVERESPONSE);i++) { *Length += DDidPtr->DDDSource[i].Size; if(DDidPtr->DDDSource[i].DDDTpyeID == DCM_DDD_SOURCE_ADDRESS) { responseCode = checkAddressRange(DCM_READ_MEMORY, DDidPtr->DDDSource[i].memoryIdentifier, DDidPtr->DDDSource[i].SourceAddressOrDid, DDidPtr->DDDSource[i].Size); } else if(DDidPtr->DDDSource[i].DDDTpyeID == DCM_DDD_SOURCE_DID) { if( lookupNonDynamicDid(DDidPtr->DDDSource[i].SourceAddressOrDid,&SourceDidPtr) && (NULL_PTR != SourceDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead) ) { if( DspCheckSessionLevel(SourceDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSessionRef) ) { if( !DspCheckSecurityLevel(SourceDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSecurityLevelRef) ) { responseCode = DCM_E_SECURITYACCESSDENIED; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } return responseCode; } #endif void DspUdsReadDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM253 */ /* !req DCM561 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint16 nrOfDids; uint16 didNr; const Dcm_DspDidType *didPtr = NULL_PTR; Dcm_DspDDDType *DDidPtr = NULL_PTR; uint16 txPos = 1u; uint16 i; uint16 Length = 0u; boolean noRequestedDidSupported = TRUE; ReadDidPendingStateType pendingState = DCM_READ_DID_IDLE; uint16 nofDidsRead = 0u; uint16 reqDidStartIndex = 0u; uint16 nofDidsReadInPendingReq = 0u; uint16 pendingDid = 0u; uint16 pendingDataLen = 0u; uint16 pendingSigIndex = 0u; uint16 pendingDataStartPos = 0u; if ( (((pduRxData->SduLength - 1) % 2) == 0) && ( 0 != (pduRxData->SduLength - 1))) { nrOfDids = (pduRxData->SduLength - 1) / 2; if( DCM_READ_DID_IDLE != dspUdsReadDidPending.state ) { pendingState = dspUdsReadDidPending.state; txPos = dspUdsReadDidPending.txWritePos; nofDidsReadInPendingReq = dspUdsReadDidPending.nofReadDids; reqDidStartIndex = dspUdsReadDidPending.reqDidIndex; pendingDataLen = dspUdsReadDidPending.pendingDataLength; pendingSigIndex = dspUdsReadDidPending.pendingSignalIndex; pendingDataStartPos = dspUdsReadDidPending.pendingDataStartPos; } /* IMPROVEMENT: Check security level and session for all dids before trying to read data */ for (i = reqDidStartIndex; (i < nrOfDids) && (responseCode == DCM_E_POSITIVERESPONSE); i++) { didNr = (uint16)((uint16)pduRxData->SduDataPtr[1 + (i * 2)] << 8) + pduRxData->SduDataPtr[2 + (i * 2)]; if (lookupNonDynamicDid(didNr, &didPtr)) { /* @req DCM438 */ noRequestedDidSupported = FALSE; /* IMPROVEMENT: Check if the did has data or did ref. If not NRC here? */ /* !req DCM481 */ /* !req DCM482 */ /* !req DCM483 */ responseCode = readDidData(didPtr, pduTxData, &txPos, &pendingState, &pendingDid, &pendingSigIndex, &pendingDataLen, &nofDidsRead, nofDidsReadInPendingReq, &pendingDataStartPos); if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsReadDidPending.reqDidIndex = i; } else { /* No pending response */ nofDidsReadInPendingReq = 0u; nofDidsRead = 0u; } } else if(LookupDDD(didNr,(const Dcm_DspDDDType **)&DDidPtr) == TRUE) { noRequestedDidSupported = FALSE; /* @req DCM651 */ /* @req DCM652 */ /* @req DCM653 */ pduTxData->SduDataPtr[txPos++] = (uint8)((DDidPtr->DynamicallyDid>>8) & 0xFF); pduTxData->SduDataPtr[txPos++] = (uint8)(DDidPtr->DynamicallyDid & 0xFF); responseCode = readDDDData(DDidPtr, &(pduTxData->SduDataPtr[txPos]), pduTxData->SduLength - txPos, &Length); txPos += Length; } else { /* DID not found. */ } } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( (responseCode != DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT) && noRequestedDidSupported ) { /* @req DCM438 */ /* None of the Dids in the request found. */ responseCode = DCM_E_REQUESTOUTOFRANGE; } if (DCM_E_POSITIVERESPONSE == responseCode) { pduTxData->SduLength = txPos; } if( DCM_E_RESPONSEPENDING == responseCode) { dspUdsReadDidPending.state = pendingState; dspUdsReadDidPending.pduRxData = (PduInfoType*)pduRxData; dspUdsReadDidPending.pduTxData = pduTxData; dspUdsReadDidPending.nofReadDids = nofDidsRead; dspUdsReadDidPending.txWritePos = txPos; dspUdsReadDidPending.pendingDid = pendingDid; dspUdsReadDidPending.pendingDataLength = pendingDataLen; dspUdsReadDidPending.pendingSignalIndex = pendingSigIndex; dspUdsReadDidPending.pendingDataStartPos = pendingDataStartPos; } else { dspUdsReadDidPending.state = DCM_READ_DID_IDLE; dspUdsReadDidPending.nofReadDids = 0; DsdDspProcessingDone(responseCode); } } static Dcm_NegativeResponseCodeType readDidScalingData(const Dcm_DspDidType *didPtr, const PduInfoType *pduTxData, uint16 *txPos) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; const Dcm_DspDataType *dataPtr; if( (*txPos + didPtr->DspDidDataScalingInfoSize + 2) <= pduTxData->SduLength ) { pduTxData->SduDataPtr[(*txPos)++] = (didPtr->DspDidIdentifier >> 8) & 0xFFu; pduTxData->SduDataPtr[(*txPos)++] = didPtr->DspDidIdentifier & 0xFFu; for( uint16 i = 0u; (i < didPtr->DspNofSignals) && (DCM_E_POSITIVERESPONSE == responseCode); i++ ) { Std_ReturnType result; Dcm_NegativeResponseCodeType errorCode; dataPtr = didPtr->DspSignalRef[i].DspSignalDataRef; if( NULL_PTR != dataPtr->DspDataGetScalingInfoFnc ) { /* @req DCM394 */ result = dataPtr->DspDataGetScalingInfoFnc(DCM_INITIAL, &pduTxData->SduDataPtr[*txPos], &errorCode); *txPos += dataPtr->DspDataInfoRef->DspDidScalingInfoSize; if ((result != E_OK) || (errorCode != DCM_E_POSITIVERESPONSE)) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { /* No scaling info function. Is it correct to give negative response here? */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } } else { /* Not enough room in tx buffer */ responseCode = DCM_E_RESPONSETOOLONG; } return responseCode; } void DspUdsReadScalingDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM258 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint16 didNr; const Dcm_DspDidType *didPtr = NULL_PTR; uint16 txPos = 1; if (pduRxData->SduLength == 3) { didNr = (uint16)((uint16)pduRxData->SduDataPtr[1] << 8) + pduRxData->SduDataPtr[2]; if (lookupNonDynamicDid(didNr, &didPtr)) { responseCode = readDidScalingData(didPtr, pduTxData, &txPos); } else { // DID not found responseCode = DCM_E_REQUESTOUTOFRANGE; } if (responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduLength = txPos; } } else { // Length not ok responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone(responseCode); } #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER #if defined(USE_NVM) && defined(DCM_USE_NVM_DID) /** * Writes data to an NvM block * @param blockId * @param data * @param isPending * @return */ static Dcm_NegativeResponseCodeType writeDataToNvMBlock(NvM_BlockIdType blockId, uint8 *data, boolean isPending) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if( isPending ){ NvM_RequestResultType errorStatus = NVM_REQ_NOT_OK; if (E_OK != NvM_GetErrorStatus(blockId, &errorStatus)){ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_GENERALREJECT; } else { if (errorStatus == NVM_REQ_PENDING){ responseCode = DCM_E_RESPONSEPENDING; } else if (errorStatus == NVM_REQ_OK) { responseCode = DCM_E_POSITIVERESPONSE; } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_GENERALREJECT; } } if( DCM_E_RESPONSEPENDING != responseCode ) { /* Done or something failed. Lock block. */ NvM_SetBlockLockStatus(blockId, TRUE); } } else { NvM_SetBlockLockStatus(blockId, FALSE); if (E_OK == NvM_WriteBlock(blockId, data)) { responseCode = DCM_E_RESPONSEPENDING; } else { NvM_SetBlockLockStatus(blockId, TRUE); DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_GENERALREJECT; } } return responseCode; } #endif static Dcm_NegativeResponseCodeType writeDidData(const Dcm_DspDidType *didPtr, const PduInfoType *pduRxData, uint16 writeDidLen) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; const Dcm_DspSignalType *signalPtr; if (didPtr->DspDidInfoRef->DspDidAccess.DspDidWrite != NULL_PTR ) { /* @req DCM468 */ if (DspCheckSessionLevel(didPtr->DspDidInfoRef->DspDidAccess.DspDidWrite->DspDidWriteSessionRef)) { /* @req DCM469 */ if (DspCheckSecurityLevel(didPtr->DspDidInfoRef->DspDidAccess.DspDidWrite->DspDidWriteSecurityLevelRef)) { /* @req DCM470 */ uint16 dataLen = 0; /* Check the size */ /* @req DCM473 */ if( (NULL_PTR != didPtr->DspSignalRef) && ( (didPtr->DspSignalRef[0].DspSignalDataRef->DspDataInfoRef->DspDidFixedLength && (writeDidLen == didPtr->DspDidDataByteSize)) || (!didPtr->DspSignalRef[0].DspSignalDataRef->DspDataInfoRef->DspDidFixedLength)) ) { for( uint16 i = 0u; i < (didPtr->DspNofSignals) && (DCM_E_POSITIVERESPONSE == responseCode); i++ ) { signalPtr = &didPtr->DspSignalRef[i]; if( !signalPtr->DspSignalDataRef->DspDataInfoRef->DspDidFixedLength ) { dataLen = writeDidLen; } Std_ReturnType result; if(signalPtr->DspSignalDataRef->DspDataUsePort == DATA_PORT_BLOCK_ID) { #if defined(USE_NVM) && defined(DCM_USE_NVM_DID) /* @req DCM541 */ responseCode = writeDataToNvMBlock(signalPtr->DspSignalDataRef->DspNvmUseBlockID, &pduRxData->SduDataPtr[3 + (signalPtr->DspSignalBitPosition / 8)], ((dspUdsWriteDidPending.state == DCM_GENERAL_PENDING)? TRUE: FALSE)); #endif } else { Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; if(dspUdsWriteDidPending.state == DCM_GENERAL_PENDING){ opStatus = (Dcm_OpStatusType)DCM_PENDING; } if( NULL_PTR != signalPtr->DspSignalDataRef->DspDataWriteDataFnc.FixLenDataWriteFnc ) { if(DATA_PORT_SR == signalPtr->DspSignalDataRef->DspDataUsePort) { result = WriteSRSignal(signalPtr->DspSignalDataRef, signalPtr->DspSignalBitPosition, &pduRxData->SduDataPtr[3]); } else { if(signalPtr->DspSignalDataRef->DspDataInfoRef->DspDidFixedLength) { /* @req DCM794 */ /* @req DCM395 */ result = signalPtr->DspSignalDataRef->DspDataWriteDataFnc.FixLenDataWriteFnc(&pduRxData->SduDataPtr[3 + (signalPtr->DspSignalBitPosition / 8)], opStatus, &responseCode); } else { /* @req DCM395 */ result = signalPtr->DspSignalDataRef->DspDataWriteDataFnc.DynLenDataWriteFnc(&pduRxData->SduDataPtr[3 + (signalPtr->DspSignalBitPosition / 8)], dataLen, opStatus, &responseCode); } } if( DCM_E_RESPONSEPENDING == responseCode || E_PENDING == result ) { responseCode = DCM_E_RESPONSEPENDING; } else if( result != E_OK && responseCode == DCM_E_POSITIVERESPONSE ) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { /* No write function */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } } } else { // Length incorrect responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { // Not allowed in current security level responseCode = DCM_E_SECURITYACCESSDENIED; } } else { // Not allowed in current session responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { // Read access not configured responseCode = DCM_E_REQUESTOUTOFRANGE; } return responseCode; } void DspUdsWriteDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM255 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint16 didNr; const Dcm_DspDidType *didPtr = NULL_PTR; uint16 didDataLength; didDataLength = pduRxData->SduLength - 3; didNr = (uint16)((uint16)pduRxData->SduDataPtr[1] << 8) + pduRxData->SduDataPtr[2]; /* Check that did is supported.*/ if (lookupNonDynamicDid(didNr, &didPtr)) { /* @req DCM467 */ responseCode = writeDidData(didPtr, pduRxData, didDataLength);/* !req DCM562 */ } else { /* DID not supported */ responseCode = DCM_E_REQUESTOUTOFRANGE; } if( DCM_E_RESPONSEPENDING != responseCode ) { if (responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduLength = 3; pduTxData->SduDataPtr[1] = (uint8)((didNr >> 8) & 0xFFu); pduTxData->SduDataPtr[2] = (uint8)(didNr & 0xFFu); } dspUdsWriteDidPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } else { dspUdsWriteDidPending.state = DCM_GENERAL_PENDING; dspUdsWriteDidPending.pduRxData = pduRxData; dspUdsWriteDidPending.pduTxData = pduTxData; } } #endif /** * Cancels a pending security access request * @param pduRxData * @param pduTxData */ static void DspCancelPendingSecurityAccess(const PduInfoType *pduRxData, PduInfoType *pduTxData) { // Check sub function range (0x01 to 0x42) if ((pduRxData->SduDataPtr[1] >= 0x01) && (pduRxData->SduDataPtr[1] <= 0x42)) { boolean isRequestSeed = ((pduRxData->SduDataPtr[1] & 0x01u) == 0x01u)? TRUE: FALSE; Dcm_SecLevelType requestedSecurityLevel = (pduRxData->SduDataPtr[1]+1)/2; if (isRequestSeed) { (void)DspUdsSecurityAccessGetSeedSubFnc(pduRxData, pduTxData, requestedSecurityLevel, TRUE); } else { (void)DspUdsSecurityAccessCompareKeySubFnc(pduRxData, pduTxData, requestedSecurityLevel, TRUE); } } } static Dcm_NegativeResponseCodeType DspUdsSecurityAccessGetSeedSubFnc (const PduInfoType *pduRxData, PduInfoType *pduTxData, Dcm_SecLevelType requestedSecurityLevel, boolean isCancel) { Dcm_NegativeResponseCodeType getSeedErrorCode; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint8 cntSecRow = 0; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; if(dspUdsSecurityAccessPending.state == DCM_GENERAL_PENDING){ if( isCancel ) { opStatus = (Dcm_OpStatusType)DCM_CANCEL; } else { opStatus = (Dcm_OpStatusType)DCM_PENDING; } } // requestSeed message // Check if type exist in security table const Dcm_DspSecurityRowType *securityRow = &Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[0]; while ((securityRow->DspSecurityLevel != requestedSecurityLevel) && (!securityRow->Arc_EOL)) { securityRow++; cntSecRow++; // Get the index of the security config } if (!securityRow->Arc_EOL) { #if (DCM_SECURITY_EOL_INDEX != 0) //Check if a wait is required before accepting a request dspUdsSecurityAccesData.currSecLevIdx = cntSecRow; if (dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].startDelayTimer != DELAY_TIMER_DEACTIVE) { responseCode = DCM_E_REQUIREDTIMEDELAYNOTEXPIRED; } else #endif { // Check length if (pduRxData->SduLength == (2 + securityRow->DspSecurityADRSize)) { /* @req DCM321 RequestSeed */ Dcm_SecLevelType activeSecLevel; Std_ReturnType result; result = Dcm_GetSecurityLevel(&activeSecLevel); if (result == E_OK) { if( (2 + securityRow->DspSecuritySeedSize) <= pduTxData->SduLength ) { if (requestedSecurityLevel == activeSecLevel) { /* @req DCM323 */ pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; // If same level set the seed to zeroes memset(&pduTxData->SduDataPtr[2], 0, securityRow->DspSecuritySeedSize); pduTxData->SduLength = 2 + securityRow->DspSecuritySeedSize; } else { // New security level ask for seed if ((securityRow->GetSeed.getSeedWithoutRecord != NULL_PTR) || (securityRow->GetSeed.getSeedWithRecord != NULL_PTR)) { Std_ReturnType getSeedResult; if(securityRow->DspSecurityADRSize > 0) { /* @req DCM324 RequestSeed */ getSeedResult = securityRow->GetSeed.getSeedWithRecord(&pduRxData->SduDataPtr[2], opStatus, &pduTxData->SduDataPtr[2], &getSeedErrorCode); } else { /* @req DCM324 RequestSeed */ getSeedResult = securityRow->GetSeed.getSeedWithoutRecord(opStatus, &pduTxData->SduDataPtr[2], &getSeedErrorCode); } if (getSeedResult == E_PENDING){ responseCode = DCM_E_RESPONSEPENDING; } else if (getSeedResult == E_OK) { // Everything ok add sub function to tx message and send it. pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; pduTxData->SduLength = 2 + securityRow->DspSecuritySeedSize; dspUdsSecurityAccesData.reqSecLevel = requestedSecurityLevel; dspUdsSecurityAccesData.reqSecLevelRef = securityRow; dspUdsSecurityAccesData.reqInProgress = TRUE; } else { // GetSeed returned not ok responseCode = getSeedErrorCode; /* @req DCM659 */ } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } } else { /* Tx buffer not big enough */ responseCode = DCM_E_RESPONSETOOLONG; } } else { // NOTE: What to do? responseCode = DCM_E_GENERALREJECT; } } else { // Length not ok responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } } else { // Requested security level not configured responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } return responseCode; } // CompareKey message static Dcm_NegativeResponseCodeType DspUdsSecurityAccessCompareKeySubFnc (const PduInfoType *pduRxData, PduInfoType *pduTxData, Dcm_SecLevelType requestedSecurityLevel, boolean isCancel) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; if(dspUdsSecurityAccessPending.state == DCM_GENERAL_PENDING){ if( isCancel ) { opStatus = (Dcm_OpStatusType)DCM_CANCEL; } else { opStatus = (Dcm_OpStatusType)DCM_PENDING; } } if (requestedSecurityLevel == dspUdsSecurityAccesData.reqSecLevel) { /* Check whether senkey message is sent according to a valid sequence */ if (dspUdsSecurityAccesData.reqInProgress) { #if (DCM_SECURITY_EOL_INDEX != 0) //Check if a wait is required before accepting a request if (dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].startDelayTimer != DELAY_TIMER_DEACTIVE) { responseCode = DCM_E_REQUIREDTIMEDELAYNOTEXPIRED; } else #endif { if (pduRxData->SduLength == (2 + dspUdsSecurityAccesData.reqSecLevelRef->DspSecurityKeySize)) { /* @req DCM321 SendKey */ if ((dspUdsSecurityAccesData.reqSecLevelRef->CompareKey != NULL_PTR)) { Std_ReturnType compareKeyResult; compareKeyResult = dspUdsSecurityAccesData.reqSecLevelRef->CompareKey(&pduRxData->SduDataPtr[2], opStatus); /* @req DCM324 SendKey */ if( isCancel ) { /* Ignore compareKeyResult on cancel */ responseCode = DCM_E_POSITIVERESPONSE; } else if (compareKeyResult == E_PENDING) { responseCode = DCM_E_RESPONSEPENDING; } else if (compareKeyResult == E_OK) { /* Client should reiterate the process of getseed msg, if sendkey fails- ISO14229 */ dspUdsSecurityAccesData.reqInProgress = FALSE; // Request accepted // Kill timer DslInternal_SetSecurityLevel(dspUdsSecurityAccesData.reqSecLevelRef->DspSecurityLevel); /* @req DCM325 */ pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; pduTxData->SduLength = 2; } else { /* Client should reiterate the process of getseed msg, if sendkey fails- ISO14229 */ dspUdsSecurityAccesData.reqInProgress = FALSE; responseCode = DCM_E_INVALIDKEY; /* @req DCM660 */ } } else { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { // Length not ok responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } #if (DCM_SECURITY_EOL_INDEX != 0) //Count the false access attempts -> Only send invalid keys events according to ISO 14229 if (responseCode == DCM_E_INVALIDKEY) { dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].secAcssAttempts += 1; if (dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].secAcssAttempts >= dspUdsSecurityAccesData.reqSecLevelRef->DspSecurityNumAttDelay) { //Enable delay timer if (Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[dspUdsSecurityAccesData.currSecLevIdx].DspSecurityDelayTime >= DCM_MAIN_FUNCTION_PERIOD_TIME_MS) { dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].startDelayTimer = DELAY_TIMER_ON_EXCEEDING_LIMIT_ACTIVE; dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].timerSecAcssAttempt = Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[dspUdsSecurityAccesData.currSecLevIdx].DspSecurityDelayTime; } dspUdsSecurityAccesData.secFalseAttemptChk[dspUdsSecurityAccesData.currSecLevIdx].secAcssAttempts = 0; if (Dcm_ConfigPtr->Dsp->DspSecurity->DspSecurityRow[dspUdsSecurityAccesData.currSecLevIdx].DspSecurityDelayTime > 0) { responseCode = DCM_E_EXCEEDNUMBEROFATTEMPTS; // Delay time is optional according to ISO spec and so is the NRC } } } #endif } } else { // sendKey request without a preceding requestSeed responseCode = DCM_E_REQUESTSEQUENCEERROR; } } else { // sendKey request without a preceding requestSeed #if defined(CFG_DCM_SECURITY_ACCESS_NRC_FIX) /* Should this really give subFunctionNotSupported? */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; #else responseCode = DCM_E_REQUESTSEQUENCEERROR; #endif } return responseCode; } void DspUdsSecurityAccess(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM252 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if( pduRxData->SduLength >= 2u) { /* Check sub function range (0x01 to 0x42) */ if ((pduRxData->SduDataPtr[1] >= 0x01) && (pduRxData->SduDataPtr[1] <= 0x42)) { boolean isRequestSeed = pduRxData->SduDataPtr[1] & 0x01u; Dcm_SecLevelType requestedSecurityLevel = (pduRxData->SduDataPtr[1]+1)/2; if (isRequestSeed) { responseCode = DspUdsSecurityAccessGetSeedSubFnc(pduRxData, pduTxData, requestedSecurityLevel,FALSE); } else { responseCode = DspUdsSecurityAccessCompareKeySubFnc(pduRxData, pduTxData, requestedSecurityLevel,FALSE); } } else { responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( DCM_E_RESPONSEPENDING != responseCode ) { dspUdsSecurityAccessPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } else { dspUdsSecurityAccessPending.state = DCM_GENERAL_PENDING; dspUdsSecurityAccessPending.pduRxData = pduRxData; dspUdsSecurityAccessPending.pduTxData = pduTxData; } } static boolean lookupRoutine(uint16 routineId, const Dcm_DspRoutineType **routinePtr) { const Dcm_DspRoutineType *dspRoutine = Dcm_ConfigPtr->Dsp->DspRoutine; boolean routineFound = FALSE; while ((dspRoutine->DspRoutineIdentifier != routineId) && (!dspRoutine->Arc_EOL)) { dspRoutine++; } if (!dspRoutine->Arc_EOL) { routineFound = TRUE; *routinePtr = dspRoutine; } return routineFound; } static void SetOpStatusDependingOnState(DspUdsGeneralPendingType *pGeneralPending,Dcm_OpStatusType *opStatus, boolean isCancel) { if(pGeneralPending->state == DCM_GENERAL_PENDING || pGeneralPending->state == DCM_GENERAL_FORCE_RCRRP){ if( isCancel ) { *opStatus = (Dcm_OpStatusType)DCM_CANCEL; } else { if(pGeneralPending->state == DCM_GENERAL_FORCE_RCRRP) { *opStatus = (Dcm_OpStatusType)DCM_FORCE_RCRRP_OK; } else { *opStatus = (Dcm_OpStatusType)DCM_PENDING; } } } } static Dcm_NegativeResponseCodeType startRoutine(const Dcm_DspRoutineType *routinePtr, const PduInfoType *pduRxData, PduInfoType *pduTxData, boolean isCancel) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType routineResult; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsRoutineControlPending,&opStatus, isCancel); // startRoutine if ((routinePtr->DspStartRoutineFnc != NULL_PTR) && (routinePtr->DspRoutineInfoRef->DspStartRoutine != NULL_PTR)) { if ( (routinePtr->DspRoutineInfoRef->DspStartRoutine->DspStartRoutineCtrlOptRecSize + 4) <= pduRxData->SduLength ) { if ((routinePtr->DspRoutineInfoRef->DspStartRoutine->DspStartRoutineStsOptRecSize + 4) <= pduTxData->SduLength ) { uint16 currentDataLength = pduRxData->SduLength - 4; /* @req DCM400 */ /* @req DCM401 */ routineResult = routinePtr->DspStartRoutineFnc(&pduRxData->SduDataPtr[4], opStatus, &pduTxData->SduDataPtr[4], &currentDataLength, &responseCode, FALSE); if (routineResult == E_PENDING){ responseCode = DCM_E_RESPONSEPENDING; } else if (routineResult == E_FORCE_RCRRP) { responseCode = DCM_E_FORCE_RCRRP; } else if (routineResult != E_OK) { /* @req DCM668 */ if(DCM_E_POSITIVERESPONSE == responseCode) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { responseCode = DCM_E_POSITIVERESPONSE; pduTxData->SduLength = currentDataLength + 4; } if( (responseCode == DCM_E_POSITIVERESPONSE) && (pduTxData->SduLength > (routinePtr->DspRoutineInfoRef->DspStartRoutine->DspStartRoutineStsOptRecSize + 4)) ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_PARAM); pduTxData->SduLength = routinePtr->DspRoutineInfoRef->DspStartRoutine->DspStartRoutineStsOptRecSize + 4; } } else { /* Tx buffer not big enough */ responseCode = DCM_E_RESPONSETOOLONG; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } return responseCode; } static Dcm_NegativeResponseCodeType stopRoutine(const Dcm_DspRoutineType *routinePtr, const PduInfoType *pduRxData, PduInfoType *pduTxData, boolean isCancel) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType routineResult; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsRoutineControlPending,&opStatus, isCancel); // stopRoutine if ((routinePtr->DspStopRoutineFnc != NULL_PTR) && (routinePtr->DspRoutineInfoRef->DspRoutineStop != NULL_PTR)) { if ( (routinePtr->DspRoutineInfoRef->DspRoutineStop->DspStopRoutineCtrlOptRecSize + 4) <= pduRxData->SduLength ) { if ( (routinePtr->DspRoutineInfoRef->DspRoutineStop->DspStopRoutineStsOptRecSize + 4) <= pduTxData->SduLength ) { uint16 currentDataLength = pduRxData->SduLength - 4; /* @req DCM402 */ /* @req DCM403 */ routineResult = routinePtr->DspStopRoutineFnc(&pduRxData->SduDataPtr[4], opStatus, &pduTxData->SduDataPtr[4], &currentDataLength, &responseCode, FALSE); if (routineResult == E_PENDING){ responseCode = DCM_E_RESPONSEPENDING; } else if (routineResult == E_FORCE_RCRRP) { responseCode = DCM_E_FORCE_RCRRP; } else if (routineResult != E_OK) { /* @req DCM670 */ if(DCM_E_POSITIVERESPONSE == responseCode) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { responseCode = DCM_E_POSITIVERESPONSE; pduTxData->SduLength = currentDataLength + 4; } if(responseCode == DCM_E_POSITIVERESPONSE && pduTxData->SduLength > routinePtr->DspRoutineInfoRef->DspRoutineStop->DspStopRoutineStsOptRecSize + 4) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_PARAM); pduTxData->SduLength = routinePtr->DspRoutineInfoRef->DspRoutineStop->DspStopRoutineStsOptRecSize + 4; } } else { /* Tx buffer not big enough */ responseCode = DCM_E_RESPONSETOOLONG; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { /* @req 4.2.2/SWS_DCM_869 */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } return responseCode; } static Dcm_NegativeResponseCodeType requestRoutineResults(const Dcm_DspRoutineType *routinePtr, PduInfoType *pduTxData, boolean isCancel) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType routineResult; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsRoutineControlPending,&opStatus, isCancel); // requestRoutineResults if ((routinePtr->DspRequestResultRoutineFnc != NULL_PTR) && (routinePtr->DspRoutineInfoRef->DspRoutineRequestRes != NULL_PTR)) { if ((routinePtr->DspRoutineInfoRef->DspRoutineRequestRes->DspReqResRtnCtrlOptRecSize + 4) <= pduTxData->SduLength) { uint16 currentDataLength = 0u; /* @req DCM404 */ /* @req DCM405 */ routineResult = routinePtr->DspRequestResultRoutineFnc(opStatus, &pduTxData->SduDataPtr[4], &currentDataLength, &responseCode, FALSE); if (routineResult == E_PENDING){ responseCode = DCM_E_RESPONSEPENDING; } else if (routineResult == E_FORCE_RCRRP) { responseCode = DCM_E_FORCE_RCRRP; } else if (routineResult != E_OK) { /* @req DCM672 */ if(DCM_E_POSITIVERESPONSE == responseCode) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { responseCode = DCM_E_POSITIVERESPONSE; pduTxData->SduLength = currentDataLength + 4; } if( (responseCode == DCM_E_POSITIVERESPONSE) && (pduTxData->SduLength > routinePtr->DspRoutineInfoRef->DspRoutineRequestRes->DspReqResRtnCtrlOptRecSize + 4) ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_PARAM); pduTxData->SduLength = routinePtr->DspRoutineInfoRef->DspRoutineRequestRes->DspReqResRtnCtrlOptRecSize + 4; } } else { responseCode = DCM_E_RESPONSETOOLONG; } } else { /* @req 4.2.2/SWS_DCM_869 */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } return responseCode; } /** * Cancels a pending routine request * @param pduRxData * @param pduTxData */ static void DspCancelPendingRoutine(const PduInfoType *pduRxData, PduInfoType *pduTxData) { uint8 subFunctionNumber = pduRxData->SduDataPtr[1]; uint16 routineId = 0; if( (NULL != pduRxData) && (NULL != pduTxData)) { const Dcm_DspRoutineType *routinePtr = NULL_PTR; routineId = (uint16)((uint16)pduRxData->SduDataPtr[2] << 8) + pduRxData->SduDataPtr[3]; if (lookupRoutine(routineId, &routinePtr)) { switch (subFunctionNumber) { case 0x01: // startRoutine (void)startRoutine(routinePtr, pduRxData, pduTxData, TRUE); break; case 0x02: // stopRoutine (void)stopRoutine(routinePtr, pduRxData, pduTxData, TRUE); break; case 0x03: // requestRoutineResults (void)requestRoutineResults(routinePtr, pduTxData, TRUE); break; default: // This shall never happen break; } } } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_PARAM); } } void DspUdsRoutineControl(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM257 */ /* !req DCM701 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; uint8 subFunctionNumber = 0; uint16 routineId = 0u; const Dcm_DspRoutineType *routinePtr = NULL_PTR; if (pduRxData->SduLength >= 4) { subFunctionNumber = pduRxData->SduDataPtr[1]; if ((subFunctionNumber > 0) && (subFunctionNumber < 4)) { routineId = (uint16)((uint16)pduRxData->SduDataPtr[2] << 8) + pduRxData->SduDataPtr[3]; /* @req DCM568 */ /* !req DCM569 */ if (lookupRoutine(routineId, &routinePtr)) { if (DspCheckSessionLevel(routinePtr->DspRoutineInfoRef->DspRoutineAuthorization.DspRoutineSessionRef)) {/* @req DCM570 */ if (DspCheckSecurityLevel(routinePtr->DspRoutineInfoRef->DspRoutineAuthorization.DspRoutineSecurityLevelRef)) {/* @req DCM571 */ switch (subFunctionNumber) { case 0x01: // startRoutine responseCode = startRoutine(routinePtr, pduRxData, pduTxData, FALSE); break; case 0x02: // stopRoutine responseCode = stopRoutine(routinePtr, pduRxData, pduTxData, FALSE); break; case 0x03: // requestRoutineResults responseCode = requestRoutineResults(routinePtr, pduTxData, FALSE); break; default: // This shall never happen responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; break; } } else { // Not allowed in current security level responseCode = DCM_E_SECURITYACCESSDENIED; } } else { // Not allowed in current session responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { // Unknown routine identifier responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { // Sub function not supported responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } } else { // Wrong length responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsRoutineControlPending.state = DCM_GENERAL_PENDING; dspUdsRoutineControlPending.pduRxData = pduRxData; dspUdsRoutineControlPending.pduTxData = pduTxData; } else if(DCM_E_FORCE_RCRRP == responseCode) { dspUdsRoutineControlPending.state = DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND; dspUdsRoutineControlPending.pduRxData = pduRxData; dspUdsRoutineControlPending.pduTxData = pduTxData; /* @req DCM669 */ /* @req DCM671 */ /* @req DCM673 */ DsdDspForceResponsePending(); } else { if (responseCode == DCM_E_POSITIVERESPONSE) { // Add header to the positive response message pduTxData->SduDataPtr[1] = subFunctionNumber; pduTxData->SduDataPtr[2] = (routineId >> 8) & 0xFFu; pduTxData->SduDataPtr[3] = routineId & 0xFFu; } dspUdsRoutineControlPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } } void DspUdsTesterPresent(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM251 */ if (pduRxData->SduLength == 2) { switch (pduRxData->SduDataPtr[1]) { case ZERO_SUB_FUNCTION: DslResetSessionTimeoutTimer(); // Create positive response pduTxData->SduDataPtr[1] = ZERO_SUB_FUNCTION; pduTxData->SduLength = 2; DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); break; default: DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); break; } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING) static void DspEnableDTCSetting(void) { /* @req Dcm751 */ if( DspDTCSetting.settingDisabled ) { Dcm_SesCtrlType currentSession = DCM_DEFAULT_SESSION; if( E_OK != DslGetSesCtrlType(&currentSession) ) { currentSession = DCM_DEFAULT_SESSION; } if(((DCM_DEFAULT_SESSION == currentSession) || !DsdDspCheckServiceSupportedInActiveSessionAndSecurity(SID_CONTROL_DTC_SETTING)) ) { if( DEM_CONTROL_DTC_STORAGE_OK != Dem_EnableDTCSetting(DspDTCSetting.dtcGroup, DspDTCSetting.dtcKind) ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } (void)Rte_Switch_DcmControlDTCSetting_DcmControlDTCSetting(RTE_MODE_DcmControlDTCSetting_ENABLEDTCSETTING); DspDTCSetting.settingDisabled = FALSE; } } } void DspUdsControlDtcSetting(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM249 */ Dem_ReturnControlDTCStorageType resultCode; if (pduRxData->SduLength == 2) { switch (pduRxData->SduDataPtr[1]) { case 0x01: // ON resultCode = Dem_EnableDTCSetting(DEM_DTC_GROUP_ALL_DTCS, DEM_DTC_KIND_ALL_DTCS); /* @req DCM304 */ if (resultCode == DEM_CONTROL_DTC_STORAGE_OK) { pduTxData->SduDataPtr[1] = 0x01; pduTxData->SduLength = 2; DspDTCSetting.settingDisabled = FALSE; /* @req DCM783 */ (void)Rte_Switch_DcmControlDTCSetting_DcmControlDTCSetting(RTE_MODE_DcmControlDTCSetting_ENABLEDTCSETTING); DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } else { DsdDspProcessingDone(DCM_E_REQUESTOUTOFRANGE); } break; case 0x02: // OFF resultCode = Dem_DisableDTCSetting(DEM_DTC_GROUP_ALL_DTCS, DEM_DTC_KIND_ALL_DTCS); /* @req DCM406 */ if (resultCode == DEM_CONTROL_DTC_STORAGE_OK) { pduTxData->SduDataPtr[1] = 0x02; pduTxData->SduLength = 2; DspDTCSetting.settingDisabled = TRUE; DspDTCSetting.dtcGroup = DEM_DTC_GROUP_ALL_DTCS; DspDTCSetting.dtcKind = DEM_DTC_KIND_ALL_DTCS; /* @req DCM784 */ (void)Rte_Switch_DcmControlDTCSetting_DcmControlDTCSetting(RTE_MODE_DcmControlDTCSetting_DISABLEDTCSETTING); DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } else { DsdDspProcessingDone(DCM_E_REQUESTOUTOFRANGE); } break; default: DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); break; } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #endif #ifdef DCM_USE_SERVICE_RESPONSEONEVENT void DspResponseOnEvent(const PduInfoType *pduRxData, PduIdType rxPduId, PduInfoType *pduTxData) { uint8 eventWindowTime = 0; uint16 eventTypeRecord = 0; uint8 serviceToRespondToLength = 0; uint8 storageState = 0; /* The minimum request includes Sid, Sub function, and event window time */ if (pduRxData->SduLength >= 3) { storageState = pduRxData->SduDataPtr[1] & 0x40; /* Bit 6 */ eventWindowTime = pduRxData->SduDataPtr[2]; switch ( pduRxData->SduDataPtr[1] & 0x3F) { case 0x00: /* Stop */ DsdDspProcessingDone(DCM_ROE_Stop(storageState, eventWindowTime, pduTxData)); break; case 0x01: /* onDTCStatusChanged */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); //Not Implemented break; case 0x02: /* onTimerInterrupt */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); //Not Implemented break; case 0x03: /* OnChangeOfDataIdentifier */ /* @req Dcm522 */ eventTypeRecord = (pduRxData->SduDataPtr[3] << 8) + pduRxData->SduDataPtr[4]; serviceToRespondToLength = pduRxData->SduLength - 5; DsdDspProcessingDone( DCM_ROE_AddDataIdentifierEvent(eventWindowTime, storageState, eventTypeRecord, &pduRxData->SduDataPtr[5], serviceToRespondToLength, pduTxData)); break; case 0x04: /* reportActiveEvents */ DsdDspProcessingDone(DCM_ROE_GetEventList(storageState, pduTxData)); break; case 0x05: /* startResponseOnEvent */ DsdDspProcessingDone(DCM_ROE_Start(storageState, eventWindowTime, rxPduId, pduTxData)); break; case 0x06: /* clearResponseOnEvent */ DsdDspProcessingDone(DCM_ROE_ClearEventList(storageState, eventWindowTime, pduTxData)); break; case 0x07: /* onComparisonOfValue */ DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); //Not Implemented break; default: DsdDspProcessingDone(DCM_E_SUBFUNCTIONNOTSUPPORTED); break; } } else { // Wrong length DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } } #endif void DspDcmConfirmation(PduIdType confirmPduId, NotifResultType result) { DslResetSessionTimeoutTimer(); /* @req DCM141 */ #if (DCM_USE_JUMP_TO_BOOT == STD_ON) if (confirmPduId == dspUdsSessionControlData.sessionPduId) { if( DCM_JTB_RESAPP_FINAL_RESPONSE_TX_CONFIRM == dspUdsSessionControlData.jumpToBootState ) { /* IMPROVEMENT: Add support for pending */ /* @req 4.2.2/SWS_DCM_01179 */ /* @req 4.2.2/SWS_DCM_01180 */ /* @req 4.2.2/SWS_DCM_01181 */ if( NTFRSLT_OK == result ) { if(E_OK == Dcm_SetProgConditions(&GlobalProgConditions)) { (void)Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE); } else { /* Final response has already been sent. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_INTEGRATION_ERROR); } } } dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; } #endif if (confirmPduId == dspUdsEcuResetData.resetPduId) { if ( DCM_DSP_RESET_WAIT_TX_CONF == dspUdsEcuResetData.resetPending) { if( NTFRSLT_OK == result ) { /* IMPROVEMENT: Should be a call to SchM */ (void)Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE);/* @req DCM594 */ } dspUdsEcuResetData.resetPending = DCM_DSP_RESET_NO_RESET; } } if ( TRUE == dspUdsSessionControlData.pendingSessionChange ) { if (confirmPduId == dspUdsSessionControlData.sessionPduId) { if( NTFRSLT_OK == result ) { /* @req DCM311 */ DslSetSesCtrlType(dspUdsSessionControlData.session); } dspUdsSessionControlData.pendingSessionChange = FALSE; } } #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL if(communicationControlData.comControlPending) { if( confirmPduId == communicationControlData.confirmPdu ) { if(NTFRSLT_OK == result) { (void)DspInternalCommunicationControl(communicationControlData.subFunction, communicationControlData.subnet, communicationControlData.comType, communicationControlData.rxPdu, TRUE); } communicationControlData.comControlPending = FALSE; } } #endif } #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) void DspResponsePendingConfirmed(PduIdType confirmPduId) { if ( (DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM == dspUdsSessionControlData.jumpToBootState) || (DCM_JTB_RESAPP_WAIT_RESPONSE_PENDING_TX_CONFIRM == dspUdsSessionControlData.jumpToBootState) ) { if (confirmPduId == dspUdsSessionControlData.sessionPduId) { if( DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM == dspUdsSessionControlData.jumpToBootState ) { /* @req DCM654 */ /* @req DCM535 */ /* IMPROVEMENT: Add support for pending */ Std_ReturnType status = E_NOT_OK; if(E_OK == Dcm_SetProgConditions(&GlobalProgConditions)) { if(E_OK == Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE)) { status = E_OK; } } if( E_OK != status ) { /* @req DCM715 */ DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } dspUdsSessionControlData.jumpToBootState = DCM_JTB_IDLE; } else if (DCM_JTB_RESAPP_WAIT_RESPONSE_PENDING_TX_CONFIRM == dspUdsSessionControlData.jumpToBootState ){ dspUdsSessionControlData.jumpToBootState = DCM_JTB_RESAPP_ASSEMBLE_FINAL_RESPONSE; } else { /* Do nothing */ } } } #if defined(DCM_USE_SERVICE_LINKCONTROL) if( DCM_JTB_WAIT_RESPONSE_PENDING_TX_CONFIRM == dspUdsLinkControlData.jumpToBootState ) { Std_ReturnType status = E_NOT_OK; if(E_OK == Dcm_SetProgConditions(&GlobalProgConditions)) { if(E_OK == Rte_Switch_DcmEcuReset_DcmEcuReset(RTE_MODE_DcmEcuReset_EXECUTE)) { status = E_OK; } } if( E_OK != status ) { /* @req DCM715 */ DsdDspProcessingDone(DCM_E_CONDITIONSNOTCORRECT); } dspUdsLinkControlData.jumpToBootState = DCM_JTB_IDLE; } #endif } #endif static Dcm_NegativeResponseCodeType readMemoryData( Dcm_OpStatusType *OpStatus, uint8 memoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, PduInfoType *pduTxData) { Dcm_ReturnReadMemoryType ReadRet; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; *OpStatus = DCM_INITIAL; /* @req DCM495 */ ReadRet = Dcm_ReadMemory(*OpStatus,memoryIdentifier, MemoryAddress, MemorySize, &pduTxData->SduDataPtr[1]); if(DCM_READ_FAILED == ReadRet) { responseCode = DCM_E_GENERALPROGRAMMINGFAILURE; /*@req Dcm644*/ } if (DCM_READ_PENDING == ReadRet) { *OpStatus = DCM_READ_PENDING; } return responseCode; } static Dcm_NegativeResponseCodeType checkAddressRange(DspMemoryServiceType serviceType, uint8 memoryIdentifier, uint32 memoryAddress, uint32 length) { const Dcm_DspMemoryIdInfo *dspMemoryInfo = Dcm_ConfigPtr->Dsp->DspMemory->DspMemoryIdInfo; const Dcm_DspMemoryRangeInfo *memoryRangeInfo = NULL_PTR; Dcm_NegativeResponseCodeType diagResponseCode = DCM_E_REQUESTOUTOFRANGE; for( ; (dspMemoryInfo->Arc_EOL == FALSE) && (memoryRangeInfo == NULL_PTR); dspMemoryInfo++ ) { if( ((TRUE == Dcm_ConfigPtr->Dsp->DspMemory->DcmDspUseMemoryId) && (dspMemoryInfo->MemoryIdValue == memoryIdentifier)) || (FALSE == Dcm_ConfigPtr->Dsp->DspMemory->DcmDspUseMemoryId) ) { if( DCM_READ_MEMORY == serviceType ) { /* @req DCM493 */ memoryRangeInfo = findRange( dspMemoryInfo->pReadMemoryInfo, memoryAddress, length ); } else { /* @req DCM489 */ memoryRangeInfo = findRange( dspMemoryInfo->pWriteMemoryInfo, memoryAddress, length ); } if( NULL_PTR != memoryRangeInfo ) { /* @req DCM490 */ /* @req DCM494 */ if( DspCheckSecurityLevel(memoryRangeInfo->pSecurityLevel)) { /* Range is ok */ diagResponseCode = DCM_E_POSITIVERESPONSE; } else { diagResponseCode = DCM_E_SECURITYACCESSDENIED; } } else { /* Range was not configured for read/write */ diagResponseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /* No memory with this id found */ diagResponseCode = DCM_E_REQUESTOUTOFRANGE; } } return diagResponseCode; } static const Dcm_DspMemoryRangeInfo* findRange(const Dcm_DspMemoryRangeInfo *memoryRangePtr, uint32 memoryAddress, uint32 length) { const Dcm_DspMemoryRangeInfo *memoryRange = NULL_PTR; for( ; (memoryRangePtr->Arc_EOL == FALSE) && (memoryRange == NULL_PTR); memoryRangePtr++ ) { /*@req DCM493*/ if((memoryAddress >= memoryRangePtr->MemoryAddressLow) && (memoryAddress <= memoryRangePtr->MemoryAddressHigh) && (memoryAddress + length - 1 <= memoryRangePtr->MemoryAddressHigh)) { memoryRange = memoryRangePtr; } } return memoryRange; } void DspUdsWriteMemoryByAddress(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM488 */ Dcm_NegativeResponseCodeType diagResponseCode; uint8 sizeFormat = 0u; uint8 addressFormat = 0u; uint32 memoryAddress = 0u; uint32 length = 0u; uint8 i = 0u; uint8 memoryIdentifier = 0u; /* Should be 0 if DcmDspUseMemoryId == FALSE */ Dcm_OpStatusType OpStatus = DCM_INITIAL; uint8 addressOffset; if( pduRxData->SduLength > ALFID_INDEX ) { sizeFormat = ((uint8)(pduRxData->SduDataPtr[ALFID_INDEX] & DCM_FORMAT_HIGH_MASK)) >> 4; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; addressFormat = ((uint8)(pduRxData->SduDataPtr[ALFID_INDEX])) & DCM_FORMAT_LOW_MASK; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; if((addressFormat != 0) && (sizeFormat != 0)) { if(addressFormat + sizeFormat + SID_LEN + ALFID_LEN <= pduRxData->SduLength) { if( TRUE == Dcm_ConfigPtr->Dsp->DspMemory->DcmDspUseMemoryId ) { memoryIdentifier = pduRxData->SduDataPtr[ADDR_START_INDEX]; addressOffset = 1u; } else { addressOffset = 0u; } /* Parse address */ for(i = addressOffset; i < addressFormat; i++) { memoryAddress <<= 8; memoryAddress += (uint32)(pduRxData->SduDataPtr[ADDR_START_INDEX + i]); } /* Parse size */ for(i = 0; i < sizeFormat; i++) { length <<= 8; length += (uint32)(pduRxData->SduDataPtr[ADDR_START_INDEX + addressFormat + i]); } if( addressFormat + sizeFormat + SID_LEN + ALFID_LEN + length == pduRxData->SduLength ) { diagResponseCode = checkAddressRange(DCM_WRITE_MEMORY, memoryIdentifier, memoryAddress, length); if( DCM_E_POSITIVERESPONSE == diagResponseCode ) { if( (SID_LEN + ALFID_LEN + addressFormat + sizeFormat) <= pduTxData->SduLength ) { diagResponseCode = writeMemoryData(&OpStatus, memoryIdentifier, memoryAddress, length, &pduRxData->SduDataPtr[SID_LEN + ALFID_LEN + addressFormat + sizeFormat]); } else { /* Not enough room in the tx buffer */ diagResponseCode = DCM_E_RESPONSETOOLONG; } } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; /*UDS_REQ_0x23_10*/ } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == diagResponseCode) { pduTxData->SduLength = SID_LEN + ALFID_LEN + addressFormat + sizeFormat; pduTxData->SduDataPtr[ALFID_INDEX] = pduRxData->SduDataPtr[ALFID_INDEX]; for(i = 0; i < addressFormat + sizeFormat; i++) { pduTxData->SduDataPtr[ADDR_START_INDEX + i] = pduRxData->SduDataPtr[ADDR_START_INDEX + i]; if(OpStatus != DCM_WRITE_PENDING) { DsdDspProcessingDone(diagResponseCode); } else { dspMemoryState=DCM_MEMORY_WRITE; } } } else { DsdDspProcessingDone(diagResponseCode); } } void DspUdsReadMemoryByAddress(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM492 */ Dcm_NegativeResponseCodeType diagResponseCode; uint8 sizeFormat; uint8 addressFormat; uint32 memoryAddress = 0; uint32 length = 0; uint8 i; uint8 memoryIdentifier = 0; /* Should be 0 if DcmDspUseMemoryId == FALSE */ Dcm_OpStatusType OpStatus = DCM_INITIAL; uint8 addressOffset; if( pduRxData->SduLength > ALFID_INDEX ) { sizeFormat = ((uint8)(pduRxData->SduDataPtr[ALFID_INDEX] & DCM_FORMAT_HIGH_MASK)) >> 4; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; addressFormat = ((uint8)(pduRxData->SduDataPtr[ALFID_INDEX])) & DCM_FORMAT_LOW_MASK; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; if((addressFormat != 0) && (sizeFormat != 0)) { if(addressFormat + sizeFormat + SID_LEN + ALFID_LEN == pduRxData->SduLength) { if( TRUE == Dcm_ConfigPtr->Dsp->DspMemory->DcmDspUseMemoryId ) { memoryIdentifier = pduRxData->SduDataPtr[ADDR_START_INDEX]; addressOffset = 1; } else { addressOffset = 0; } /* Parse address */ for(i = addressOffset; i < addressFormat; i++) { memoryAddress <<= 8; memoryAddress += (uint32)(pduRxData->SduDataPtr[ADDR_START_INDEX + i]); } /* Parse size */ for(i = 0; i < sizeFormat; i++) { length <<= 8; length += (uint32)(pduRxData->SduDataPtr[ADDR_START_INDEX + addressFormat + i]); } if((length <= (DCM_PROTOCAL_TP_MAX_LENGTH - SID_LEN)) && (length <= (pduTxData->SduLength - SID_LEN)) ) { diagResponseCode = checkAddressRange(DCM_READ_MEMORY, memoryIdentifier, memoryAddress, length); if( DCM_E_POSITIVERESPONSE == diagResponseCode ) { diagResponseCode = readMemoryData(&OpStatus, memoryIdentifier, memoryAddress, length, pduTxData); } } else { diagResponseCode = DCM_E_RESPONSETOOLONG; } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; /*UDS_REQ_0x23_10*/ } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == diagResponseCode) { pduTxData->SduLength = SID_LEN + length; if(OpStatus == DCM_READ_PENDING) { dspMemoryState = DCM_MEMORY_READ; } else { DsdDspProcessingDone(DCM_E_POSITIVERESPONSE); } } else { DsdDspProcessingDone(diagResponseCode); } } static Dcm_NegativeResponseCodeType writeMemoryData(Dcm_OpStatusType* OpStatus, uint8 memoryIdentifier, uint32 MemoryAddress, uint32 MemorySize, uint8 *SourceData) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dcm_ReturnWriteMemoryType writeRet; *OpStatus = DCM_INITIAL; /* @req DCM491 */ writeRet = Dcm_WriteMemory(*OpStatus, memoryIdentifier, MemoryAddress, MemorySize, SourceData); if(DCM_WRITE_FAILED == writeRet) { /* @req DCM643 */ responseCode = DCM_E_GENERALPROGRAMMINGFAILURE; /*@req UDS_REQ_0X3D_16 */ } else if(DCM_WRITE_PENDING == writeRet) { *OpStatus = DCM_PENDING; } else { responseCode = DCM_E_POSITIVERESPONSE; } return responseCode; } #if defined(DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER) && defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) /** * Checks if a periodic Did is setup for periodic transmission * @param PeriodicDid * @return TRUE: PDid setup, FALSE: PDid not setup */ static boolean isInPDidBuffer(uint8 PeriodicDid) { boolean ret = FALSE; for(uint8 i = 0; (i < dspPDidRef.PDidNofUsed) && (ret == FALSE); i++) { if(PeriodicDid == dspPDidRef.dspPDid[i].PeriodicDid) { ret = TRUE; } } return ret; } #endif #ifdef DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER /** * Checks if a periodic Did is setup for transmission on connection * corresponding to the the rxPduId. If so index in PDid buffer is returned * @param PeriodicDid * @param rxPduId * @param postion * @return TRUE: PDid setup, FALSE: PDid not setup */ static boolean checkPeriodicIdentifierBuffer(uint8 PeriodicDid, PduIdType rxPduId, uint8 *postion) { boolean ret = FALSE; for(uint8 i = 0; (i < dspPDidRef.PDidNofUsed) && (ret == FALSE); i++) { if((PeriodicDid == dspPDidRef.dspPDid[i].PeriodicDid) && (rxPduId == dspPDidRef.dspPDid[i].PDidRxPduID)) { ret = TRUE; *postion = i; } } return ret; } /** * Removes a Pdid, for the corresponding rxPduId, from * transmission * @param pDid * @param rxPduId */ static void DspPdidRemove(uint8 pDid, PduIdType rxPduId) { uint8 pos = 0; if( checkPeriodicIdentifierBuffer(pDid, rxPduId, &pos) ) { dspPDidRef.PDidNofUsed--; dspPDidRef.dspPDid[pos].PeriodicDid = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PeriodicDid; dspPDidRef.dspPDid[pos].PDidTxCounter = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxCounter; dspPDidRef.dspPDid[pos].PDidTxPeriod = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxPeriod; dspPDidRef.dspPDid[pos].PDidRxPduID = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidRxPduID; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) dspPDidRef.dspPDid[pos].PdidLength = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidLength; dspPDidRef.dspPDid[pos].PdidSampleStatus = dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidSampleStatus; if( PDID_SAMPLED_OK == dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidSampleStatus ) { memcpy(dspPDidRef.dspPDid[pos].PdidData, dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidData, dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidLength); } dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidLength = 0; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidSampleStatus = PDID_NOT_SAMPLED; #endif dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PeriodicDid = 0; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxCounter = 0; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxPeriod = 0; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidRxPduID = 0; if(dspPDidRef.nextStartIndex >= dspPDidRef.PDidNofUsed) { dspPDidRef.nextStartIndex = 0; } } } /** * Adds a PDid for periodic transmission or updates period if already setup * @param pDid * @param rxPduId * @param periodicTransmitCounter * @return PDID_BUFFER_FULL: Could not add PDid, PDID_ADDED: PDid was added, PDID_UPDATED: Period was updated to already setup PDid */ static PdidEntryStatusType DspPdidAddOrUpdate(uint8 pDid, PduIdType rxPduId, uint32 periodicTransmitCounter) { uint8 indx = 0; PdidEntryStatusType ret = PDID_BUFFER_FULL; if( checkPeriodicIdentifierBuffer(pDid, rxPduId, &indx) ) { if( 0 != periodicTransmitCounter ) { dspPDidRef.dspPDid[indx].PDidTxPeriod = periodicTransmitCounter; dspPDidRef.dspPDid[indx].PDidTxCounter = 0; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) dspPDidRef.dspPDid[indx].PdidSampleStatus = PDID_NOT_SAMPLED; #endif } ret = PDID_UPDATED; } else if(dspPDidRef.PDidNofUsed < DCM_LIMITNUMBER_PERIODDATA) { dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PeriodicDid = pDid; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxCounter = 0; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidTxPeriod = periodicTransmitCounter; dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PDidRxPduID = rxPduId; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) dspPDidRef.dspPDid[dspPDidRef.PDidNofUsed].PdidSampleStatus = PDID_NOT_SAMPLED; #endif dspPDidRef.PDidNofUsed++; ret = PDID_ADDED; } return ret; } #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) /** * Synchronizes PDids for a specific period and rxPduId * @param period * @param rxPduId */ static void DspSynchronizePdids(uint32 period, PduIdType rxPduId) { for(uint8 i = 0; i < dspPDidRef.PDidNofUsed; i++) { if( (dspPDidRef.dspPDid[i].PDidTxPeriod == period) && (dspPDidRef.dspPDid[i].PDidRxPduID == rxPduId) ) { dspPDidRef.dspPDid[i].PDidTxCounter = 0; dspPDidRef.dspPDid[i].PdidSampleStatus = PDID_NOT_SAMPLED; } } } /** * Reads PDid for a specific rxPduId from buffer * @param Pdid * @param rxPduId * @param data * @param dataLength * @return DCM_E_POSITIVERESPONSE: PDid read, DCM_E_REQUESTOUTOFRANGE: PDid not found in buffer or has not been sampled */ static Dcm_NegativeResponseCodeType getPDidDataFromBuffer(uint8 Pdid, PduIdType rxPduId, uint8 *data, uint16 *dataLength) { /* NOTE: Once a PDid is read using this function * the PDid will be marked as not sampled. */ Dcm_NegativeResponseCodeType responseCode = DCM_E_REQUESTOUTOFRANGE; boolean found = FALSE; for(uint8 i = 0; (i < dspPDidRef.PDidNofUsed) && !found; i++) { if( (dspPDidRef.dspPDid[i].PeriodicDid == Pdid) && (dspPDidRef.dspPDid[i].PDidRxPduID == rxPduId)) { found = TRUE; if( PDID_SAMPLED_OK == dspPDidRef.dspPDid[i].PdidSampleStatus ) { memcpy(data, dspPDidRef.dspPDid[i].PdidData, dspPDidRef.dspPDid[i].PdidLength); *dataLength = dspPDidRef.dspPDid[i].PdidLength; dspPDidRef.dspPDid[i].PdidSampleStatus = PDID_NOT_SAMPLED; responseCode = DCM_E_POSITIVERESPONSE; } } } return responseCode; } /** * Samples PDid for a specific period and rxPduId * @param period * @param rxPduId */ static void DspSamplePDids(uint32 period, PduIdType rxPduId) { for(uint8 i = 0; i < dspPDidRef.PDidNofUsed; i++) { if( (dspPDidRef.dspPDid[i].PDidTxPeriod == period) && (dspPDidRef.dspPDid[i].PDidRxPduID == rxPduId) ) { uint16 pdidLength = 0; if( DCM_E_POSITIVERESPONSE == getPDidData(TO_PERIODIC_DID(dspPDidRef.dspPDid[i].PeriodicDid), dspPDidRef.dspPDid[i].PdidData, MAX_PDID_DATA_SIZE, &pdidLength) ) { /* Assuming max length will fit in uint8 to save ram.. */ dspPDidRef.dspPDid[i].PdidLength = (uint8)pdidLength; dspPDidRef.dspPDid[i].PdidSampleStatus = PDID_SAMPLED_OK; } else { dspPDidRef.dspPDid[i].PdidSampleStatus = PDID_SAMPLED_FAILED; } } } } #endif /** * Reads data for a non-dynamic PDid * @param PDidPtr * @param Data * @param Length * @return DCM_E_POSITIVERESPONSE: PDid read OK, DCM_E_REQUESTOUTOFRANGE: PDid read failed */ static Dcm_NegativeResponseCodeType readPeriodDidData(const Dcm_DspDidType *PDidPtr, uint8 *Data, uint16 bufSize, uint16 *Length) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; PduInfoType myPdu; uint16 txPos = 0u; ReadDidPendingStateType pendingState = DCM_READ_DID_IDLE; uint16 pendingDataLen = 0u; uint16 pendingSignalIndex = 0u; uint16 didDataStartPos = 0u; *Length = 0u; if (PDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead != NULL_PTR ) { myPdu.SduDataPtr = Data; myPdu.SduLength = bufSize; responseCode = getDidData(PDidPtr, &myPdu, &txPos, &pendingState, &pendingDataLen, &pendingSignalIndex, &didDataStartPos, FALSE); if( DCM_E_POSITIVERESPONSE == responseCode ) { *Length = txPos; } else if(DCM_E_RESPONSEPENDING == responseCode) { DspCancelPendingDid(PDidPtr->DspDidIdentifier, pendingSignalIndex, pendingState, &myPdu); responseCode = DCM_E_REQUESTOUTOFRANGE; } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } return responseCode; } /** * Removes PDid(s) from transmission * @param pduRxData * @param pduTxData * @param rxPduId */ static void ClearPeriodicIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData, PduIdType rxPduId ) { uint16 PdidNumber; uint8 i; if( pduRxData->SduDataPtr[1] == DCM_PERIODICTRANSMIT_STOPSENDING_MODE ) { PdidNumber = pduRxData->SduLength - 2; for(i = 0u;i < PdidNumber; i++) { DspPdidRemove(pduRxData->SduDataPtr[2 + i], rxPduId); } pduTxData->SduLength = 1; } } /** * Gets the maximum length of a PDid for a transmission type on the active protocol * @param txType * @return */ static uint16 DspGetProtocolMaxPDidLength(Dcm_ProtocolTransTypeType txType) { uint16 maxLength = 0u; Dcm_ProtocolType activeProtocol; if(E_OK == DslGetActiveProtocol(&activeProtocol)) { switch(activeProtocol) { case DCM_OBD_ON_CAN: case DCM_UDS_ON_CAN: case DCM_ROE_ON_CAN: case DCM_PERIODICTRANS_ON_CAN: maxLength = (DCM_PROTOCOL_TRANS_TYPE_2 == txType) ? MAX_TYPE2_PERIODIC_DID_LEN_CAN : MAX_TYPE1_PERIODIC_DID_LEN_CAN; break; case DCM_OBD_ON_FLEXRAY: case DCM_UDS_ON_FLEXRAY: case DCM_ROE_ON_FLEXRAY: case DCM_PERIODICTRANS_ON_FLEXRAY: maxLength = (DCM_PROTOCOL_TRANS_TYPE_2 == txType) ? MAX_TYPE2_PERIODIC_DID_LEN_FLEXRAY : MAX_TYPE1_PERIODIC_DID_LEN_FLEXRAY; break; case DCM_OBD_ON_IP: case DCM_UDS_ON_IP: case DCM_ROE_ON_IP: case DCM_PERIODICTRANS_ON_IP: maxLength = (DCM_PROTOCOL_TRANS_TYPE_2 == txType) ? MAX_TYPE2_PERIODIC_DID_LEN_IP : MAX_TYPE1_PERIODIC_DID_LEN_IP; break; default: break; } } return maxLength; } /** * Checks if a PDid is supported. If supported, the length of the PDid is returned * @param pDid * @param didLength * @param responseCode * @return TRUE: PDid supported, FALSE: PDid not supported */ static boolean checkPDidSupported(uint16 pDid, uint16 *didLength, Dcm_NegativeResponseCodeType *responseCode) { const Dcm_DspDidType *PDidPtr = NULL_PTR; Dcm_DspDDDType *DDidPtr = NULL_PTR; boolean didSupported = FALSE; boolean isDynamicDid = FALSE; if( lookupNonDynamicDid(pDid, &PDidPtr) ) { didSupported = TRUE; } else if(lookupDynamicDid(pDid, &PDidPtr)) { didSupported = TRUE; isDynamicDid = TRUE; } *responseCode = DCM_E_REQUESTOUTOFRANGE; if(didSupported && (NULL_PTR != PDidPtr) && (NULL_PTR != PDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead)) { /* @req DCM721 */ if(DspCheckSessionLevel(PDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSessionRef)) { /* @req DCM722 */ *responseCode = DCM_E_SECURITYACCESSDENIED; if(DspCheckSecurityLevel(PDidPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSecurityLevelRef)) { *responseCode = DCM_E_POSITIVERESPONSE; if( isDynamicDid ) { *responseCode = DCM_E_REQUESTOUTOFRANGE; if( LookupDDD(pDid, (const Dcm_DspDDDType **)&DDidPtr) ) { /* It is a dynamically defined did */ /* @req DCM721 */ /* @req DCM722 */ *responseCode = checkDDDConditions(DDidPtr, didLength); } } } } } return didSupported; } /** * Reads data of a PDid * @param did * @param data * @param dataLength * @return DCM_E_POSITIVERESPONSE: Read OK, other: Read failed */ static Dcm_NegativeResponseCodeType getPDidData(uint16 did, uint8 *data, uint16 bufSize, uint16 *dataLength) { Dcm_NegativeResponseCodeType responseCode; const Dcm_DspDidType *PDidPtr = NULL_PTR; Dcm_DspDDDType *DDidPtr = NULL_PTR; if( lookupNonDynamicDid(did, &PDidPtr) ) { responseCode = readPeriodDidData(PDidPtr, data, bufSize, dataLength); } else if( LookupDDD(did, (const Dcm_DspDDDType **)&DDidPtr) ) { responseCode = readDDDData(DDidPtr, data, bufSize, dataLength); } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } return responseCode; } /** * Implements UDS service 0x2A (readDataByPeriodicIdentifier) * @param pduRxData * @param pduTxData * @param rxPduId * @param txType * @param internalRequest */ void DspReadDataByPeriodicIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData, PduIdType rxPduId, Dcm_ProtocolTransTypeType txType, boolean internalRequest) { /* @req DCM254 */ uint8 PDidLowByte; uint16 PdidNumber; uint32 periodicTransmitCounter = 0u; uint16 DataLength = 0u; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; boolean secAccOK = FALSE; boolean requestOK = FALSE; boolean requestHasSupportedDid = FALSE; uint8 nofPdidsAdded = 0u; uint8 pdidsAdded[DCM_LIMITNUMBER_PERIODDATA]; uint16 maxDidLen = 0u; boolean supressNRC = FALSE; memset(pdidsAdded, 0, DCM_LIMITNUMBER_PERIODDATA); if(pduRxData->SduLength > 2) { switch(pduRxData->SduDataPtr[1]) { case DCM_PERIODICTRANSMIT_DEFAULT_MODE: periodicTransmitCounter = 0; responseCode = internalRequest ? responseCode:DCM_E_REQUESTOUTOFRANGE; break; case DCM_PERIODICTRANSMIT_SLOW_MODE: periodicTransmitCounter = DCM_PERIODICTRANSMIT_SLOW; break; case DCM_PERIODICTRANSMIT_MEDIUM_MODE: periodicTransmitCounter = DCM_PERIODICTRANSMIT_MEDIUM; break; case DCM_PERIODICTRANSMIT_FAST_MODE: periodicTransmitCounter = DCM_PERIODICTRANSMIT_FAST; break; case DCM_PERIODICTRANSMIT_STOPSENDING_MODE: ClearPeriodicIdentifier(pduRxData,pduTxData, rxPduId); break; default: responseCode = DCM_E_REQUESTOUTOFRANGE; break; } if((pduRxData->SduDataPtr[1] != DCM_PERIODICTRANSMIT_STOPSENDING_MODE) && (DCM_E_POSITIVERESPONSE == responseCode)) { maxDidLen = DspGetProtocolMaxPDidLength(txType); PdidNumber = pduRxData->SduLength - 2; /* Check the dids in the request. Must be "small" enough to fit in the response frame. * If there are more dids in the request than we can handle, we only give negative response code * if the number of supported dids in the request are greater than the number of entries left * in our buffer. */ for( uint8 indx = 0u; (indx < PdidNumber) && (DCM_E_POSITIVERESPONSE == responseCode); indx++ ) { PDidLowByte = pduRxData->SduDataPtr[2 + indx]; uint16 didLength = 0u; Dcm_NegativeResponseCodeType resp = DCM_E_POSITIVERESPONSE; if(checkPDidSupported(TO_PERIODIC_DID(PDidLowByte), &didLength, &resp)) { requestHasSupportedDid = TRUE; secAccOK = secAccOK || (DCM_E_SECURITYACCESSDENIED != resp); if((DCM_E_POSITIVERESPONSE == resp) && (didLength <= maxDidLen)) { requestOK = TRUE; PdidEntryStatusType pdidStatus = DspPdidAddOrUpdate(PDidLowByte, rxPduId, periodicTransmitCounter); if( PDID_ADDED == pdidStatus) { pdidsAdded[nofPdidsAdded++] = PDidLowByte; } else if( PDID_BUFFER_FULL == pdidStatus ){ /* Would exceed the maximum number of periodic dids. * Clear the ones added now. */ for( uint8 idx = 0u; idx < nofPdidsAdded; idx++ ) { DspPdidRemove(pdidsAdded[idx], rxPduId); } responseCode = DCM_E_REQUESTOUTOFRANGE; requestOK = FALSE; } else { /* PDid was updated */ } } } } if( requestOK ) { /* Request contained at least one supported DID * accessible in the current session and security level */ if( internalRequest) { /* Internal request, we should transmit */ uint8 dataStartIndex = 1; /* Type 1*/ if( (1 != PdidNumber) || (0 != periodicTransmitCounter) ) { /* Internal request with more than one pdid, not expected */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } if (DCM_PROTOCOL_TRANS_TYPE_2 == txType) { dataStartIndex = 0; memset(pduTxData->SduDataPtr, 0, 8); /* The buffer is always 8 bytes */ } supressNRC = TRUE; #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) responseCode = getPDidDataFromBuffer(PDidLowByte, rxPduId, &pduTxData->SduDataPtr[dataStartIndex + 1], &DataLength); #else responseCode = getPDidData(TO_PERIODIC_DID(PDidLowByte), &pduTxData->SduDataPtr[dataStartIndex + 1], pduTxData->SduLength - dataStartIndex, &DataLength); #endif if(responseCode != DCM_E_POSITIVERESPONSE) { /* NOTE: If a read returns error, should we really remove the did? */ DspPdidRemove(PDidLowByte, rxPduId); } else { pduTxData->SduDataPtr[dataStartIndex] = PDidLowByte; if (DCM_PROTOCOL_TRANS_TYPE_2 == txType) { /* Make sure that unused bytes are 0 */ for(uint16 byteIndex = (DataLength + dataStartIndex + 1); byteIndex < (maxDidLen + dataStartIndex + 1); byteIndex++) { pduTxData->SduDataPtr[byteIndex] = 0; } pduTxData->SduLength = maxDidLen + dataStartIndex + 1; } else { pduTxData->SduLength = DataLength + dataStartIndex + 1; } } } else { #if (DCM_PERIODIC_DID_SYNCH_SAMPLING == STD_ON) /* Something was updated or added. Reset timers for Pdids with this * period to simplify synchronized sampling. */ DspSynchronizePdids(periodicTransmitCounter, rxPduId); #endif pduTxData->SduLength = 1; } } else { if(requestHasSupportedDid && !secAccOK) { /* Request contained supported did(s) but none had access in the current security level */ /* @req DCM721 */ responseCode = DCM_E_SECURITYACCESSDENIED; } else { /* No did available in current session, buffer overflow or no did in request will fit in single frame */ /* @req DCM722 */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } } } else if( (pduRxData->SduLength == 2) && (pduRxData->SduDataPtr[1] == DCM_PERIODICTRANSMIT_STOPSENDING_MODE) ) { memset(&dspPDidRef,0,sizeof(dspPDidRef)); pduTxData->SduLength = 1; } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone_ReadDataByPeriodicIdentifier(responseCode, supressNRC); } #endif #ifdef DCM_USE_SERVICE_DYNAMICALLYDEFINEDATAIDENTIFIER static Dcm_NegativeResponseCodeType dynamicallyDefineDataIdentifierbyDid(uint16 DDIdentifier,const PduInfoType *pduRxData,PduInfoType *pduTxData) { uint8 i; uint16 SourceDidNr; const Dcm_DspDidType *SourceDid = NULL_PTR; Dcm_DspDDDType *DDid = NULL_PTR; uint16 SourceLength = 0u; uint16 DidLength = 0u; uint16 Length = 0u; uint8 Num = 0u; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; const Dcm_DspSignalType *signalPtr; if(FALSE == LookupDDD(DDIdentifier, (const Dcm_DspDDDType **)&DDid)) { while((Num < DCM_MAX_DDD_NUMBER) && (dspDDD[Num].DynamicallyDid != 0 )) { Num++; } if(Num >= DCM_MAX_DDD_NUMBER) { responseCode = DCM_E_REQUESTOUTOFRANGE; } else { DDid = &dspDDD[Num]; } } else { while((SourceLength < DCM_MAX_DDDSOURCE_NUMBER) && (DDid->DDDSource[SourceLength].formatOrPosition != 0 )) { SourceLength++; } } if(responseCode == DCM_E_POSITIVERESPONSE) { Length = (pduRxData->SduLength - SID_AND_DDDID_LEN) /SDI_AND_MS_LEN; if(((Length*SDI_AND_MS_LEN) == (pduRxData->SduLength - SID_AND_DDDID_LEN)) && (Length != 0)) { if((Length + SourceLength) <= DCM_MAX_DDDSOURCE_NUMBER) { for(i = 0;(i < Length) && (responseCode == DCM_E_POSITIVERESPONSE);i++) { SourceDidNr = (((uint16)pduRxData->SduDataPtr[SID_AND_DDDID_LEN + i*SDI_AND_MS_LEN] << 8) & DCM_DID_HIGH_MASK) + (((uint16)pduRxData->SduDataPtr[(5 + i*SDI_AND_MS_LEN)]) & DCM_DID_LOW_MASK); if( lookupNonDynamicDid(SourceDidNr, &SourceDid) && (NULL_PTR != SourceDid->DspDidInfoRef->DspDidAccess.DspDidRead) ) {/*UDS_REQ_0x2C_4*/ /* @req DCM725 */ if(DspCheckSessionLevel(SourceDid->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSessionRef)) { /* @req DCM726 */ if(DspCheckSecurityLevel(SourceDid->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSecurityLevelRef)) { DidLength = 0; uint16 tempSize = 0; for( uint16 sigIndex = 0; (sigIndex < SourceDid->DspNofSignals) && (responseCode == DCM_E_POSITIVERESPONSE); sigIndex++ ) { tempSize = 0; signalPtr = &SourceDid->DspSignalRef[sigIndex]; if( signalPtr->DspSignalDataRef->DspDataInfoRef->DspDidFixedLength || (DATA_PORT_SR == signalPtr->DspSignalDataRef->DspDataUsePort)) { tempSize = GetNofAffectedBytes(signalPtr->DspSignalDataRef->DspDataEndianess, signalPtr->DspSignalBitPosition, signalPtr->DspSignalDataRef->DspDataBitSize); } else if( NULL_PTR != signalPtr->DspSignalDataRef->DspDataReadDataLengthFnc ) { (void)signalPtr->DspSignalDataRef->DspDataReadDataLengthFnc(&tempSize); } tempSize += (signalPtr->DspSignalBitPosition / 8); if( tempSize > DidLength ) { DidLength = tempSize; } } if(DidLength != 0) { if((pduRxData->SduDataPtr[SID_AND_SDI_LEN + i*SDI_AND_MS_LEN] != 0) && (pduRxData->SduDataPtr[SID_AND_PISDR_LEN + i*SDI_AND_MS_LEN] != 0) && (((uint16)pduRxData->SduDataPtr[SID_AND_SDI_LEN + i*SDI_AND_MS_LEN] + (uint16)pduRxData->SduDataPtr[SID_AND_PISDR_LEN + i*SID_AND_DDDID_LEN] - 1) <= DidLength)) { DDid->DDDSource[i + SourceLength].formatOrPosition = pduRxData->SduDataPtr[SID_AND_SDI_LEN + i*SDI_AND_MS_LEN]; DDid->DDDSource[i + SourceLength].Size = pduRxData->SduDataPtr[SID_AND_PISDR_LEN + i*SDI_AND_MS_LEN]; DDid->DDDSource[i + SourceLength].SourceAddressOrDid = SourceDid->DspDidIdentifier; DDid->DDDSource[i + SourceLength].DDDTpyeID = DCM_DDD_SOURCE_DID; } else { /*UDS_REQ_0x2C_6*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /*UDS_REQ_0x2C_14*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_SECURITYACCESSDENIED; } } else { /*UDS_REQ_0x2C_19,DCM726*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /*DCM725*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } } } else { /*UDS_REQ_0x2C_13*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { /*UDS_REQ_0x2C_11*/ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(responseCode == DCM_E_POSITIVERESPONSE) { DDid->DynamicallyDid = DDIdentifier; pduTxData->SduDataPtr[1] = DCM_DDD_SUBFUNCTION_DEFINEBYDID; } } if(responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduDataPtr[1] = DCM_DDD_SUBFUNCTION_DEFINEBYDID; } return responseCode; } static Dcm_NegativeResponseCodeType dynamicallyDefineDataIdentifierbyAddress(uint16 DDIdentifier,const PduInfoType *pduRxData,PduInfoType *pduTxData) { uint16 numNewDefinitions; uint16 numEarlierDefinitions = 0u; Dcm_DspDDDType *DDid = NULL_PTR; uint8 Num = 0u; uint8 definitionIndex; Dcm_NegativeResponseCodeType diagResponseCode = DCM_E_POSITIVERESPONSE; uint8 sizeFormat; uint8 addressFormat; uint32 memoryAddress = 0u; uint32 length = 0u; uint8 i; uint8 memoryIdentifier = 0u; /* Should be 0 if DcmDspUseMemoryId == FALSE */ uint8 addressOffset; if(FALSE == LookupDDD(DDIdentifier, (const Dcm_DspDDDType **)&DDid)) { while((Num < DCM_MAX_DDD_NUMBER) && (dspDDD[Num].DynamicallyDid != 0 )) { Num++; } if(Num >= DCM_MAX_DDD_NUMBER) { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; } else { DDid = &dspDDD[Num]; } } else { while((numEarlierDefinitions < DCM_MAX_DDDSOURCE_NUMBER) && (DDid->DDDSource[numEarlierDefinitions].formatOrPosition != 0 )) { numEarlierDefinitions++; } if(numEarlierDefinitions >= DCM_MAX_DDDSOURCE_NUMBER) { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; } } if( diagResponseCode == DCM_E_POSITIVERESPONSE ) { if( pduRxData->SduLength > DYNDEF_ALFID_INDEX ) { sizeFormat = ((uint8)(pduRxData->SduDataPtr[DYNDEF_ALFID_INDEX] & DCM_FORMAT_HIGH_MASK)) >> 4; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; addressFormat = ((uint8)(pduRxData->SduDataPtr[DYNDEF_ALFID_INDEX])) & DCM_FORMAT_LOW_MASK; /*@req UDS_REQ_0x23_1 & UDS_REQ_0x23_5*/; if((addressFormat != 0) && (sizeFormat != 0)) { numNewDefinitions = (pduRxData->SduLength - (SID_LEN + SF_LEN + DDDDI_LEN + ALFID_LEN) ) / (sizeFormat + addressFormat); if( (numNewDefinitions != 0) && ((SID_LEN + SF_LEN + DDDDI_LEN + ALFID_LEN + numNewDefinitions * (sizeFormat + addressFormat)) == pduRxData->SduLength) ) { if( (numEarlierDefinitions+numNewDefinitions) <= DCM_MAX_DDDSOURCE_NUMBER ) { for( definitionIndex = 0; (definitionIndex < numNewDefinitions) && (diagResponseCode == DCM_E_POSITIVERESPONSE); definitionIndex++ ) { if( TRUE == Dcm_ConfigPtr->Dsp->DspMemory->DcmDspUseMemoryId ) { memoryIdentifier = pduRxData->SduDataPtr[DYNDEF_ADDRESS_START_INDEX + definitionIndex * (sizeFormat + addressFormat)]; addressOffset = 1; } else { addressOffset = 0; } /* Parse address */ memoryAddress = 0u; for(i = addressOffset; i < addressFormat; i++) { memoryAddress <<= 8; memoryAddress += (uint32)(pduRxData->SduDataPtr[DYNDEF_ADDRESS_START_INDEX + definitionIndex * (sizeFormat + addressFormat) + i]); } /* Parse size */ length = 0; for(i = 0; i < sizeFormat; i++) { length <<= 8; length += (uint32)(pduRxData->SduDataPtr[DYNDEF_ADDRESS_START_INDEX + definitionIndex * (sizeFormat + addressFormat) + addressFormat + i]); } diagResponseCode = checkAddressRange(DCM_READ_MEMORY, memoryIdentifier, memoryAddress, length); if( DCM_E_POSITIVERESPONSE == diagResponseCode ) { DDid->DDDSource[definitionIndex + numEarlierDefinitions].formatOrPosition = pduRxData->SduDataPtr[DYNDEF_ALFID_INDEX]; DDid->DDDSource[definitionIndex + numEarlierDefinitions].memoryIdentifier = memoryIdentifier; DDid->DDDSource[definitionIndex + numEarlierDefinitions].SourceAddressOrDid = memoryAddress; DDid->DDDSource[definitionIndex + numEarlierDefinitions].Size = length; DDid->DDDSource[definitionIndex + numEarlierDefinitions].DDDTpyeID = DCM_DDD_SOURCE_ADDRESS; } } if(diagResponseCode == DCM_E_POSITIVERESPONSE) { DDid->DynamicallyDid = DDIdentifier; } else { for( definitionIndex = 0; (definitionIndex < numNewDefinitions); definitionIndex++ ) { DDid->DDDSource[definitionIndex + numEarlierDefinitions].formatOrPosition = 0x00; DDid->DDDSource[definitionIndex + numEarlierDefinitions].memoryIdentifier = 0x00; DDid->DDDSource[definitionIndex + numEarlierDefinitions].SourceAddressOrDid = 0x00000000; DDid->DDDSource[definitionIndex + numEarlierDefinitions].Size = 0x0000; DDid->DDDSource[definitionIndex + numEarlierDefinitions].DDDTpyeID = DCM_DDD_SOURCE_DEFAULT; } } } else { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { diagResponseCode = DCM_E_REQUESTOUTOFRANGE; /*UDS_REQ_0x23_10*/ } } else { diagResponseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } if(diagResponseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduDataPtr[SF_INDEX] = DCM_DDD_SUBFUNCTION_DEFINEBYADDRESS; } return diagResponseCode; } /* DESCRIPTION: UDS Service 0x2c - Clear dynamically Did */ static Dcm_NegativeResponseCodeType ClearDynamicallyDefinedDid(uint16 DDIdentifier,const PduInfoType *pduRxData, PduInfoType * pduTxData) { /*UDS_REQ_0x2C_5*/ sint8 i; uint8 j; Dcm_DspDDDType *DDid = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(pduRxData->SduLength == 4) { if(TRUE == LookupDDD(DDIdentifier, (const Dcm_DspDDDType **)&DDid)) { #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) if((isInPDidBuffer(pduRxData->SduDataPtr[3]) == TRUE) && (pduRxData->SduDataPtr[2] == 0xF2)) { /*UDS_REQ_0x2C_9*/ responseCode = DCM_E_REQUESTOUTOFRANGE; } else #endif { memset(DDid, 0, sizeof(Dcm_DspDDDType)); for(i = DCM_MAX_DDD_NUMBER - 1;i >= 0 ;i--) { /* find the first DDDid from bottom */ if (0 != dspDDD[i].DynamicallyDid) { for (j = 0; j <DCM_MAX_DDD_NUMBER; j++) { /* find the first empty slot from top */ if (j >= i) { /* Rearrange finished */ pduTxData->SduDataPtr[1] = DCM_DDD_SUBFUNCTION_CLEAR; pduTxData->SduLength = 2; return responseCode; } else if (0 == dspDDD[j].DynamicallyDid) { /* find, exchange */ memcpy(&dspDDD[j], (Dcm_DspDDDType*)&dspDDD[i], sizeof(Dcm_DspDDDType)); memset((Dcm_DspDDDType*)&dspDDD[i], 0, sizeof(Dcm_DspDDDType)); }else{ /*do nothing */ } } } } } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; /* DDDid not found */ } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduDataPtr[1] = DCM_DDD_SUBFUNCTION_CLEAR; pduTxData->SduLength = 2; } return responseCode; } void DspDynamicallyDefineDataIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData) { /*UDS_REQ_0x2C_1 */ /* @req DCM259 */ uint16 i; uint16 DDIdentifier; boolean PeriodicUse = FALSE; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; const Dcm_DspDidType *dDidPtr = NULL_PTR; if(pduRxData->SduLength > 2) { /* Check if DDID is in the range 0xF200-0xF3FF */ DDIdentifier = ((((uint16)pduRxData->SduDataPtr[2]) << 8) & DCM_DID_HIGH_MASK) + (pduRxData->SduDataPtr[3] & DCM_DID_LOW_MASK); /* @req DCM723 */ if( lookupDynamicDid(DDIdentifier, &dDidPtr) && (NULL_PTR != dDidPtr) && (NULL_PTR != dDidPtr->DspDidInfoRef->DspDidAccess.DspDidWrite) && DspCheckSessionLevel(dDidPtr->DspDidInfoRef->DspDidAccess.DspDidWrite->DspDidWriteSessionRef)) { /* @req DCM724 */ if( DspCheckSecurityLevel(dDidPtr->DspDidInfoRef->DspDidAccess.DspDidWrite->DspDidWriteSecurityLevelRef) ) { switch(pduRxData->SduDataPtr[1]) { /*UDS_REQ_0x2C_2*//* @req DCM646 */ case DCM_DDD_SUBFUNCTION_DEFINEBYDID: responseCode = dynamicallyDefineDataIdentifierbyDid(DDIdentifier,pduRxData,pduTxData); break; case DCM_DDD_SUBFUNCTION_DEFINEBYADDRESS: responseCode = dynamicallyDefineDataIdentifierbyAddress(DDIdentifier,pduRxData,pduTxData); break; case DCM_DDD_SUBFUNCTION_CLEAR:/* @req DCM647 */ responseCode = ClearDynamicallyDefinedDid(DDIdentifier, pduRxData,pduTxData); break; default: responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; /*UDS_REQ_0x2C_10*/ break; } } else { responseCode = DCM_E_SECURITYACCESSDENIED; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } if(responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduDataPtr[2] = pduRxData->SduDataPtr[2]; pduTxData->SduDataPtr[3] = pduRxData->SduDataPtr[3]; pduTxData->SduLength = 4; } } else if((pduRxData->SduLength == 2)&&(pduRxData->SduDataPtr[1] == DCM_DDD_SUBFUNCTION_CLEAR)) { /*UDS_REQ_0x2C_7*/ #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) for(i = 0;i < DCM_MAX_DDD_NUMBER;i++) { if(isInPDidBuffer((uint8)(dspDDD[i].DynamicallyDid & DCM_DID_LOW_MASK)) == TRUE) { PeriodicUse = TRUE; } } #endif if(PeriodicUse == FALSE) { memset(dspDDD,0,sizeof(dspDDD)); pduTxData->SduDataPtr[1] = DCM_DDD_SUBFUNCTION_CLEAR; pduTxData->SduLength = 2; } else { responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { /*UDS_REQ_0x2C_11*/ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone(responseCode); } #endif #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS) /** * Function for return active control to ECU * @param checkSessionAndSecLevel */ static void DspStopInputOutputControl(boolean checkSessionAndSecLevel) { const Dcm_DspDidControlType *DidControl = NULL_PTR; const Dcm_DspDidType *DidPtr = NULL_PTR; const Dcm_DspSignalType *signalPtr; Dcm_NegativeResponseCodeType responseCode; /* @req DCM628 */ boolean serviceSupported = DsdDspCheckServiceSupportedInActiveSessionAndSecurity(SID_INPUT_OUTPUT_CONTROL_BY_IDENTIFIER); for(uint16 i = 0u; i < DCM_NOF_IOCONTROL_DIDS; i++) { if( IOControlStateList[i].controlActive ) { /* Control not in the hands of the ECU. * Return it. */ if(lookupNonDynamicDid(IOControlStateList[i].did, &DidPtr)) { DidControl = DidPtr->DspDidInfoRef->DspDidAccess.DspDidControl; if(NULL_PTR != DidControl) { boolean returnToECU = TRUE; if(serviceSupported && checkSessionAndSecLevel) { /* Should check if supported in session and security level */ if( DspCheckSessionLevel(DidControl->DspDidControlSessionRef) && DspCheckSecurityLevel(DidControl->DspDidControlSecurityLevelRef) ) { /* Control is supported in current session and security level. * Do not return control to ECU. */ returnToECU = FALSE; } } if( returnToECU ) { /* Return control to the ECU */ for( uint16 sigIndex = 0; sigIndex < DidPtr->DspNofSignals; sigIndex++ ) { if( IOControlStateList[i].activeSignalBitfield[sigIndex/8] & TO_SIGNAL_BIT(sigIndex) ) { signalPtr = &DidPtr->DspSignalRef[sigIndex]; if ((signalPtr->DspSignalDataRef->DspDataUsePort == DATA_PORT_ECU_SIGNAL) && (signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc != NULL_PTR)){ (void)signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc(DCM_RETURN_CONTROL_TO_ECU, NULL_PTR); } else if(signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc != NULL_PTR) { (void)signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc(DCM_INITIAL, &responseCode); } IOControlStateList[i].activeSignalBitfield[sigIndex/8] &= ~(TO_SIGNAL_BIT(sigIndex)); } } IOControlStateList[i].controlActive = FALSE; } else { /* Control is supported in the current session and security level */ } } else { /* No control access. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); IOControlStateList[i].controlActive = FALSE; } } else { /* Did not found in config. Strange.. */ IOControlStateList[i].controlActive = FALSE; DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } } } /** * Function to mark did signals as currently under control. * @param didNr * @param signalAffected * @param active */ static void DspIOControlSetActive(uint16 didNr, Dcm_DspIOControlVector signalAffected, boolean active) { uint16 unusedIndex = DCM_NOF_IOCONTROL_DIDS; uint16 didIndex = DCM_NOF_IOCONTROL_DIDS; boolean indexOK = TRUE; uint16 indx = 0u; for(uint16 i = 0u; (i < DCM_NOF_IOCONTROL_DIDS) && (DCM_NOF_IOCONTROL_DIDS == didIndex); i++) { if(didNr == IOControlStateList[i].did) { didIndex = i; } else if( (DCM_NOF_IOCONTROL_DIDS == unusedIndex) && !IOControlStateList[i].controlActive ) { unusedIndex = i; } } if( DCM_NOF_IOCONTROL_DIDS > didIndex ) { indx = didIndex; } else if( active && (DCM_NOF_IOCONTROL_DIDS > unusedIndex) ) { indx = unusedIndex; } else { indexOK = FALSE; } if( indexOK ) { /* Did was in list or found and unused slot and should activate */ IOControlStateList[indx].controlActive = FALSE; IOControlStateList[indx].did = didNr; for( uint8 byteIndex = 0; byteIndex < sizeof(Dcm_DspIOControlVector); byteIndex++ ) { if( active ) { IOControlStateList[indx].activeSignalBitfield[byteIndex] |= signalAffected[byteIndex]; } else { IOControlStateList[indx].activeSignalBitfield[byteIndex] &= ~(signalAffected[byteIndex]); } if(IOControlStateList[indx].activeSignalBitfield[byteIndex]) { IOControlStateList[indx].controlActive = TRUE; } } } else if( active ) { /* Should set control active but could not find an entry * to use. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } /** * Function used for returning control to ECU for data where * control has been taken over but a positive response has not yet been sent. * @param didNr * @param signalActivated */ static void DspIOControlStopActivated(uint16 didNr, Dcm_DspIOControlVector signalActivated) { const Dcm_DspDidType *DidPtr = NULL_PTR; const Dcm_DspSignalType *signalPtr; Dcm_NegativeResponseCodeType responseCode; boolean done = FALSE; Dcm_DspIOControlVector currentlyActive; memset(currentlyActive, 0, sizeof(Dcm_DspIOControlVector)); if(lookupNonDynamicDid(didNr, &DidPtr)) { for(uint16 i = 0; (i < DCM_NOF_IOCONTROL_DIDS) && !done; i++) { if(didNr == IOControlStateList[i].did) { memcpy(currentlyActive, IOControlStateList[i].activeSignalBitfield, sizeof(Dcm_DspIOControlVector)); done = TRUE; } } } if(NULL_PTR != DidPtr) { for( uint16 sigIndex = 0; sigIndex < DidPtr->DspNofSignals; sigIndex++ ) { if( (0 != (currentlyActive[sigIndex/8] & TO_SIGNAL_BIT(sigIndex))) && (0 != (signalActivated[sigIndex/8] & TO_SIGNAL_BIT(sigIndex))) ) { /* Control was activated and was activated again by current request */ signalPtr = &DidPtr->DspSignalRef[sigIndex]; if ((signalPtr->DspSignalDataRef->DspDataUsePort == DATA_PORT_ECU_SIGNAL) && (signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc != NULL_PTR)){ (void)signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc(DCM_RETURN_CONTROL_TO_ECU, NULL_PTR); } else if(signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc != NULL_PTR) { (void)signalPtr->DspSignalDataRef->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc(DCM_INITIAL, &responseCode); } } } } } /* This is used when the port is USE_ECU_SIGNAL i.e. calling IOHWAB */ static Std_ReturnType EcuSignalInputOutputControl(const Dcm_DspDataType *DataPtr, Dcm_IOControlParameterType action, uint8* controlOptionRecord, Dcm_NegativeResponseCodeType* responseCode) { /* @req DCM580 */ *responseCode = DCM_E_REQUESTOUTOFRANGE; // Value to use if no callback found Std_ReturnType retVal = E_NOT_OK; /* @req DCM579 */ switch(action) { case DCM_RETURN_CONTROL_TO_ECU: if (DataPtr->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc != NULL_PTR) { *responseCode = DCM_E_POSITIVERESPONSE; retVal = DataPtr->DspDataReturnControlToEcuFnc.EcuSignalReturnControlToECUFnc(DCM_RETURN_CONTROL_TO_ECU, NULL_PTR); } break; case DCM_RESET_TO_DEFAULT: if (DataPtr->DspDataResetToDefaultFnc.EcuSignalResetToDefaultFnc != NULL_PTR) { *responseCode = DCM_E_POSITIVERESPONSE; retVal = DataPtr->DspDataResetToDefaultFnc.EcuSignalResetToDefaultFnc(DCM_RESET_TO_DEFAULT, NULL_PTR); } break; case DCM_FREEZE_CURRENT_STATE: if (DataPtr->DspDataFreezeCurrentStateFnc.EcuSignalFreezeCurrentStateFnc != NULL_PTR) { *responseCode = DCM_E_POSITIVERESPONSE; retVal = DataPtr->DspDataFreezeCurrentStateFnc.EcuSignalFreezeCurrentStateFnc(DCM_FREEZE_CURRENT_STATE, NULL_PTR); } break; case DCM_SHORT_TERM_ADJUSTMENT: if (DataPtr->DspDataShortTermAdjustmentFnc.EcuSignalShortTermAdjustmentFnc != NULL_PTR) { *responseCode = DCM_E_POSITIVERESPONSE; retVal = DataPtr->DspDataShortTermAdjustmentFnc.EcuSignalShortTermAdjustmentFnc(DCM_SHORT_TERM_ADJUSTMENT, controlOptionRecord); } break; default: break; } return retVal; } /* This is used when the port is not USE_ECU_SIGNAL */ static Std_ReturnType FunctionInputOutputControl(const Dcm_DspDataType *DataPtr, Dcm_IOControlParameterType action, Dcm_OpStatusType opStatus, uint8* controlOptionRecord, Dcm_NegativeResponseCodeType* responseCode) { *responseCode = DCM_E_REQUESTOUTOFRANGE; // Value to use if no callback found Std_ReturnType retVal = E_NOT_OK; /* @req DCM579 */ switch(action) { case DCM_RETURN_CONTROL_TO_ECU: if(DataPtr->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc != NULL_PTR) { retVal = DataPtr->DspDataReturnControlToEcuFnc.FuncReturnControlToECUFnc(opStatus ,responseCode); } break; case DCM_RESET_TO_DEFAULT: if(DataPtr->DspDataResetToDefaultFnc.FuncResetToDefaultFnc != NULL_PTR) { retVal = DataPtr->DspDataResetToDefaultFnc.FuncResetToDefaultFnc(opStatus ,responseCode); } break; case DCM_FREEZE_CURRENT_STATE: if(DataPtr->DspDataFreezeCurrentStateFnc.FuncFreezeCurrentStateFnc != NULL_PTR) { retVal = DataPtr->DspDataFreezeCurrentStateFnc.FuncFreezeCurrentStateFnc(opStatus ,responseCode); } break; case DCM_SHORT_TERM_ADJUSTMENT: if(DataPtr->DspDataShortTermAdjustmentFnc.FuncShortTermAdjustmentFnc != NULL_PTR) { retVal = DataPtr->DspDataShortTermAdjustmentFnc.FuncShortTermAdjustmentFnc(controlOptionRecord, opStatus, responseCode); } break; default: break; } return retVal; } #endif #ifdef DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER #ifdef DCM_USE_CONTROL_DIDS /** * Runs IO control for a DID * @param DidPtr * @param action * @param Data * @param pendingPtr * @param initOpStatus * @param ctrlEnableMaskPtr * @return */ static Dcm_NegativeResponseCodeType IOControlExecute(const Dcm_DspDidType *DidPtr, Dcm_IOControlParameterType action, uint8 *Data, DspUdsIOControlPendingType *pendingPtr, Dcm_OpStatusType initOpStatus, uint8 *ctrlEnableMaskPtr) { Std_ReturnType retVal = E_OK; Dcm_OpStatusType opStatus = initOpStatus; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; const Dcm_DspSignalType *signalPtr; /* @req DCM680 */ for(uint16 sigIndex = pendingPtr->pendingSignalIndex; (sigIndex < DidPtr->DspNofSignals) && (E_OK == retVal) && (DCM_E_POSITIVERESPONSE == responseCode); sigIndex++) { signalPtr = &DidPtr->DspSignalRef[sigIndex]; /* @req DCM581 */ if( (NULL_PTR == ctrlEnableMaskPtr) || (ctrlEnableMaskPtr[sigIndex/8] & TO_SIGNAL_BIT(sigIndex)) ) { /* @req DCM396 */ /* @req DCM397 */ /* @req DCM398 */ /* @req DCM399 */ if ( signalPtr->DspSignalDataRef->DspDataUsePort == DATA_PORT_ECU_SIGNAL) { retVal = EcuSignalInputOutputControl(signalPtr->DspSignalDataRef, action, &Data[(signalPtr->DspSignalBitPosition / 8)], &responseCode); } else { retVal = FunctionInputOutputControl(signalPtr->DspSignalDataRef, action, opStatus, &Data[(signalPtr->DspSignalBitPosition / 8)], &responseCode); } pendingPtr->state = DCM_GENERAL_IDLE; pendingPtr->pendingSignalIndex = 0; switch(retVal) { case E_OK: pendingPtr->signalAffected[sigIndex/8] |= TO_SIGNAL_BIT(sigIndex); pendingPtr->controlActivated = TRUE; opStatus = DCM_INITIAL; responseCode = DCM_E_POSITIVERESPONSE; break; case E_PENDING: pendingPtr->pendingControl = TRUE; pendingPtr->pendingSignalIndex = sigIndex; pendingPtr->state = DCM_GENERAL_PENDING; responseCode = DCM_E_RESPONSEPENDING; break; case E_NOT_OK: /* Keep response code */ if( DCM_E_POSITIVERESPONSE == responseCode ) { responseCode = DCM_E_REQUESTOUTOFRANGE; } break; default: responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } } return responseCode; } /** * Function used by IO control for reading DID data * @param DidPtr * @param Data * @param pendingPtr * @param initOpStatus * @return */ static Dcm_NegativeResponseCodeType IOControlReadData(const Dcm_DspDidType *DidPtr, uint8 *Data, DspUdsIOControlPendingType *pendingPtr, Dcm_OpStatusType initOpStatus) { /* @req DCM682 */ const Dcm_DspSignalType *signalPtr; Dcm_OpStatusType opStatus = initOpStatus; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType retVal = E_OK; for( uint16 sigIndex = pendingPtr->pendingSignalIndex; (sigIndex < DidPtr->DspNofSignals) && (E_OK == retVal); sigIndex++ ) { signalPtr = &DidPtr->DspSignalRef[sigIndex]; if( signalPtr->DspSignalDataRef->DspDataReadDataFnc.SynchDataReadFnc != NULL_PTR ) { if( (DATA_PORT_SYNCH == signalPtr->DspSignalDataRef->DspDataUsePort) || (DATA_PORT_ECU_SIGNAL == signalPtr->DspSignalDataRef->DspDataUsePort) ) { if( E_OK != signalPtr->DspSignalDataRef->DspDataReadDataFnc.SynchDataReadFnc(&Data[(signalPtr->DspSignalBitPosition / 8)])) { /* Synch port cannot return E_PENDING */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); retVal = E_NOT_OK; } } else if(DATA_PORT_ASYNCH == signalPtr->DspSignalDataRef->DspDataUsePort) { retVal = signalPtr->DspSignalDataRef->DspDataReadDataFnc.AsynchDataReadFnc(opStatus, &Data[(signalPtr->DspSignalBitPosition / 8)]); } else { /* Port not supported */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_CONFIG_INVALID); retVal = E_NOT_OK; } pendingPtr->state = DCM_GENERAL_IDLE; opStatus = DCM_INITIAL; switch(retVal) { case E_OK: break; case E_PENDING: pendingPtr->pendingControl = FALSE; pendingPtr->pendingSignalIndex = sigIndex; pendingPtr->state = DCM_GENERAL_PENDING; responseCode = DCM_E_RESPONSEPENDING; break; case E_NOT_OK: responseCode = DCM_E_CONDITIONSNOTCORRECT; break; default: responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } else { /* No read function */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } return responseCode; } #endif /* DCM_USE_CONTROL_DIDS */ /** * Implements UDS service 0x2F * @param pduRxData * @param pduTxData */ void DspIOControlByDataIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData) { /* @req DCM256 */ #ifdef DCM_USE_CONTROL_DIDS uint16 didSize = 0u; uint16 didNr = 0u; boolean didFound; const Dcm_DspDidType *DidPtr = NULL_PTR; const Dcm_DspDidControlType *DidControl = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dcm_OpStatusType opStatus = DCM_PENDING; if( DCM_GENERAL_IDLE == IOControlData.state ) { IOControlData.pendingSignalIndex = 0u; IOControlData.pendingControl = TRUE; IOControlData.controlActivated = FALSE; memset(IOControlData.signalAffected, 0 , sizeof(IOControlData.signalAffected)); opStatus = DCM_INITIAL; } IOControlData.pduRxData = pduRxData; IOControlData.pduTxData = pduTxData; didNr = (pduRxData->SduDataPtr[IOI_INDEX] << 8 & DCM_DID_HIGH_MASK) + (pduRxData->SduDataPtr[IOI_INDEX+1] & DCM_DID_LOW_MASK); didFound = lookupNonDynamicDid(didNr, &DidPtr); if( TRUE == lookupNonDynamicDid(didNr, &DidPtr) ) { didFound = TRUE; didSize = DidPtr->DspDidDataByteSize; } if( TRUE == IOControlData.pendingControl ) { if(pduRxData->SduLength >= (SID_LEN + IOI_LEN + IOCP_LEN)) { /* @req DCM563 */ /* !req DCM564 */ if(TRUE == didFound) { DidControl = DidPtr->DspDidInfoRef->DspDidAccess.DspDidControl; /* @req DCM565 */ if((NULL_PTR != DidControl) && (DidPtr->DspNofSignals != 0) && IS_VALID_IOCTRL_PARAM(pduRxData->SduDataPtr[IOCP_INDEX])) { /* @req DCM566 */ if(TRUE == DspCheckSessionLevel(DidControl->DspDidControlSessionRef)) { /* @req DCM567 */ if(TRUE == DspCheckSecurityLevel(DidControl->DspDidControlSecurityLevelRef)) { uint8 *maskPtr = NULL_PTR; boolean requestOk = FALSE; uint16 controlOptionSize = (DCM_SHORT_TERM_ADJUSTMENT == pduRxData->SduDataPtr[IOCP_INDEX]) ? DidPtr->DspDidDataByteSize : 0u; uint16 controlEnableMaskSize = (DidPtr->DspNofSignals > 1) ? ((DidPtr->DspNofSignals + 7) / 8) : 0u; requestOk = (pduRxData->SduLength == (SID_LEN + IOI_LEN + IOCP_LEN + controlOptionSize + controlEnableMaskSize)); maskPtr = (DidPtr->DspNofSignals > 1) ? (&pduRxData->SduDataPtr[COR_INDEX + controlOptionSize]) : NULL_PTR; if( requestOk ) { if( pduTxData->SduLength >= (SID_LEN + IOI_LEN + IOCP_LEN + didSize) ) { responseCode = IOControlExecute(DidPtr, pduRxData->SduDataPtr[IOCP_INDEX], &pduRxData->SduDataPtr[COR_INDEX], &IOControlData, opStatus, maskPtr); if( DCM_E_POSITIVERESPONSE == responseCode ) { opStatus = DCM_INITIAL; } } else { /* Tx buffer not big enough */ responseCode = DCM_E_RESPONSETOOLONG; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { responseCode = DCM_E_SECURITYACCESSDENIED; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } if( DCM_E_POSITIVERESPONSE == responseCode ) { pduTxData->SduLength = SID_LEN + IOI_LEN + IOCP_LEN + didSize; pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1];// did pduTxData->SduDataPtr[2] = pduRxData->SduDataPtr[2];// did pduTxData->SduDataPtr[3] = pduRxData->SduDataPtr[IOCP_INDEX]; // IMPROVEMENT: rework this totally: use the read did implementation if( NULL_PTR != DidPtr ) { responseCode = IOControlReadData(DidPtr, &pduTxData->SduDataPtr[4], &IOControlData, opStatus); } } switch(pduRxData->SduDataPtr[IOCP_INDEX]) { case DCM_RETURN_CONTROL_TO_ECU: DspIOControlSetActive(didNr, IOControlData.signalAffected, FALSE); break; case DCM_RESET_TO_DEFAULT: case DCM_FREEZE_CURRENT_STATE: case DCM_SHORT_TERM_ADJUSTMENT: DspIOControlSetActive(didNr, IOControlData.signalAffected, TRUE); break; default: break; } if( DCM_E_POSITIVERESPONSE == responseCode ) { switch(pduRxData->SduDataPtr[IOCP_INDEX]) { case DCM_RETURN_CONTROL_TO_ECU: DspIOControlSetActive(didNr, IOControlData.signalAffected, FALSE); break; case DCM_RESET_TO_DEFAULT: case DCM_FREEZE_CURRENT_STATE: case DCM_SHORT_TERM_ADJUSTMENT: DspIOControlSetActive(didNr, IOControlData.signalAffected, TRUE); break; default: break; } } else if( IOControlData.controlActivated && (DCM_RETURN_CONTROL_TO_ECU != pduRxData->SduDataPtr[IOCP_INDEX]) && (DCM_E_RESPONSEPENDING != responseCode) ) { /* Will give negative response. Disable any control which was activated by this request */ DspIOControlStopActivated(didNr, IOControlData.signalAffected); } if(DCM_E_RESPONSEPENDING != responseCode) { DsdDspProcessingDone(responseCode); } #else /* No control dids configured */ (void)pduTxData; if(pduRxData->SduLength >= (SID_LEN + IOI_LEN + IOCP_LEN)) { DsdDspProcessingDone(DCM_E_REQUESTOUTOFRANGE); } else { DsdDspProcessingDone(DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT); } #endif } #endif #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL /** * Get the rte and dcm modes correcponding to received request * @param subFunction * @param comType * @param rteMode * @param dcmMode * @return E_OK: modes found, E_NOT: Modes NOT found */ Std_ReturnType getCommunicationControlModes(uint8 subFunction, uint8 comType, uint8 *rteMode, Dcm_CommunicationModeType *dcmMode) { const uint8 RteModeMap[UDS_0x28_NOF_COM_TYPES][UDS_0x28_NOF_SUB_FUNCTIONS] = { {RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM, RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORMAL},/* Normal communication */ {RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NM, RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NM},/* Network management communication */ {RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_TX_NORM_NM, RTE_MODE_DcmCommunicationControl_DCM_ENABLE_RX_DISABLE_TX_NORM_NM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_ENABLE_TX_NORM_NM, RTE_MODE_DcmCommunicationControl_DCM_DISABLE_RX_TX_NORM_NM} /* Network management and normal communication */ }; const uint8 DcmModeMap[UDS_0x28_NOF_COM_TYPES][UDS_0x28_NOF_SUB_FUNCTIONS] = { {DCM_ENABLE_RX_TX_NORM, DCM_ENABLE_RX_DISABLE_TX_NORM, DCM_DISABLE_RX_ENABLE_TX_NORM, DCM_DISABLE_RX_TX_NORMAL},/* Normal communication */ {DCM_ENABLE_RX_TX_NM, DCM_ENABLE_RX_DISABLE_TX_NM, DCM_DISABLE_RX_ENABLE_TX_NM, DCM_DISABLE_RX_TX_NM},/* Network management communication */ {DCM_ENABLE_RX_TX_NORM_NM, DCM_ENABLE_RX_DISABLE_TX_NORM_NM, DCM_DISABLE_RX_ENABLE_TX_NORM_NM, DCM_DISABLE_RX_TX_NORM_NM} /* Network management and normal communication */ }; Std_ReturnType ret = E_NOT_OK; if( IS_SUPPORTED_0x28_SUBFUNCTION(subFunction) && IS_VALID_0x28_COM_TYPE(comType) ) { *rteMode = RteModeMap[comType - 1][subFunction]; *dcmMode = DcmModeMap[comType - 1][subFunction]; ret = E_OK; } return ret; } /** * Runs service communication control */ static Dcm_NegativeResponseCodeType DspInternalCommunicationControl(uint8 subFunction, uint8 subNet, uint8 comType, PduIdType rxPduId, boolean executeModeSwitch) { const Dcm_DspComControlAllChannelType *AllChannels; const Dcm_DspComControlSpecificChannelType *SpecificChannels; uint8 rteMode; Dcm_CommunicationModeType dcmMode; Dcm_NegativeResponseCodeType responseCode = DCM_E_REQUESTOUTOFRANGE; if(E_OK == getCommunicationControlModes(subFunction, (comType), &rteMode, &dcmMode)) { if(0xFu == subNet) { /* Channel which request was received on */ /* @req DCM785 */ const Dcm_DslProtocolRxType *protocolRx = NULL_PTR; if( (E_OK == DsdDspGetCurrentProtocolRx(rxPduId, &protocolRx)) && (NULL_PTR != protocolRx) ) { if( executeModeSwitch ) { (void)Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].ModeSwitchFnc(rteMode); DspChannelComMode[protocolRx->ComMChannelInternalIndex] = dcmMode; #if defined(USE_BSWM) BswM_Dcm_CommunicationMode_CurrentState(Dcm_ConfigPtr->DcmComMChannelCfg[protocolRx->ComMChannelInternalIndex].NetworkHandle, dcmMode); #endif } responseCode = DCM_E_POSITIVERESPONSE; } } else { if(NULL_PTR != Dcm_ConfigPtr->Dsp->DspComControl) { if( 0u == subNet ) { /* All channels */ /* @req DCM512 */ AllChannels = Dcm_ConfigPtr->Dsp->DspComControl->DspControlAllChannel; while(!AllChannels->Arc_EOL) { if( executeModeSwitch ) { (void)Dcm_ConfigPtr->DcmComMChannelCfg[AllChannels->ComMChannelIndex].ModeSwitchFnc(rteMode); DspChannelComMode[AllChannels->ComMChannelIndex] = dcmMode; #if defined(USE_BSWM) BswM_Dcm_CommunicationMode_CurrentState(Dcm_ConfigPtr->DcmComMChannelCfg[AllChannels->ComMChannelIndex].NetworkHandle, dcmMode); #endif } AllChannels++; responseCode = DCM_E_POSITIVERESPONSE; } } else { /* Specific channels */ /* @req DCM786 */ SpecificChannels = Dcm_ConfigPtr->Dsp->DspComControl->DspControlSpecificChannel; while(!SpecificChannels->Arc_EOL) { if( subNet == SpecificChannels->SubnetNumber ) { if( executeModeSwitch ) { (void)Dcm_ConfigPtr->DcmComMChannelCfg[SpecificChannels->ComMChannelIndex].ModeSwitchFnc(rteMode); DspChannelComMode[SpecificChannels->ComMChannelIndex] = dcmMode; #if defined(USE_BSWM) BswM_Dcm_CommunicationMode_CurrentState(Dcm_ConfigPtr->DcmComMChannelCfg[SpecificChannels->ComMChannelIndex].NetworkHandle, dcmMode); #endif } responseCode = DCM_E_POSITIVERESPONSE; } SpecificChannels++; } } } } } return responseCode; } /** * Implements UDS service 0x28 (CommunicationControl) * @param pduRxData * @param pduTxData */ void DspCommunicationControl(const PduInfoType *pduRxData,PduInfoType *pduTxData, PduIdType rxPduId, PduIdType txConfirmId) { /* @req DCM511 */ /* !req DCM753 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_REQUESTOUTOFRANGE; uint8 subFunction = pduRxData->SduDataPtr[SF_INDEX]; uint8 subNet; uint8 comType; if(pduRxData->SduLength == 3) { if( IS_SUPPORTED_0x28_SUBFUNCTION(subFunction) ) { subNet = pduRxData->SduDataPtr[CC_CTP_INDEX] >> 4u; comType = pduRxData->SduDataPtr[CC_CTP_INDEX] & 3u; responseCode = DspInternalCommunicationControl(subFunction, subNet, comType, rxPduId, FALSE); if(DCM_E_POSITIVERESPONSE == responseCode) { communicationControlData.comControlPending = TRUE; communicationControlData.subFunction = subFunction; communicationControlData.subnet = subNet; communicationControlData.comType = comType; communicationControlData.confirmPdu = txConfirmId; communicationControlData.rxPdu = rxPduId; } else { communicationControlData.comControlPending = FALSE; } } else { /* ISO reserved for future definition */ responseCode = DCM_E_SUBFUNCTIONNOTSUPPORTED; } } else { /* Length not correct */ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduLength = SID_LEN + SF_LEN; pduTxData->SduDataPtr[SF_INDEX] = pduRxData->SduDataPtr[SF_INDEX]; } DsdDspProcessingDone(responseCode); } #endif #if defined(DCM_USE_SERVICE_REQUESTCURRENTPOWERTRAINDIAGNOSTICDATA) || defined(DCM_USE_SERVICE_REQUESTPOWERTRAINFREEZEFRAMEDATA) static boolean lookupPid(uint8 pidId, Dcm_PidServiceType service, const Dcm_DspPidType **PidPtr) { const Dcm_DspPidType *dspPid = Dcm_ConfigPtr->Dsp->DspPid; boolean pidFound = FALSE; if(dspPid != NULL_PTR) { for ( ;(!dspPid->Arc_EOL); dspPid++) { if ((dspPid->DspPidIdentifier == pidId) && ((DCM_SERVICE_01_02 == dspPid->DspPidService) || (service == dspPid->DspPidService)) && (*dspPid->Arc_DcmPidEnabled == TRUE)) { pidFound = TRUE; *PidPtr = dspPid; /* terminate the loop using break statement */ break; } else { /*do nothing*/ } } } else { /*do nothing*/ } return pidFound; } #endif #if defined(DCM_USE_SERVICE_ONBOARDMONITORINGTESTRESULTSSPECIFICMONITOREDSYSTEMS) /** * Looks up for the OBDMID available in the configuration list(OBD Service $06) * @param obdmid * @param obdmidPtr * @return TRUE (found) or FALSE (not found) */ static boolean lookupObdmid(uint8 obdmid, const Dcm_DspTestResultObdmidType **obdmidPtr) { boolean obdidFound = FALSE; const Dcm_DspTestResultObdmidType *dspObdmid = Dcm_ConfigPtr->Dsp->DspTestResultByObdmid->DspTestResultObdmidTid; if(dspObdmid != NULL_PTR){ do{ if(dspObdmid->DspTestResultObdmid == obdmid){ obdidFound = TRUE; *obdmidPtr = dspObdmid; break; } dspObdmid++; }while(!dspObdmid->Arc_EOL); } return obdidFound; } /** * Fills the 4 byte data according to the result data required by ISO 15031-5 (OBD Service $06) * depending up on the supported OBDMIDs * @param obdmid * @param data * @return TRUE (Updated) or FALSE (No update) */ static boolean setAvailabilityObdmidValue(uint8 obdmid, uint32 *data) { uint8 shift; uint32 obdmidData = 0u; uint32 temp; boolean setOk = FALSE; const Dcm_DspTestResultObdmidType *dspObdmid = Dcm_ConfigPtr->Dsp->DspTestResultByObdmid->DspTestResultObdmidTid; if(dspObdmid != NULL_PTR) { while (0 == dspObdmid->Arc_EOL) { if((dspObdmid->DspTestResultObdmid >= (obdmid + AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MIN)) && /* ISO 15031-5 says to do <= for the below line, but configurator does not supoort it and hence there is elseif part */ (dspObdmid->DspTestResultObdmid < (obdmid + AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MAX))) { shift = dspObdmid->DspTestResultObdmid - obdmid; temp = (uint32)1 << (AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MAX - shift); obdmidData |= temp; } else if(dspObdmid->DspTestResultObdmid > (obdmid + AVAIL_TO_SUPPORTED_OBDMID_OFFSET_MAX)) {/* check any subsequent range */ obdmidData |= (uint32)1; } else { /*do nothing*/ } dspObdmid++; } } if(0 != obdmidData) { setOk = TRUE; } (*data) = obdmidData; /* 0 if not found */ return setOk; } #endif #ifdef DCM_USE_SERVICE_REQUESTCURRENTPOWERTRAINDIAGNOSTICDATA static boolean setAvailabilityPidValue(uint8 Pid, Dcm_PidServiceType service, uint32 *Data) { uint8 shift; uint32 pidData = 0u; uint32 temp; boolean setOk = TRUE; const Dcm_DspPidType *dspPid = Dcm_ConfigPtr->Dsp->DspPid; if(dspPid != NULL_PTR) { while (0 == dspPid->Arc_EOL) { if( (DCM_SERVICE_01_02 == dspPid->DspPidService) || (service == dspPid->DspPidService) ) { if((dspPid->DspPidIdentifier >= (Pid + AVAIL_TO_SUPPORTED_PID_OFFSET_MIN)) && (dspPid->DspPidIdentifier <= (Pid + AVAIL_TO_SUPPORTED_PID_OFFSET_MAX))) { shift = dspPid->DspPidIdentifier - Pid; temp = (uint32)1 << (AVAIL_TO_SUPPORTED_PID_OFFSET_MAX - shift); pidData |= temp; } else if(dspPid->DspPidIdentifier > (Pid + AVAIL_TO_SUPPORTED_PID_OFFSET_MAX)) { pidData |= (uint32)1; } else { /*do nothing*/ } } dspPid++; } } else { setOk = FALSE; } if(0 == pidData) { setOk = FALSE; } else { /*do nothing*/ } (*Data) = pidData; return setOk; } /*@req OBD_DCM_REQ_2*//* @req OBD_REQ_1 */ void DspObdRequestCurrentPowertrainDiagnosticData(const PduInfoType *pduRxData,PduInfoType *pduTxData) { /* !req DCM243 */ /* !req DCM621 */ /* !req DCM622 */ uint16 nofAvailabilityPids = 0u; uint16 findPid = 0u; uint16 txPos = SID_LEN; uint32 DATA = 0u; uint16 txLength = SID_LEN; uint16 pidNum = pduRxData->SduLength - SID_LEN; const Dcm_DspPidType *sourcePidPtr = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; /* @req OBD_REQ_3 */ if((pduRxData->SduLength >= OBD_REQ_MESSAGE_LEN_ONE_MIN) && (pduRxData->SduLength <= OBD_REQ_MESSAGE_LEN_MAX)) { for(uint16 i = 0u; i < pidNum; i++) { /*figure out the txLength to be sent*/ /*situation of availability Pids*/ if( IS_AVAILABILITY_PID(pduRxData->SduDataPtr[i + 1]) ) { nofAvailabilityPids++; /*used to judge if the message is valid, if nofAvailabilityPids != 0 or Pidnum, invalid*/ txLength += PID_LEN + SUPPRTED_PIDS_DATA_LEN; } /*situation of supported Pids*/ else if(TRUE == lookupPid(pduRxData->SduDataPtr[i + 1], DCM_SERVICE_01, &sourcePidPtr)) { txLength += PID_LEN + sourcePidPtr->DspPidSize; } else { /*do nothing*/ } } /*@req OBD_DCM_REQ_7*/ if(txLength <= pduTxData->SduLength) { /*if txLength is smaller than the configured length*/ if(pidNum == nofAvailabilityPids) { /*check if all the request PIDs are the 0x00...0xE0 format*/ /* @req DCM407 */ for(uint16 i = 0;i < pidNum;i++) { /*Check the PID configuration,find which PIDs were configured for 0x00,0x20,0x40 respectively,and fill in the pduTxBuffer,and count the txLength*/ /*@OBD_DCM_REQ_3,@OBD_DCM_REQ_6*/ if(TRUE == setAvailabilityPidValue(pduRxData->SduDataPtr[i + 1], DCM_SERVICE_01, &DATA)) { pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[i + 1]; /*take every byte of uint32 DATA,and fill in txbuffer*/ pduTxData->SduDataPtr[txPos++] = (uint8)(((DATA) & (OBD_DATA_LSB_MASK << OFFSET_THREE_BYTES)) >> OFFSET_THREE_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((DATA) & (OBD_DATA_LSB_MASK << OFFSET_TWO_BYTES)) >> OFFSET_TWO_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((DATA) & (OBD_DATA_LSB_MASK << OFFSET_ONE_BYTE)) >> OFFSET_ONE_BYTE); pduTxData->SduDataPtr[txPos++] = (uint8)((DATA) & OBD_DATA_LSB_MASK); } else if(PIDZERO == pduRxData->SduDataPtr[i + 1]) { pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[i + 1]; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; } else { findPid++; } } } else if(0 == nofAvailabilityPids) { /*check if all the request PIDs are the supported PIDs,like 0x01,0x02...*/ for(uint16 i = 0u; i < pidNum; i++) { if(TRUE == lookupPid(pduRxData->SduDataPtr[i + 1], DCM_SERVICE_01, &sourcePidPtr)) { /*@req OBD_DCM_REQ_3,OBD_DCM_REQ_5,OBD_DCM_REQ_8*//* @req OBD_REQ_2 */ /* !req DCM623 */ if(E_OK == sourcePidPtr->DspGetPidValFnc(&pduTxData->SduDataPtr[txPos+1])) {/* @req DCM408 */ pduTxData->SduDataPtr[txPos] = pduRxData->SduDataPtr[i + 1]; txPos += (sourcePidPtr->DspPidSize + 1); } else { responseCode = DCM_E_CONDITIONSNOTCORRECT; break; } } else { findPid++; } } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(pidNum == findPid) { responseCode = DCM_E_REQUESTOUTOFRANGE; } else { /*do nothing*/ } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == responseCode) { pduTxData->SduLength = txPos; } else { /*do nothing*/ } DsdDspProcessingDone(responseCode); return; } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTPOWERTRAINFREEZEFRAMEDATA) /*@req OBD_DCM_REQ_9*/ void DspObdRequestPowertrainFreezeFrameData(const PduInfoType *pduRxData,PduInfoType *pduTxData) { /* !req DCM244 */ /* @req DCM287 */ uint16 nofAvailabilityPids = 0u; uint16 findPid = 0u; uint32 dtc = 0; uint32 supportBitfield = 0u; uint16 txPos = SID_LEN; uint16 txLength = SID_LEN; uint16 messageLen = pduRxData->SduLength; const Dcm_DspPidType *sourcePidPtr = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; /* @req OBD_REQ_6 */ if((messageLen >= OBD_REQ_MESSAGE_LEN_TWO_MIN ) && (messageLen <= OBD_REQ_MESSAGE_LEN_MAX ) && (((messageLen - 1) % 2) == 0)) { uint16 pidNum = ((messageLen - 1) >> 1); const uint8* PIDAndFramePtr = &pduRxData->SduDataPtr[1]; /*find out PID and FFnum*/ for(uint16 i = 0u; i < pidNum; i++) { /* Calulate tx length */ if(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX] == OBD_SERVICE_TWO) { txLength += PID_LEN + FF_NUM_LEN + OBD_DTC_LEN; } else if( IS_AVAILABILITY_PID(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]) ) { nofAvailabilityPids++; /*used to judge if the message is valid, if nofAvailabilityPids != 0 or Pidnum, invalid*/ txLength += PID_LEN + SUPPRTED_PIDS_DATA_LEN; } else if(TRUE == lookupPid(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX], DCM_SERVICE_02, &sourcePidPtr)) { txLength += PID_LEN + FF_NUM_LEN + sourcePidPtr->DspPidSize; } else { /*do nothing*/ } PIDAndFramePtr += OBD_SERVICE_2_PID_AND_FRAME_SIZE; } /*@req OBD_DCM_REQ_7*/ if(txLength <= (pduTxData->SduLength)) { if(pidNum == nofAvailabilityPids) { /*check if all the request PIDs are the 0x00...0xE0 format*/ PIDAndFramePtr = &pduRxData->SduDataPtr[1]; /* @req DCM284 */ for(uint16 i = 0; i < pidNum; i++) { /*Check the PID configuration,find which PIDs were configured for 0x00,0x20,0x40 respectively,and fill in the pduTxBuffer,and count the txLength*/ if(PIDAndFramePtr[OBD_SERVICE_2_FRAME_INDEX] == RECORD_NUM_ZERO) { /* @req DCM409 */ if(TRUE == setAvailabilityPidValue(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX], DCM_SERVICE_02, &supportBitfield)) { pduTxData->SduDataPtr[txPos++] = PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]; pduTxData->SduDataPtr[txPos++] = RECORD_NUM_ZERO; /*take every byte of uint32 DATA,and fill in txbuffer*/ pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_THREE_BYTES)) >> OFFSET_THREE_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_TWO_BYTES)) >> OFFSET_TWO_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_ONE_BYTE)) >> OFFSET_ONE_BYTE); pduTxData->SduDataPtr[txPos++] = (uint8)((supportBitfield) & OBD_DATA_LSB_MASK); } else if(PIDZERO == PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]) { pduTxData->SduDataPtr[txPos++] = PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]; pduTxData->SduDataPtr[txPos++] = RECORD_NUM_ZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; } else { findPid++; } } else { /*@req OBD_DCM_REQ_11*/ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; break; } PIDAndFramePtr += OBD_SERVICE_2_PID_AND_FRAME_SIZE; } } else if(0 == nofAvailabilityPids) { /*check if all the request PIDs are the supported PIDs,like 0x01,0x02...*/ PIDAndFramePtr = &pduRxData->SduDataPtr[1]; for(uint16 i = 0; i < pidNum; i++) { /*@req OBD_DCM_REQ_10*/ if(PIDAndFramePtr[OBD_SERVICE_2_FRAME_INDEX] == RECORD_NUM_ZERO) { /* @req DCM409 */ uint8 bufSize = 0; if(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX] == OBD_SERVICE_TWO) { /*@req OBD_DCM_REQ_12,@OBD_DCM_REQ_13,@OBD_DCM_REQ_14*/ if(E_OK == Dem_GetDTCOfOBDFreezeFrame(RECORD_NUM_ZERO, &dtc)) { /* @req DCM279 */ pduTxData->SduDataPtr[txPos++] = PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]; pduTxData->SduDataPtr[txPos++] = RECORD_NUM_ZERO; pduTxData->SduDataPtr[txPos++] = (uint8)(((dtc) & (OBD_DATA_LSB_MASK << OFFSET_TWO_BYTES)) >> OFFSET_TWO_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((dtc) & (OBD_DATA_LSB_MASK << OFFSET_ONE_BYTE)) >> OFFSET_ONE_BYTE); } /*if the DTC did not cause the stored FF,DTC of 0x0000 should be returned*/ /* @req OBD_REQ_5 */ else { pduTxData->SduDataPtr[txPos++] = PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]; pduTxData->SduDataPtr[txPos++] = RECORD_NUM_ZERO; pduTxData->SduDataPtr[txPos++] = 0x00; pduTxData->SduDataPtr[txPos++] = 0x00; } } /*req OBD_DCM_REQ_17*/ else { /*@req OBD_DCM_REQ_28*/ pduTxData->SduDataPtr[txPos++] = PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX]; pduTxData->SduDataPtr[txPos++] = RECORD_NUM_ZERO; bufSize = (uint8)(pduTxData->SduLength - txPos); /*@req OBD_DCM_REQ_15,OBD_DCM_REQ_16*//* @req OBD_REQ_4 */ /* IMPROVEMENT: Dem_GetOBDFreezeFrameData should be called for each data element in the * Pid. Parameter DataElementIndexOfPid should be the index of the data element * within the Pid. But currently only one data element per Pid is supported. */ /* @req DCM286 */ if(E_OK == Dem_ReadDataOfOBDFreezeFrame(PIDAndFramePtr[OBD_SERVICE_2_PID_INDEX], DATA_ELEMENT_INDEX_OF_PID_NOT_SUPPORTED, &(pduTxData->SduDataPtr[txPos]), &bufSize)) { txPos += bufSize; } else { txPos -= 2; findPid++; } } } else { /*@req OBD_DCM_REQ_11*/ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; break; } PIDAndFramePtr += OBD_SERVICE_2_PID_AND_FRAME_SIZE; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(pidNum == findPid) { responseCode = DCM_E_REQUESTOUTOFRANGE; } else { /*do nothing*/ } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == responseCode) { pduTxData->SduLength = txPos; } else { /*do nothing*/ } DsdDspProcessingDone(responseCode); return; } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_CLEAREMISSIONRELATEDDIAGNOSTICDATA) /** * Implements OBD service $04 - Clear/Reset emission-related diagnostic information * @param pduRxData * @param pduTxData */ void DspObdClearEmissionRelatedDiagnosticData(const PduInfoType *pduRxData,PduInfoType *pduTxData) { /* !req DCM246 */ uint16 messageLen = pduRxData->SduLength; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(messageLen == SID_LEN ) { /* @req DCM004 */ /* @req DCM413 */ if(DEM_CLEAR_OK == Dem_ClearDTC(DEM_DTC_GROUP_ALL_DTCS, DEM_DTC_FORMAT_OBD, DEM_DTC_ORIGIN_PRIMARY_MEMORY)) { /*do nothing*/ } else { /* @req DCM704 */ /* !req DCM703 */ responseCode = DCM_E_CONDITIONSNOTCORRECT; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == responseCode) { pduTxData->SduLength = SID_LEN; } DsdDspProcessingDone(responseCode); return; } #endif #if defined(USE_DEM) #if defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDIAGNOSTICTROUBLECODES) || \ defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSDETECTEDDURINGCURRENTORLASTCOMPLETEDDRIVINGCYCLE) || \ defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSWITHPERMANENTSTATUS) /** * Reads DTCs from Dem according to diag request * @param pduTxData * @param setDtcFilterResult * @return NRC */ static Dcm_NegativeResponseCodeType OBD_Sevice_03_07_0A(PduInfoType *pduTxData, Dem_ReturnSetFilterType setDtcFilterResult) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if (setDtcFilterResult == DEM_FILTER_ACCEPTED) { uint32 dtc; Dem_EventStatusExtendedType dtcStatus; uint8 nrOfDtcs = 0; uint16 indx = 2; while ((Dem_GetNextFilteredDTC(&dtc, &dtcStatus)) == DEM_FILTERED_OK) { if((indx + LENGTH_OF_DTC) >= (pduTxData->SduLength)) { responseCode = DCM_E_REQUESTOUTOFRANGE; break; } /* @req OBD_REQ_9 */ pduTxData->SduDataPtr[indx] = (uint8)EMISSION_DTCS_HIGH_BYTE(dtc); pduTxData->SduDataPtr[1+indx] = (uint8)EMISSION_DTCS_LOW_BYTE(dtc); indx += LENGTH_OF_DTC; nrOfDtcs++; } /* @req OBD_REQ_8 */ if(responseCode == DCM_E_POSITIVERESPONSE) { pduTxData->SduLength = indx; pduTxData->SduDataPtr[1] = nrOfDtcs; } } else { responseCode = DCM_E_CONDITIONSNOTCORRECT; } return responseCode; } #endif #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDIAGNOSTICTROUBLECODES) /*@req OBD_DCM_REQ_23*//* @req OBD_REQ_7 */ void DspObdRequestEmissionRelatedDiagnosticTroubleCodes(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* !req DCM245 */ uint16 messageLen = pduRxData->SduLength; Dem_ReturnSetFilterType setDtcFilterResult; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(messageLen == SID_LEN ) { /*"confirmed" diagnostic trouble codes*/ /*@req OBD_DCM_REQ_1*/ /*@req OBD_DCM_REQ_24*/ /* @req DCM289 */ setDtcFilterResult = Dem_SetDTCFilter(DEM_CONFIRMED_DTC, DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_OBD, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); responseCode = OBD_Sevice_03_07_0A(pduTxData,setDtcFilterResult); } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone(responseCode); } #endif #if defined(DCM_USE_SERVICE_ONBOARDMONITORINGTESTRESULTSSPECIFICMONITOREDSYSTEMS) /** * Realisation of OBD Service $06, * provides OBD monitoring results for the requested OBDMID with the assist of registered SWCs * Provides Availabilty OBDMID list * loop backed here if dummy mode is ON * @param pduRxData * @param pduTxData * @return none */ void DspObdRequestOnBoardMonitoringTestResultsService06(const PduInfoType *pduRxData,PduInfoType *pduTxData){ /* !req DCM414 */ uint16 i; uint16 nofAvailabilityObdmids = 0u; uint8 unFoundObdmid = 0u; uint16 unFoundTid = 0u; uint16 txPos = SID_LEN; uint32 supportBitfield = 0u; uint16 txLength = SID_LEN; uint16 obdmidNum = pduRxData->SduLength - SID_LEN; const Dcm_DspTestResultObdmidType *sourceObdmidPtr = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; uint16 testval = 0u; uint16 testMinlimit = 0u; uint16 testMaxlimit = 0u; DTRStatusType dtrStatus = 0; if((pduRxData->SduLength >= OBD_REQ_MESSAGE_LEN_ONE_MIN) && (pduRxData->SduLength <= OBD_REQ_MESSAGE_LEN_MAX)) { for(i = 0u; i < obdmidNum; i++) { /*situation of availability Obdmids*/ if( IS_AVAILABILITY_OBDMID(pduRxData->SduDataPtr[OBDMID_DATA_START_INDEX + i]) ) { txLength += OBDMID_LEN + SUPPORTED_OBDMIDS_DATA_LEN; nofAvailabilityObdmids++; } /*situation of supported Obdmids*/ else if(obdmidNum == SUPPORTED_MAX_OBDMID_REQUEST_LEN ) { if(TRUE == lookupObdmid(pduRxData->SduDataPtr[OBDMID_DATA_START_INDEX + i],&sourceObdmidPtr)){ txLength += (sourceObdmidPtr->DspTestResultTidSize * (OBDMID_LEN + SUPPORTED_OBDM_OUTPUT_LEN)); }else { responseCode = DCM_E_REQUESTOUTOFRANGE;/* request for not supported obdmid - (ignore)*/ } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT;/* request for more than one supported OBDMID or mixed request..(ignore) */ } } /* @req DCM415 */ if(responseCode == DCM_E_POSITIVERESPONSE){ /* check request is valid before validating the length */ if(txLength <= pduTxData->SduLength) { /*if txLength is smaller than the configured length*/ if(obdmidNum == nofAvailabilityObdmids) { /*check if all the request OBDMIDs are Availabilty OBDMIDs*/ for(i = 0;i < obdmidNum;i++) { /*Check the OBDMID configuration,find which OBDMIDs were configured for 0x00,0x20,0x40 respectively,and fill in the pduTxBuffer,and count the txLength*/ if(TRUE == setAvailabilityObdmidValue(pduRxData->SduDataPtr[OBDMID_DATA_START_INDEX + i], &supportBitfield)) { pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[OBDMID_DATA_START_INDEX + i]; /*take every byte of supportBitfield,and fill in txbuffer*/ pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_THREE_BYTES)) >> OFFSET_THREE_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_TWO_BYTES)) >> OFFSET_TWO_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)(((supportBitfield) & (OBD_DATA_LSB_MASK << OFFSET_ONE_BYTE)) >> OFFSET_ONE_BYTE); pduTxData->SduDataPtr[txPos++] = (uint8) ((supportBitfield) & (OBD_DATA_LSB_MASK)); } else { unFoundObdmid++; /* no range supported (ignore)*/ } } } /* @req DCM416 */ else {/* Non availabilty OBDMID request*/ if(sourceObdmidPtr != NULL_PTR) { for(i = 0; i < sourceObdmidPtr->DspTestResultTidSize; i++){ if( E_OK == sourceObdmidPtr->DspTestResultObdmidTidRef[i].DspGetDTRValueFnc(opStatus,&testval,&testMinlimit,&testMaxlimit,&dtrStatus)) { if(DCM_DTRSTATUS_VISIBLE == dtrStatus){ pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[OBDMID_DATA_START_INDEX]; pduTxData->SduDataPtr[txPos++] = sourceObdmidPtr->DspTestResultObdmidTidRef[i].DspTestResultTestId; pduTxData->SduDataPtr[txPos++] = sourceObdmidPtr->DspTestResultObdmidTidRef[i].DspTestResultUaSid; pduTxData->SduDataPtr[txPos++] = (uint8)((testval >> OFFSET_ONE_BYTE) & OBDM_LSB_MASK); pduTxData->SduDataPtr[txPos++] = (uint8)(testval & OBDM_LSB_MASK); pduTxData->SduDataPtr[txPos++] = (uint8)((testMinlimit >> OFFSET_ONE_BYTE) & OBDM_LSB_MASK); pduTxData->SduDataPtr[txPos++] = (uint8)(testMinlimit & OBDM_LSB_MASK); pduTxData->SduDataPtr[txPos++] = (uint8)((testMaxlimit >> OFFSET_ONE_BYTE) & OBDM_LSB_MASK); pduTxData->SduDataPtr[txPos++] = (uint8)(testMaxlimit & OBDM_LSB_MASK); } else{ /* else ignore updating the result */ unFoundTid++; /* not visible */ } }else{ unFoundTid++; /* Wrong response though not intended */ } } if(sourceObdmidPtr->DspTestResultTidSize == unFoundTid) { /* Response for the test results from the registered application/s are either seems NOT OK */ responseCode = DCM_E_CONDITIONSNOTCORRECT; /* (or) DTRStatus seems DCM_DTRSTATUS_INVISIBLE for all the requests */ } } } if(obdmidNum == unFoundObdmid) { /* No obdMid found */ responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; /*if txLength is not smaller than the configured length*/ } } } else { /* Invalid message */ responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == responseCode){ pduTxData->SduLength = txPos; } DsdDspProcessingDone(responseCode); return; } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSDETECTEDDURINGCURRENTORLASTCOMPLETEDDRIVINGCYCLE) /*@req OBD_DCM_REQ_25*//* @req OBD_REQ_12 */ void DspObdRequestEmissionRelatedDiagnosticTroubleCodesService07(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* !req DCM410 */ uint16 messageLen = pduRxData->SduLength; Dem_ReturnSetFilterType setDtcFilterResult; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(messageLen == SID_LEN ) { /*"pending" diagnostic trouble codes*/ /*@req OBD_DCM_REQ_1*/ /*@req OBD_DCM_REQ_26*/ /* @req DCM412 */ setDtcFilterResult = Dem_SetDTCFilter(DEM_PENDING_DTC, DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_OBD, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); responseCode = OBD_Sevice_03_07_0A(pduTxData,setDtcFilterResult); } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone(responseCode); return; } #endif #ifdef DCM_USE_SERVICE_REQUESTVEHICLEINFORMATION static boolean lookupInfoType(uint8 InfoType, const Dcm_DspVehInfoType **InfoTypePtr) { const Dcm_DspVehInfoType *dspVehInfo = Dcm_ConfigPtr->Dsp->DspVehInfo; boolean InfoTypeFound = FALSE; while ((dspVehInfo->DspVehInfoType != InfoType) && ((dspVehInfo->Arc_EOL) == FALSE)) { dspVehInfo++; } if ((dspVehInfo->Arc_EOL) == FALSE) { InfoTypeFound = TRUE; *InfoTypePtr = dspVehInfo; } return InfoTypeFound; } static boolean setAvailabilityInfoTypeValue(uint8 InfoType, uint32 *DATABUF) { uint8 shift; uint32 databuf = 0u; uint32 temp; boolean setInfoTypeOk = TRUE; const Dcm_DspVehInfoType *dspVehInfo = Dcm_ConfigPtr->Dsp->DspVehInfo; if(dspVehInfo != NULL_PTR) { while ((dspVehInfo->DspVehInfoType != FALSE) && ((dspVehInfo->Arc_EOL) == FALSE)) { if((dspVehInfo->DspVehInfoType >= (InfoType + AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MIN)) && (dspVehInfo->DspVehInfoType <= (InfoType + AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MAX))) { shift = dspVehInfo->DspVehInfoType - InfoType; temp = (uint32)1 << (AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MAX - shift); databuf |= temp; } else if( dspVehInfo->DspVehInfoType > (InfoType + AVAIL_TO_SUPPORTED_INFOTYPE_OFFSET_MAX)) { databuf |= (uint32)0x01; } else { /*do nothing*/ } dspVehInfo++; } if(databuf == 0) { setInfoTypeOk = FALSE; } else { /*do nothing*/ } } else { setInfoTypeOk = FALSE; } (*DATABUF) = databuf; return setInfoTypeOk; } /** * Function for reading VIT data * @param VIT * @param dataBuffer * @param sourceVehInfoPtr * @return E_OK: Read OK, E_NOT_OK: Read failed */ static Std_ReturnType readVITData(const uint8 VIT, uint8 *dataBuffer, const Dcm_DspVehInfoType *sourceVehInfoPtr) { Std_ReturnType ret = E_OK; uint16 dataPos = 0u; const Dcm_DspVehInfoDataType *dataItems = sourceVehInfoPtr->DspVehInfoDataItems; for( uint8 dataIdx = 0u; (dataIdx < sourceVehInfoPtr->DspVehInfoNumberOfDataItems) && (E_OK == ret); dataIdx++ ) { /* @req DCM423 */ if (dataItems[dataIdx].DspGetVehInfoTypeFnc(&dataBuffer[dataPos]) != E_OK) { if( VIT == 0x02 ) { /* Special for read VIN fail, customer's requirement*/ memset(&dataBuffer[dataPos], 0xFF, dataItems[dataIdx].DspVehInfoSize); } else { ret = E_NOT_OK; } } dataPos += dataItems[dataIdx].DspVehInfoSize; } return ret; } /*@req OBD_DCM_REQ_27*//*@req OBD_REQ_13*/ void DspObdRequestVehicleInformation(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* !req DCM421 */ uint8 nofAvailabilityInfoTypes = 0u; uint16 txPos = SID_LEN; uint32 DATABUF; uint8 findNum = 0u; uint16 InfoTypeNum = pduRxData->SduLength - 1u; const Dcm_DspVehInfoType *sourceVehInfoPtr = NULL_PTR; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; /*@req OBD_REQ_14*/ if((pduRxData->SduLength >= OBD_REQ_MESSAGE_LEN_ONE_MIN) && (pduRxData->SduLength <= OBD_REQ_MESSAGE_LEN_MAX )) { for( uint16 i = 0u; i < InfoTypeNum; i++ ) { if( IS_AVAILABILITY_INFO_TYPE(pduRxData->SduDataPtr[i + 1]) ) { nofAvailabilityInfoTypes++; } } /*@req OBD_DCM_REQ_29*/ if(InfoTypeNum == nofAvailabilityInfoTypes) { /*check if all the request PIDs are the 0x00...0xE0 format*/ /* @req DCM422 */ for(uint16 i = 0u; i < InfoTypeNum; i++) { /*Check the PID configuration,find which PIDs were configured for 0x00,0x20,0x40 respectively,and fill in the pduTxBuffer,and count the txLength*/ if(TRUE == setAvailabilityInfoTypeValue(pduRxData->SduDataPtr[i + 1], &DATABUF)) { pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[i + 1]; /*take every byte of uint32 DTC,and fill in txbuffer*/ pduTxData->SduDataPtr[txPos++] = (uint8)((DATABUF & (OBD_DATA_LSB_MASK << OFFSET_THREE_BYTES)) >> OFFSET_THREE_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)((DATABUF & (OBD_DATA_LSB_MASK << OFFSET_TWO_BYTES)) >> OFFSET_TWO_BYTES); pduTxData->SduDataPtr[txPos++] = (uint8)((DATABUF & (OBD_DATA_LSB_MASK << OFFSET_ONE_BYTE)) >> OFFSET_ONE_BYTE); pduTxData->SduDataPtr[txPos++] = (uint8)(DATABUF & OBD_DATA_LSB_MASK); } else if(INFOTYPE_ZERO == pduRxData->SduDataPtr[i + 1]) { pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[i + 1]; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; pduTxData->SduDataPtr[txPos++] = DATAZERO; } else { findNum++; } } } /*@req OBD_DCM_REQ_28*/ else if(nofAvailabilityInfoTypes == 0) { /*check if all the request PIDs are the supported VINs,like 0x01,0x02...*/ /*@req OBD_REQ_15*/ if(pduRxData->SduLength == OBD_REQ_MESSAGE_LEN_ONE_MIN) { if(TRUE == lookupInfoType(pduRxData->SduDataPtr[1], &sourceVehInfoPtr )) { if( pduTxData->SduLength >= (3u + sourceVehInfoPtr->DspVehInfoTotalSize) ) {/* 3 = SID */ /* Insert Info type in response */ pduTxData->SduDataPtr[txPos++] = pduRxData->SduDataPtr[1]; /* Insert the number of data items in the response */ /*@req OBD_DCM_REQ_30*/ pduTxData->SduDataPtr[txPos++] = sourceVehInfoPtr->DspVehInfoNumberOfDataItems;/* @req DCM684 */ if( E_OK != readVITData(pduRxData->SduDataPtr[1], &pduTxData->SduDataPtr[txPos], sourceVehInfoPtr) ) { responseCode = DCM_E_CONDITIONSNOTCORRECT; } else { txPos += sourceVehInfoPtr->DspVehInfoTotalSize; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { findNum++; } } /*@req OBD_REQ_16*/ else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(findNum == InfoTypeNum) { responseCode = DCM_E_REQUESTOUTOFRANGE; } else { /* do nothing */ } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if(DCM_E_POSITIVERESPONSE == responseCode) { pduTxData->SduLength = txPos; } else { /* do nothing */ } DsdDspProcessingDone(responseCode); } #endif #if defined(USE_DEM) && defined(DCM_USE_SERVICE_REQUESTEMISSIONRELATEDDTCSWITHPERMANENTSTATUS) /** * Implements OBD service $0A * @param pduRxData * @param pduTxData */ void DspObdRequestEmissionRelatedDiagnosticTroubleCodesWithPermanentStatus(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* !req DCM411 */ uint16 messageLen = pduRxData->SduLength; Dem_ReturnSetFilterType setDtcFilterResult; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(messageLen == SID_LEN ) { /*"confirmed" diagnostic trouble codes*/ /* @req DCM330 */ setDtcFilterResult = Dem_SetDTCFilter(DEM_DTC_STATUS_MASK_ALL, DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_OBD, DEM_DTC_ORIGIN_PERMANENT_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, VALUE_IS_NOT_USED, DEM_FILTER_FOR_FDC_NO); responseCode = OBD_Sevice_03_07_0A(pduTxData,setDtcFilterResult); } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } DsdDspProcessingDone(responseCode); } #endif uint32 DspRoutineInfoReadUnsigned(uint8 *data, uint16 bitOffset, uint8 size, boolean changeEndian) { uint32 retVal = 0u; const uint16 little_endian = 0x1u; if(size > 32) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_CONFIG_INVALID); return 0; } if((uint8)changeEndian ^ *((uint8*)&little_endian)) { // read little endian for(int i = 0; i < size / 8; i++) { retVal = (retVal << 8) | (data+bitOffset/8 + size/8 - 1)[-i]; } } else { // read big endian for(int i = 0; i < size / 8; i++) { retVal = (retVal << 8) | (data+bitOffset/8)[i]; } } return retVal; } sint32 DspRoutineInfoRead(uint8 *data, uint16 bitOffset, uint8 size, boolean changeEndian) { uint32 retVal = DspRoutineInfoReadUnsigned(data, bitOffset, size, changeEndian); uint32 mask = 0xFFFFFFFFul << (size - 1); if(retVal & mask) { // result is negative retVal &= mask; } return (sint32)retVal; } void DspRoutineInfoWrite(uint32 val, uint8 *data, uint16 bitOffset, uint8 size, boolean changeEndian) { const uint16 little_endian = 0x1u; if((uint8)changeEndian ^ *((uint8*)&little_endian)) { // write little endian for(int i = 0; i < size / 8; i++) { (data+bitOffset/8)[i] = 0xFF & val; val = val >> 8; } } else { for(int i = 0; i < size / 8; i++) { (data+(bitOffset + size)/8 - 1)[-i] = 0xFF & val; val = val >> 8; } } } #ifdef DCM_USE_SERVICE_REQUESTDOWNLOAD void DspUdsRequestDownload(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM496 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType ret; uint32 memoryAddress = 0u; uint32 memorySize = 0u; uint32 blockSize = 0u; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsUploadDownloadPending, &opStatus, FALSE); if(pduRxData->SduLength >= 5) { uint8 dataFormatIdentifier = pduRxData->SduDataPtr[1]; uint8 nofSizeBytes = ((uint8)(pduRxData->SduDataPtr[2] & DCM_FORMAT_HIGH_MASK)) >> 4; uint8 nofAddrBytes = ((uint8)(pduRxData->SduDataPtr[2])) & DCM_FORMAT_LOW_MASK; if( pduRxData->SduLength == (3 + nofSizeBytes + nofAddrBytes) && (0 < nofSizeBytes) && (4 >= nofSizeBytes) && (0 < nofAddrBytes) && (4 >= nofAddrBytes)) { for(uint8 idx = 0; idx < nofAddrBytes; idx++) { memoryAddress <<= 8; memoryAddress += (pduRxData->SduDataPtr[3 + idx]); } for(uint8 idx = 0; idx < nofSizeBytes; idx++) { memorySize <<= 8; memorySize += (pduRxData->SduDataPtr[3 + nofAddrBytes + idx]); } if( DCM_INITIAL == opStatus ) { ret = Dcm_ProcessRequestDownload(opStatus, dataFormatIdentifier, memoryAddress, memorySize, &blockSize, &responseCode); } else { ret = Dcm_ProcessRequestDownload(opStatus, 0, 0, 0, &blockSize, &responseCode); } switch (ret) { case E_OK: pduTxData->SduDataPtr[1] = 0x40; pduTxData->SduDataPtr[2] = (uint8)((blockSize>>24) & 0xff); pduTxData->SduDataPtr[3] = (uint8)((blockSize>>16) & 0xff); pduTxData->SduDataPtr[4] = (uint8)((blockSize>>8) & 0xff); pduTxData->SduDataPtr[5] = (uint8)(blockSize & 0xff); pduTxData->SduLength = 6; responseCode = DCM_E_POSITIVERESPONSE; TransferStatus.transferType = DCM_DOWNLOAD; TransferStatus.blockSequenceCounter = 1; TransferStatus.firstBlockReceived = FALSE; TransferStatus.nextAddress = memoryAddress; break; case E_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; case E_FORCE_RCRRP: responseCode = DCM_E_FORCE_RCRRP; break; case E_NOT_OK: /* @req DCM757 */ break; default: DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsUploadDownloadPending.state = DCM_GENERAL_PENDING; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_DOWNLOAD; } else if(DCM_E_FORCE_RCRRP == responseCode) { dspUdsUploadDownloadPending.state = DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_DOWNLOAD; DsdDspForceResponsePending(); } else { dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } } #endif #ifdef DCM_USE_SERVICE_REQUESTUPLOAD /** * @brief The client requests the negotiation of a data transfer from the server to the client. * * @param[in] pduRxData Received PDU data. * @param[out] pduTxData PDU data to be transfered. * */ void DspUdsRequestUpload(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM499 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType ret; uint32 memoryAddress = 0u; uint32 memorySize = 0u; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; uint32 maxNumberOfBlockLength; SetOpStatusDependingOnState(&dspUdsUploadDownloadPending, &opStatus, FALSE); if(pduRxData->SduLength >= 5) { uint8 dataFormatIdentifier = pduRxData->SduDataPtr[1]; uint8 nofSizeBytes = ((uint8)(pduRxData->SduDataPtr[2] & DCM_FORMAT_HIGH_MASK)) >> 4; uint8 nofAddrBytes = ((uint8)(pduRxData->SduDataPtr[2])) & DCM_FORMAT_LOW_MASK; if( pduRxData->SduLength == (3 + nofSizeBytes + nofAddrBytes) && (0 < nofSizeBytes) && (4 >= nofSizeBytes) && (0 < nofAddrBytes) && (4 >= nofAddrBytes)) { for(uint8 idx = 0; idx < nofAddrBytes; idx++) { memoryAddress <<= 8; memoryAddress += (pduRxData->SduDataPtr[3 + idx]); } for(uint8 idx = 0; idx < nofSizeBytes; idx++) { memorySize <<= 8; memorySize += (pduRxData->SduDataPtr[3 + nofAddrBytes + idx]); TransferStatus.uplBytesLeft = memorySize; } if( DCM_INITIAL == opStatus ) { ret = Dcm_ProcessRequestUpload(opStatus, dataFormatIdentifier, memoryAddress, memorySize, &responseCode); } else { ret = Dcm_ProcessRequestUpload(opStatus, 0, 0, 0, &responseCode); } switch (ret) { case E_OK: maxNumberOfBlockLength = (uint32) pduTxData->SduLength; pduTxData->SduDataPtr[1] = 0x40; pduTxData->SduDataPtr[2] = (uint8)((maxNumberOfBlockLength>>24) & 0xff); pduTxData->SduDataPtr[3] = (uint8)((maxNumberOfBlockLength>>16) & 0xff); pduTxData->SduDataPtr[4] = (uint8)((maxNumberOfBlockLength>>8) & 0xff); pduTxData->SduDataPtr[5] = (uint8)(maxNumberOfBlockLength & 0xff); pduTxData->SduLength = 6; responseCode = DCM_E_POSITIVERESPONSE; TransferStatus.transferType = DCM_UPLOAD; TransferStatus.blockSequenceCounter = 1; TransferStatus.firstBlockReceived = FALSE; TransferStatus.nextAddress = memoryAddress; TransferStatus.uplMemBlockSize = maxNumberOfBlockLength -2; break; case E_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; case E_FORCE_RCRRP: responseCode = DCM_E_FORCE_RCRRP; break; case E_NOT_OK: /* @req DCM758 */ break; default: DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsUploadDownloadPending.state = DCM_GENERAL_PENDING; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_UPLOAD; } else if(DCM_E_FORCE_RCRRP == responseCode) { dspUdsUploadDownloadPending.state = DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_UPLOAD; DsdDspForceResponsePending(); } else { dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } } } #endif #ifdef DCM_USE_SERVICE_TRANSFERDATA void DspUdsTransferData(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM502 */ uint16 respParamRecLen; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsUploadDownloadPending, &opStatus, FALSE); Dcm_ReturnReadMemoryType readRet; Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; if(DCM_NO_DATA_TRANSFER != TransferStatus.transferType) { if((pduRxData->SduLength >= 2 && DCM_UPLOAD == TransferStatus.transferType) || (pduRxData->SduLength >= 3 && DCM_DOWNLOAD == TransferStatus.transferType) ) { respParamRecLen = pduTxData->SduLength - 2; if( (pduRxData->SduDataPtr[1] == TransferStatus.blockSequenceCounter)) { if( DCM_DOWNLOAD == TransferStatus.transferType ) { Dcm_ReturnWriteMemoryType writeRet; /* @req DCM503 */ if( DCM_INITIAL == opStatus ) { writeRet = Dcm_WriteMemory(opStatus, 0, TransferStatus.nextAddress, pduRxData->SduLength - 2, &pduRxData->SduDataPtr[2]); } else { writeRet = Dcm_WriteMemory(opStatus, 0, 0, 0, 0); } switch(writeRet) { case DCM_WRITE_OK: TransferStatus.blockSequenceCounter++; TransferStatus.firstBlockReceived = TRUE; TransferStatus.nextAddress += pduRxData->SduLength - 2; pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; Dcm_Arc_GetDownloadResponseParameterRecord(&pduTxData->SduDataPtr[2], &respParamRecLen); pduTxData->SduLength = 2 + respParamRecLen; break; case DCM_WRITE_FORCE_RCRRP: responseCode = DCM_E_FORCE_RCRRP; break; case DCM_WRITE_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; default: responseCode = DCM_E_GENERALPROGRAMMINGFAILURE;/* @req DCM643 */ break; } } else if ( DCM_UPLOAD == TransferStatus.transferType ) { uint32 readMemSize = 0; /* @req DCM504 */ if( DCM_INITIAL == opStatus ) { readMemSize = MIN((TransferStatus.uplMemBlockSize), (TransferStatus.uplBytesLeft)); readRet = Dcm_ReadMemory(opStatus, 0, TransferStatus.nextAddress, readMemSize, &pduTxData->SduDataPtr[2]); } else { readRet = Dcm_ReadMemory(opStatus, 0, 0, 0, 0); } switch(readRet) { case DCM_READ_OK: TransferStatus.firstBlockReceived = TRUE; /* I know, it should be block send, but we reuse the same control flag */ TransferStatus.nextAddress += readMemSize; TransferStatus.uplBytesLeft -= readMemSize; respParamRecLen = readMemSize; pduTxData->SduDataPtr[1] = TransferStatus.blockSequenceCounter; TransferStatus.blockSequenceCounter++; pduTxData->SduLength = 2 + respParamRecLen; break; case DCM_READ_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; default: responseCode = DCM_E_GENERALREJECT; /* @req DCM644 */ break; } } else { responseCode = DCM_E_REQUESTOUTOFRANGE; } } else { uint8 okCounter; if(0 == TransferStatus.blockSequenceCounter) { okCounter = 0xFF; } else { okCounter = TransferStatus.blockSequenceCounter - 1; } /* Allow the same sequence counter again (but do nothing) as long as we have received the first block. */ /* @req DCM645 */ if ( (FALSE == TransferStatus.firstBlockReceived) || (pduRxData->SduDataPtr[1] != okCounter) ) { responseCode = DCM_E_WRONGBLOCKSEQUENCECOUNTER; } else { pduTxData->SduDataPtr[1] = pduRxData->SduDataPtr[1]; if( DCM_DOWNLOAD == TransferStatus.transferType ) { Dcm_Arc_GetDownloadResponseParameterRecord(&pduTxData->SduDataPtr[2], &respParamRecLen); } else if ( DCM_UPLOAD == TransferStatus.transferType ) { readRet = Dcm_ReadMemory(opStatus, 0, TransferStatus.nextAddress, MIN((TransferStatus.uplMemBlockSize), (TransferStatus.uplBytesLeft)), &pduTxData->SduDataPtr[2]); switch(readRet) { case DCM_READ_OK: break; case DCM_READ_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; default: responseCode = DCM_E_GENERALREJECT; /* @req DCM644 */ break; } } pduTxData->SduLength = 2 + respParamRecLen; } } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } } else { responseCode = DCM_E_REQUESTSEQUENCEERROR; } if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsUploadDownloadPending.state = DCM_GENERAL_PENDING; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_TRANSFER_DATA; } else if(DCM_E_FORCE_RCRRP == responseCode) { dspUdsUploadDownloadPending.state = DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_TRANSFER_DATA; DsdDspForceResponsePending(); } else { dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } } #endif #ifdef DCM_USE_SERVICE_REQUESTTRANSFEREXIT void DspUdsRequestTransferExit(const PduInfoType *pduRxData, PduInfoType *pduTxData) { /* @req DCM505 */ Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; Std_ReturnType ret; Dcm_OpStatusType opStatus = (Dcm_OpStatusType)DCM_INITIAL; SetOpStatusDependingOnState(&dspUdsUploadDownloadPending, &opStatus, FALSE); if(pduRxData->SduLength >= 1) { if( DCM_NO_DATA_TRANSFER != TransferStatus.transferType ) { if( DCM_INITIAL == opStatus ) { ret = Dcm_ProcessRequestTransferExit(DCM_INITIAL, &pduRxData->SduDataPtr[1], pduRxData->SduLength - 1, &responseCode); } else { ret = Dcm_ProcessRequestTransferExit(opStatus, 0, 0, &responseCode); } switch (ret) { case E_OK: TransferStatus.transferType = DCM_NO_DATA_TRANSFER; uint16 respParamRecLen = pduTxData->SduLength; Dcm_Arc_GetTransferExitResponseParameterRecord(&pduTxData->SduDataPtr[1], &respParamRecLen); pduTxData->SduLength = 1 + respParamRecLen; responseCode = DCM_E_POSITIVERESPONSE; break; case E_PENDING: responseCode = DCM_E_RESPONSEPENDING; break; case E_FORCE_RCRRP: responseCode = DCM_E_FORCE_RCRRP; break; case E_NOT_OK: /* @req DCM759 */ break; default: DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); responseCode = DCM_E_REQUESTOUTOFRANGE; break; } } else { responseCode = DCM_E_REQUESTSEQUENCEERROR; } } else { responseCode = DCM_E_INCORRECTMESSAGELENGTHORINVALIDFORMAT; } if( DCM_E_RESPONSEPENDING == responseCode ) { dspUdsUploadDownloadPending.state = DCM_GENERAL_PENDING; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_TRANSFER_EXIT; } else if(DCM_E_FORCE_RCRRP == responseCode) { dspUdsUploadDownloadPending.state = DCM_GENERAL_FORCE_RCRRP_AWAITING_SEND; dspUdsUploadDownloadPending.pduRxData = pduRxData; dspUdsUploadDownloadPending.pduTxData = pduTxData; dspUdsUploadDownloadPending.pendingService = SID_REQUEST_TRANSFER_EXIT; DsdDspForceResponsePending(); } else { dspUdsUploadDownloadPending.state = DCM_GENERAL_IDLE; DsdDspProcessingDone(responseCode); } } #endif
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Dsp.c
C
unknown
291,506
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #include "MemMap.h" #ifndef DCM_NOT_SERVICE_COMPONENT #include "Rte_Dcm.h" #endif #if defined(USE_NVM) #include "NvM.h" #endif #include "arc_assert.h" #define IS_SIGNED_DATATYPE(_x) (((_x) == DCM_SINT8) || ((_x) == DCM_SINT16) || ((_x) == DCM_SINT32)) /* Disable MISRA 2004 rule 16.2, MISRA 2012 rule 17.2. * This because of recursive calls to readDidData. * */ //lint -estring(974,*recursive*) typedef struct { uint8 session; uint8 testerSrcAddr; uint8 protocolId; boolean requestFullComm; boolean requested; }DcmProtocolRequestType; typedef void (*Dcm_StartProtocolNotificationFncType)(boolean started); typedef struct { uint8 priority; Dcm_StartProtocolNotificationFncType StartProtNotification; }DcmRequesterConfigType; static DcmProtocolRequestType ProtocolRequests[DCM_NOF_REQUESTERS]; static boolean ProtocolRequestsAllowed = FALSE; boolean lookupNonDynamicDid(uint16 didNr, const Dcm_DspDidType **didPtr) { const Dcm_DspDidType *dspDid = Dcm_ConfigPtr->Dsp->DspDid; boolean didFound = FALSE; while ((dspDid->DspDidIdentifier != didNr) && (FALSE == dspDid->Arc_EOL)) { dspDid++; } /* @req Dcm651 */ if ((FALSE == dspDid->Arc_EOL) && (!((TRUE == dspDid->DspDidInfoRef->DspDidDynamicllyDefined) && DID_IS_IN_DYNAMIC_RANGE(didNr)) ) ) { didFound = TRUE; *didPtr = dspDid; } return didFound; } boolean lookupDynamicDid(uint16 didNr, const Dcm_DspDidType **didPtr) { const Dcm_DspDidType *dspDid = Dcm_ConfigPtr->Dsp->DspDid; boolean didFound = FALSE; if( DID_IS_IN_DYNAMIC_RANGE(didNr) ) { while ((dspDid->DspDidIdentifier != didNr) && (FALSE == dspDid->Arc_EOL)) { dspDid++; } /* @req Dcm651 */ if ((FALSE == dspDid->Arc_EOL) && (TRUE == dspDid->DspDidInfoRef->DspDidDynamicllyDefined)) { didFound = TRUE; *didPtr = dspDid; } } return didFound; } Dcm_NegativeResponseCodeType readDidData(const Dcm_DspDidType *didPtr, PduInfoType *pduTxData, uint16 *txPos, ReadDidPendingStateType *pendingState, uint16 *pendingDid, uint16 *pendingSignalIndex, uint16 *pendingDataLen, uint16 *didIndex, uint16 didStartIndex, uint16 *didDataStartPos) { Dcm_NegativeResponseCodeType responseCode = DCM_E_POSITIVERESPONSE; boolean didOnlyRefsDids = (NULL_PTR == didPtr->DspSignalRef)? TRUE: FALSE; if (didPtr->DspDidInfoRef->DspDidAccess.DspDidRead != NULL_PTR) { /** @req DCM433 */ if (TRUE == DspCheckSessionLevel(didPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSessionRef)) { /** @req DCM434 */ if (TRUE == DspCheckSecurityLevel(didPtr->DspDidInfoRef->DspDidAccess.DspDidRead->DspDidReadSecurityLevelRef)) { /** @req DCM435 */ if( (FALSE == didOnlyRefsDids) && (*didIndex >= didStartIndex)) { /* Get the data if available */ responseCode = getDidData(didPtr, pduTxData, txPos, pendingState, pendingDataLen, pendingSignalIndex, didDataStartPos, TRUE); if(DCM_E_RESPONSEPENDING == responseCode) { *pendingDid = didPtr->DspDidIdentifier; } else if( DCM_E_POSITIVERESPONSE == responseCode ) { /* Data successfully read */ (*didIndex)++; *pendingSignalIndex = 0; }else{ /* do nothing */ } } else { /* This did only references other dids or did already read. */ if( *didIndex >= didStartIndex ) { /* Not already read. */ if ((*txPos + 2) <= pduTxData->SduLength) { pduTxData->SduDataPtr[(*txPos)] = (didPtr->DspDidIdentifier >> 8) & 0xFFu; (*txPos)++; pduTxData->SduDataPtr[(*txPos)] = didPtr->DspDidIdentifier & 0xFFu; (*txPos)++; responseCode = DCM_E_POSITIVERESPONSE; } else { /* Tx buffer full. */ responseCode = DCM_E_RESPONSETOOLONG; } } (*didIndex)++; } } else { // Not allowed in current security level responseCode = DCM_E_SECURITYACCESSDENIED; } } else { // Not allowed in current session responseCode = DCM_E_REQUESTOUTOFRANGE;/** @req DCM433 */ } } else { // Read access not configured responseCode = DCM_E_REQUESTOUTOFRANGE; } for (uint16 i = 0; (FALSE == didPtr->DspDidRef[i]->Arc_EOL) && (DCM_E_POSITIVERESPONSE == responseCode); i++) { /* Recurse trough the rest of the dids. *//** @req DCM440 */ responseCode = readDidData(didPtr->DspDidRef[i], pduTxData, txPos, pendingState, pendingDid, pendingSignalIndex, pendingDataLen, didIndex, didStartIndex, didDataStartPos); } return responseCode; } /** * Writes data to SR port. Assumes that there actually is a SR configured. * @param dataPtr * @param dataVal * @return */ static Std_ReturnType WriteSRDataToPort(const Dcm_DspDataType *dataPtr, uint32 dataVal) { Std_ReturnType ret; switch(dataPtr->DspDataType) { case DCM_SINT8: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_SINT8((sint8)dataVal); break; case DCM_SINT16: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_SINT16((sint16)dataVal); break; case DCM_SINT32: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_SINT32((sint32)dataVal); break; case DCM_BOOLEAN: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_BOOLEAN((boolean)dataVal); break; case DCM_UINT8: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_UINT8((uint8)dataVal); break; case DCM_UINT16: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_UINT16((uint16)dataVal); break; case DCM_UINT32: ret = dataPtr->DspDataWriteDataFnc.SRDataWriteFnc_UINT32(dataVal); break; default: ret = E_NOT_OK; break; } return ret; } /** * Function for writing SR data * @param dataPtr * @param bitPosition * @param dataBuffer, pointer to first byte of DID buffer * @return */ Std_ReturnType WriteSRSignal(const Dcm_DspDataType *dataPtr, uint16 bitPosition, const uint8 *dataBuffer) { Std_ReturnType ret = E_OK; /* Unaligned data and/or endian-ness conversion*/ uint32 pduData = 0UL; if(dataPtr->DspDataEndianess == DCM_BIG_ENDIAN) { uint32 lsbIndex = (uint32)(((bitPosition ^ 0x7u) + dataPtr->DspDataBitSize - 1) ^ 7u); /* calculate lsb bit index. This could be moved to generator*/ const uint8 *pduDataPtr = ((&dataBuffer[lsbIndex / 8])-3); /* calculate big endian ptr to data*/ uint8 bitShift = (uint8)(lsbIndex % 8); for(uint32 i = 0uL; i < 4uL; i++) { pduData = (pduData << 8uL) | pduDataPtr[i]; } pduData >>= bitShift; if((32 - bitShift) < dataPtr->DspDataBitSize) { pduData |= (uint32)pduDataPtr[-1] << (32u - bitShift); } } else if (dataPtr->DspDataEndianess == DCM_LITTLE_ENDIAN) { uint32 lsbIndex = (uint32)bitPosition; const uint8 *pduDataPtr = &dataBuffer[(bitPosition/8)]; uint8 bitShift = (uint8)(lsbIndex % 8); for(sint32 i = 3; i >= 0; i--) { pduData = (uint32)((pduData << 8uL) | pduDataPtr[i]); } pduData >>= bitShift; if((32 - bitShift) < dataPtr->DspDataBitSize) { pduData |= (uint32)pduDataPtr[4] << (32u - bitShift); } } else { ret = E_NOT_OK; } if( E_OK == ret ) { uint32 mask = 0xFFFFFFFFUL >> (32u - dataPtr->DspDataBitSize); /* calculate mask for SigVal */ pduData &= mask; /* clear bit out of range */ uint32 signmask = ~(mask >> 1u); if( IS_SIGNED_DATATYPE(dataPtr->DspDataType) ) { if(0 < (pduData & signmask)) { pduData |= signmask; /* add sign bits*/ } } /* Write to SR interface */ ret = WriteSRDataToPort(dataPtr, pduData); } return ret; } /** * * @param dataPtr * @param bitPosition * @param dataBuffer, pointer to first byte of DID buffer * @return */ Std_ReturnType ReadSRSignal(const Dcm_DspDataType *dataPtr, uint16 bitPosition, uint8 *dataBuffer) { Std_ReturnType ret; uint8 tempData[4]; uint32 dataVal=0uL; ret = dataPtr->DspDataReadDataFnc.SRDataReadFnc((void *)tempData); switch(dataPtr->DspDataType) { case DCM_BOOLEAN: case DCM_UINT8: case DCM_SINT8: dataVal = *(tempData); break; case DCM_UINT16: case DCM_SINT16: /*lint -e{826} -e{927} uint8* to uint16* casting is required */ dataVal = *((const uint16*)tempData); break; case DCM_UINT32: case DCM_SINT32: /*lint -e{826} -e{927} uint8* to uint16* casting is required */ dataVal = *((const uint32*)tempData); break; case DCM_UINT8_N: default: /* Data type not supported for SR */ ASSERT(0); break; } uint32 mask = 0xFFFFFFFFUL >> (32u - dataPtr->DspDataBitSize); /* calculate mask for SigVal*/ dataVal &= mask; // mask sigVal; if(dataPtr->DspDataEndianess == DCM_BIG_ENDIAN) { uint32 lsbIndex = (uint32)(((bitPosition ^ 0x7u) + dataPtr->DspDataBitSize - 1) ^ 7u); /* calculate lsb bit index. This could be moved to generator*/ uint8 *pduDataPtr = ((&dataBuffer [lsbIndex / 8])-3); /* calculate big endian ptr to data*/ uint32 pduData = 0uL; for(uint32 i = 0uL; i < 4uL; i++) { pduData = ((pduData << 8) | pduDataPtr[i]); } uint8 bitShift = (uint8)(lsbIndex % 8u); uint32 sigLo = dataVal << bitShift; uint32 maskLo = ~(mask << bitShift); uint32 newPduData = (pduData & maskLo) | sigLo; for(sint16 i = 3; i >= 0; i--) { pduDataPtr[i] = (uint8)newPduData; newPduData >>= 8; } uint8 maxBitsWritten = 32 - bitShift; if(maxBitsWritten < dataPtr->DspDataBitSize) { pduDataPtr--; pduData = *pduDataPtr; uint32 maskHi = ~(mask >> maxBitsWritten); uint32 sigHi = dataVal >> maxBitsWritten; newPduData = (pduData & maskHi) | sigHi; *pduDataPtr = (uint8)newPduData; } } else if (dataPtr->DspDataEndianess == DCM_LITTLE_ENDIAN) { uint32 lsbIndex = bitPosition; /* calculate lsb bit index.*/ uint8 *pduDataPtr = (&dataBuffer[lsbIndex / 8]); /* calculate big endian ptr to data*/ uint32 pduData = 0uL; for(sint32 i = 3; i >= 0; i--) { pduData = (pduData << 8u) | pduDataPtr[i]; } uint8 bitShift = (uint8)(lsbIndex % 8); uint32 sigLo = dataVal << bitShift; uint32 maskLo = ~(mask << bitShift); uint32 newPduData = (pduData & maskLo) | sigLo; for(uint32 i = 0uL; i < 4uL; i++) { pduDataPtr[i] = (uint8)newPduData; newPduData >>= 8; } uint8 maxBitsWritten = 32 - bitShift; if(maxBitsWritten < dataPtr->DspDataBitSize) { pduDataPtr = &pduDataPtr[4]; pduData = *pduDataPtr; uint32 maskHi = ~(mask >> maxBitsWritten); uint32 sigHi = dataVal >> maxBitsWritten; newPduData = (pduData & maskHi) | sigHi; *pduDataPtr = (uint8)newPduData; } } else { ret = E_NOT_OK; } return ret; } /** * Function to get the number of bytes affected by a signal * @param endianess * @param startBitPos * @param bitLength * @return */ uint16 GetNofAffectedBytes(DcmDspDataEndianessType endianess, uint16 startBitPos, uint16 bitLength) { uint16 affectedBytes = 1u; uint8 bitsInFirstByte; if( DCM_BIG_ENDIAN == endianess ) { bitsInFirstByte = (uint8)((startBitPos % 8u) + 1u); } else { bitsInFirstByte = (uint8)(8u - (startBitPos % 8u)); } if(bitsInFirstByte <= bitLength) { /* Data is across byte boundary. * Check how many bytes are needed for the rest. */ affectedBytes += (uint16)(((bitLength - bitsInFirstByte) + 7u) / 8u); } return affectedBytes; } Dcm_NegativeResponseCodeType getDidData(const Dcm_DspDidType *didPtr, const PduInfoType *pduTxData, uint16 *txPos, ReadDidPendingStateType *pendingState, uint16 *pendingDataLen, uint16 *pendingSignalIndex, uint16 *didDataStartPos, boolean includeDID) { Dcm_NegativeResponseCodeType errorCode = DCM_E_POSITIVERESPONSE; Dcm_OpStatusType opStatus = DCM_INITIAL; Std_ReturnType result = E_OK; const Dcm_DspSignalType *signalPtr; const Dcm_DspDataType *dataPtr; uint16 requiredBufSize; boolean inPendingState = (DCM_READ_DID_PENDING_COND_CHECK == *pendingState) || (DCM_READ_DID_PENDING_READ_DATA == *pendingState); requiredBufSize = *txPos + didPtr->DspDidDataByteSize; if( (TRUE == includeDID) && (FALSE == inPendingState) ) {/* When in pending state size of DID identifier has already been added to txPos (see below) */ requiredBufSize += 2u; } if( (TRUE == inPendingState) || (requiredBufSize <= pduTxData->SduLength) ) { /* Skip check when in pending state. It has already been done. */ if( TRUE == inPendingState ) { opStatus = DCM_PENDING; } else { if( TRUE == includeDID ) { pduTxData->SduDataPtr[*txPos] = (didPtr->DspDidIdentifier >> 8u) & 0xFFu; (*txPos)++; pduTxData->SduDataPtr[*txPos] = didPtr->DspDidIdentifier & 0xFFu; (*txPos)++; } *didDataStartPos = *txPos; memset(&pduTxData->SduDataPtr[*txPos], 0, didPtr->DspDidDataByteSize); } /* @req Dcm578 Skipping condition check for ECU_SIGNALs */ for(uint16 signalIndex = *pendingSignalIndex; (signalIndex < didPtr->DspNofSignals) && (DCM_E_POSITIVERESPONSE == errorCode); signalIndex++) { signalPtr = &didPtr->DspSignalRef[signalIndex]; dataPtr = signalPtr->DspSignalDataRef; if( ((DCM_READ_DID_PENDING_COND_CHECK == *pendingState) || (DCM_READ_DID_IDLE == *pendingState)) && (DATA_PORT_ECU_SIGNAL != dataPtr->DspDataUsePort) && (DATA_PORT_SR != dataPtr->DspDataUsePort) ) { /* @req Dcm439 */ if((DATA_PORT_ASYNCH == dataPtr->DspDataUsePort) || (DATA_PORT_SYNCH == dataPtr->DspDataUsePort)) { if( NULL_PTR != dataPtr->DspDataConditionCheckReadFnc ) { result = dataPtr->DspDataConditionCheckReadFnc(opStatus, &errorCode); } else { result = E_NOT_OK; } if(DATA_PORT_ASYNCH == dataPtr->DspDataUsePort) { if( E_PENDING == result ) { *pendingState = DCM_READ_DID_PENDING_COND_CHECK; } else { *pendingState = DCM_READ_DID_IDLE; opStatus = DCM_INITIAL; } } else { if( E_PENDING == result ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } } } #if defined(USE_NVM) && defined(DCM_USE_NVM_DID) else if(DATA_PORT_BLOCK_ID == dataPtr->DspDataUsePort){ /* @req DCM560 */ if (E_OK == NvM_ReadBlock(dataPtr->DspNvmUseBlockID, &pduTxData->SduDataPtr[(*txPos)])) { *pendingState = DCM_READ_DID_PENDING_READ_DATA; }else{ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } } #endif else { /* Port not supported */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_CONFIG_INVALID); result = E_NOT_OK; } } else { /* Condition check function already called with positive return */ result = E_OK; errorCode = DCM_E_POSITIVERESPONSE; } if ((result == E_OK) && (errorCode == DCM_E_POSITIVERESPONSE)) { /** @req DCM439 */ uint16 dataLen = 0u; if ( (TRUE == dataPtr->DspDataInfoRef->DspDidFixedLength) || (DATA_PORT_SR == dataPtr->DspDataUsePort) ) { /** @req DCM436 */ dataLen = GetNofAffectedBytes(dataPtr->DspDataEndianess, signalPtr->DspSignalBitPosition, dataPtr->DspDataBitSize); } else { if (dataPtr->DspDataReadDataLengthFnc != NULL_PTR) { if( DCM_READ_DID_IDLE == *pendingState ) { /* ReadDataLengthFunction is only allowed to return E_OK */ if(E_OK != dataPtr->DspDataReadDataLengthFnc(&dataLen)) { //lint !e934 Address of auto variable is OK DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } } else { /* Read length function has already been called */ dataLen = *pendingDataLen; } } } if( E_OK == result ) { // Now ready for reading the data! uint16 signalFirstBytePos = signalPtr->DspSignalBitPosition / 8u; if ((*didDataStartPos + signalFirstBytePos + dataLen) <= pduTxData->SduLength) { /** @req DCM437 */ if((DATA_PORT_SYNCH == dataPtr->DspDataUsePort ) || (DATA_PORT_ECU_SIGNAL == dataPtr->DspDataUsePort)) { if( NULL_PTR != dataPtr->DspDataReadDataFnc.SynchDataReadFnc ) { /* Synch read function is only allowed to return E_OK */ if(E_OK != dataPtr->DspDataReadDataFnc.SynchDataReadFnc(&pduTxData->SduDataPtr[(*didDataStartPos) + signalFirstBytePos]) ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } } else { result = E_NOT_OK; } } else if( DATA_PORT_ASYNCH == dataPtr->DspDataUsePort ) { if( NULL_PTR != dataPtr->DspDataReadDataFnc.AsynchDataReadFnc ) { result = dataPtr->DspDataReadDataFnc.AsynchDataReadFnc(opStatus, &pduTxData->SduDataPtr[(*didDataStartPos) + signalFirstBytePos]); } else { result = E_NOT_OK; } #if defined(USE_NVM) && defined(DCM_USE_NVM_DID) } else if ( DATA_PORT_BLOCK_ID == dataPtr->DspDataUsePort ){ NvM_RequestResultType errorStatus; if (E_OK != NvM_GetErrorStatus(dataPtr->DspNvmUseBlockID, &errorStatus)){//lint !e934 Address of auto variable is OK DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } if (errorStatus == NVM_REQ_PENDING){ result = E_PENDING; }else if (errorStatus == NVM_REQ_OK){ *pendingState = DCM_READ_DID_IDLE; }else{ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); result = E_NOT_OK; } #endif } else if(DATA_PORT_SR == dataPtr->DspDataUsePort) { result = ReadSRSignal(dataPtr, signalPtr->DspSignalBitPosition, &pduTxData->SduDataPtr[(*didDataStartPos)]); } else { /* Port not supported */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_CONFIG_INVALID); result = E_NOT_OK; } if( E_PENDING == result ) { *pendingState = DCM_READ_DID_PENDING_READ_DATA; *pendingDataLen = dataLen; *pendingSignalIndex = signalIndex; errorCode = DCM_E_RESPONSEPENDING; } else if (result != E_OK) { errorCode = DCM_E_CONDITIONSNOTCORRECT; } else { /* Did successfully read */ *pendingState = DCM_READ_DID_IDLE; /* Increment to highest position written */ if( *txPos < ((*didDataStartPos) + signalFirstBytePos + dataLen) ) { *txPos = ((*didDataStartPos) + signalFirstBytePos + dataLen); } } } else { // tx buffer full errorCode = DCM_E_REQUESTOUTOFRANGE; } } else {// Invalid return from readLenFunction errorCode = DCM_E_CONDITIONSNOTCORRECT; } } else if( E_PENDING == result ) { /* Pending condition check */ *pendingSignalIndex = signalIndex; errorCode = DCM_E_RESPONSEPENDING; } else { // CheckRead failed errorCode = DCM_E_CONDITIONSNOTCORRECT; } } } else { /* Tx buffer not big enough */ errorCode = DCM_E_RESPONSETOOLONG; } return errorCode; } void getDidLength(const Dcm_DspDidType *didPtr, uint16 *length, uint16* nofDatas) { boolean didOnlyRefsDids = (NULL_PTR == didPtr->DspSignalRef)? TRUE: FALSE; if( FALSE == didOnlyRefsDids) { /* Get the data if available */ (*length) += didPtr->DspDidDataByteSize; (*nofDatas)++; } for (uint16 i = 0; FALSE == didPtr->DspDidRef[i]->Arc_EOL; i++) { /* Recurse trough the rest of the dids. */ getDidLength(didPtr->DspDidRef[i], length, nofDatas); } } void DcmResetDiagnosticActivityOnSessionChange(Dcm_SesCtrlType newSession) { DspResetDiagnosticActivityOnSessionChange(newSession); DsdCancelPendingExternalServices(); } void DcmResetDiagnosticActivity(void) { DcmDspResetDiagnosticActivity(); DsdCancelPendingExternalServices(); } /** * Function for canceling pending requests */ void DcmCancelPendingRequests() { DspCancelPendingRequests(); DsdCancelPendingExternalServices(); } /** * * @param requester * @param session * @param protocolId * @param testerSrcAddr * @param requestFullComm * @return E_OK: Operation successful, E_NOT_OK: Operation failed */ Std_ReturnType DcmRequestStartProtocol(DcmProtocolRequesterType requester, uint8 session, uint8 protocolId, uint8 testerSrcAddr, boolean requestFullComm) { Std_ReturnType ret = E_NOT_OK; if( (requester < DCM_NOF_REQUESTERS) && (TRUE == ProtocolRequestsAllowed) ) { ProtocolRequests[requester].requested = TRUE; ProtocolRequests[requester].session = session; ProtocolRequests[requester].testerSrcAddr = testerSrcAddr; ProtocolRequests[requester].protocolId = protocolId; ProtocolRequests[requester].requestFullComm = requestFullComm; ret = E_OK; } return ret; } /** * Checks for protocol start requests and tries to start the highest prioritized */ void DcmExecuteStartProtocolRequest(void) { static const DcmRequesterConfigType DcmRequesterConfig[DCM_NOF_REQUESTERS] = { [DCM_REQ_DSP] = { .priority = 0, .StartProtNotification = DcmDspProtocolStartNotification }, #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && defined(USE_NVM) [DCM_REQ_ROE] = { .priority = 1, .StartProtNotification = DcmRoeProtocolStartNotification }, #endif }; DcmProtocolRequesterType decidingRequester = DCM_NOF_REQUESTERS; boolean requestFullComm = FALSE; uint8 currPrio = 0xff; for( uint8 requester = 0; requester < (uint8)DCM_NOF_REQUESTERS; requester++ ) { if( TRUE == ProtocolRequests[requester].requested ) { if(DcmRequesterConfig[requester].priority < currPrio ) { currPrio = DcmRequesterConfig[requester].priority; decidingRequester = (DcmProtocolRequesterType)requester; requestFullComm = ProtocolRequests[requester].requestFullComm; } } } if( decidingRequester != DCM_NOF_REQUESTERS ) { /* Find out if fullcomm should be requested */ for( uint8 requester = 0; requester <(uint8)DCM_NOF_REQUESTERS; requester++ ) { if( (TRUE == ProtocolRequests[requester].requested) && (ProtocolRequests[requester].requestFullComm == TRUE) && (ProtocolRequests[requester].session == ProtocolRequests[decidingRequester].session) && (ProtocolRequests[requester].testerSrcAddr == ProtocolRequests[decidingRequester].testerSrcAddr) && (ProtocolRequests[requester].protocolId == ProtocolRequests[decidingRequester].protocolId) ) { requestFullComm = TRUE; } } Std_ReturnType ret = DslDspSilentlyStartProtocol(ProtocolRequests[decidingRequester].session, ProtocolRequests[decidingRequester].protocolId, (uint16)ProtocolRequests[decidingRequester].testerSrcAddr, requestFullComm); /* Notify requesters */ boolean started; for( uint8 requester = 0; requester <(uint8)DCM_NOF_REQUESTERS; requester++ ) { if( ProtocolRequests[requester].requested == TRUE ) { started = FALSE; if( (ProtocolRequests[requester].session == ProtocolRequests[decidingRequester].session) && (ProtocolRequests[requester].testerSrcAddr == ProtocolRequests[decidingRequester].testerSrcAddr) && (ProtocolRequests[requester].protocolId == ProtocolRequests[decidingRequester].protocolId) ) { started = (E_OK == ret) ? TRUE : FALSE; } if( NULL_PTR != DcmRequesterConfig[requester].StartProtNotification ) { DcmRequesterConfig[requester].StartProtNotification(started); } } } } } /** * Sets allowance to request protocol start * @param allowed */ void DcmSetProtocolStartRequestsAllowed(boolean allowed) { if( (TRUE == allowed) && (FALSE == ProtocolRequestsAllowed)) { memset(ProtocolRequests, 0, sizeof(ProtocolRequests)); } ProtocolRequestsAllowed = allowed; }
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Internal.c
C
unknown
29,272
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* * NB! This file is for DCM internal use only and may only be included from DCM C-files! */ #ifndef DCM_INTERNAL_H_ #define DCM_INTERNAL_H_ #include "Dcm.h" #if defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && (0 < DCM_NOF_IOCONTROL_DIDS) #define DCM_USE_CONTROL_DIDS #endif #if ( DCM_DEV_ERROR_DETECT == STD_ON ) #if defined(USE_DET) #include "Det.h" #endif #define DCM_DET_REPORTERROR(_api,_err) \ (void)Det_ReportError(DCM_MODULE_ID, 0, _api, _err); \ #else #define DCM_DET_REPORTERROR(_api,_err) #endif #define VALIDATE(_exp,_api,_err ) \ if(!(_exp)) { \ DCM_DET_REPORTERROR(_api, _err); \ return E_NOT_OK; \ } #define VALIDATE_RV(_exp,_api,_err,_rv ) \ if(!(_exp)) { \ DCM_DET_REPORTERROR(_api, _err); \ return _rv; \ } #define VALIDATE_NO_RV(_exp,_api,_err ) \ if(!(_exp) ){ \ DCM_DET_REPORTERROR(_api, _err); \ return; \ } #define IS_PERIODIC_TX_PDU(_x) (((_x) >= DCM_FIRST_PERIODIC_TX_PDU) && ((_x) < (DCM_FIRST_PERIODIC_TX_PDU + DCM_NOF_PERIODIC_TX_PDU))) #define TO_INTERNAL_PERIODIC_PDU(_x) ((_x) - DCM_FIRST_PERIODIC_TX_PDU) // SID table #define SID_DIAGNOSTIC_SESSION_CONTROL 0x10 #define SID_ECU_RESET 0x11 #define SID_CLEAR_DIAGNOSTIC_INFORMATION 0x14 #define SID_READ_DTC_INFORMATION 0x19 #define SID_READ_DATA_BY_IDENTIFIER 0x22 #define SID_READ_MEMORY_BY_ADDRESS 0x23 #define SID_READ_SCALING_DATA_BY_IDENTIFIER 0x24 #define SID_SECURITY_ACCESS 0x27 #define SID_COMMUNICATION_CONTROL 0x28 #define SID_READ_DATA_BY_PERIODIC_IDENTIFIER 0x2A #define SID_DYNAMICALLY_DEFINE_DATA_IDENTIFIER 0x2C #define SID_WRITE_DATA_BY_IDENTIFIER 0x2E #define SID_INPUT_OUTPUT_CONTROL_BY_IDENTIFIER 0x2F #define SID_ROUTINE_CONTROL 0x31 #define SID_WRITE_MEMORY_BY_ADDRESS 0x3D #define SID_TESTER_PRESENT 0x3E #define SID_NEGATIVE_RESPONSE 0x7F #define SID_CONTROL_DTC_SETTING 0x85 #define SID_RESPONSE_ON_EVENT 0x86 #define SID_LINK_CONTROL 0x87 #define SID_REQUEST_DOWNLOAD 0x34 #define SID_REQUEST_UPLOAD 0x35 #define SID_TRANSFER_DATA 0x36 #define SID_REQUEST_TRANSFER_EXIT 0x37 //OBD SID TABLE #define SID_REQUEST_CURRENT_POWERTRAIN_DIAGNOSTIC_DATA 0x01 #define SID_REQUEST_POWERTRAIN_FREEZE_FRAME_DATA 0x02 #define SID_CLEAR_EMISSION_RELATED_DIAGNOSTIC_INFORMATION 0x04 #define SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES 0x03 #define SID_REQUEST_ON_BOARD_MONITORING_TEST_RESULTS_SPECIFIC_MONITORED_SYSTEMS 0x06 #define SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES_DETECTED_DURING_CURRENT_OR_LAST_COMPLETED_DRIVING_CYCLE 0x07 #define SID_REQUEST_VEHICLE_INFORMATION 0x09 #define SID_REQUEST_EMISSION_RELATED_DIAGNOSTIC_TROUBLE_CODES_WITH_PERMANENT_STATUS 0x0A // Misc definitions #define SUPPRESS_POS_RESP_BIT (uint8)0x80 #define SID_RESPONSE_BIT (uint8)0x40 #define VALUE_IS_NOT_USED (uint8)0x00 // This diag request error code is not an error and is therefore not allowed to be used by SWCs, only used internally in DCM. // It is therefore not defined in Rte_Dcm.h #define DCM_E_RESPONSEPENDING ((Dcm_NegativeResponseCodeType)0x78) #define DCM_E_FORCE_RCRRP ((Dcm_NegativeResponseCodeType)0x01)/* Not an actual response code. Used internally */ #define DID_IS_IN_DYNAMIC_RANGE(_x) (((_x) >= 0xF200) && ((_x) <= 0xF3FF)) typedef enum { DSD_TX_RESPONSE_READY, DSD_TX_RESPONSE_SUPPRESSED } DsdProcessingDoneResultType; typedef enum { DCM_READ_DID_IDLE, DCM_READ_DID_PENDING_COND_CHECK, DCM_READ_DID_PENDING_READ_DATA } ReadDidPendingStateType; typedef enum { DCM_NO_COM = 0, DCM_SILENT_COM, DCM_FULL_COM }DcmComModeType; typedef enum { DCM_REQ_DSP = 0, #if defined(DCM_USE_SERVICE_RESPONSEONEVENT) && defined(USE_NVM) DCM_REQ_ROE, #endif DCM_NOF_REQUESTERS }DcmProtocolRequesterType; /* * DSP */ void DspInit(boolean firstCall); void DspMain(void); void DspPreDsdMain(void); void DspTimerMain(void); void DspUdsDiagnosticSessionControl(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean respPendOnTransToBoot, boolean internalStartupRequest); #if defined(DCM_USE_SERVICE_LINKCONTROL) void DspUdsLinkControl(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean respPendOnTransToBoot); #endif void DspUdsEcuReset(const PduInfoType *pduRxData, PduIdType txPduId, PduInfoType *pduTxData, boolean startupResponseRequest); void DspUdsClearDiagnosticInformation(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsSecurityAccess(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsTesterPresent(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsReadDtcInformation(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsReadDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsReadScalingDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData); #ifdef DCM_USE_SERVICE_WRITEDATABYIDENTIFIER void DspUdsWriteDataByIdentifier(const PduInfoType *pduRxData, PduInfoType *pduTxData); #endif void DspUdsControlDtcSetting(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspResponseOnEvent(const PduInfoType *pduRxData, PduIdType rxPduId, PduInfoType *pduTxData); void DspUdsRoutineControl(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspDcmConfirmation(PduIdType confirmPduId, NotifResultType result); void DspUdsReadMemoryByAddress(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspUdsWriteMemoryByAddress(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DspReadDataByPeriodicIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData, PduIdType rxPduId, Dcm_ProtocolTransTypeType txType, boolean internalRequest); void DspDynamicallyDefineDataIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspIOControlByDataIdentifier(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DcmDspResetDiagnosticActivity(void); void DspResetDiagnosticActivityOnSessionChange(Dcm_SesCtrlType newSession); void DspCommunicationControl(const PduInfoType *pduRxData,PduInfoType *pduTxData, PduIdType rxPduId, PduIdType txConfirmId); void DspUdsTransferData(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspUdsRequestTransferExit(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspUdsRequestDownload(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspUdsRequestUpload(const PduInfoType *pduRxData, PduInfoType *pduTxData); void DcmDspProtocolStartNotification(boolean started); // OBD stack interface void DspObdRequestCurrentPowertrainDiagnosticData(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestPowertrainFreezeFrameData(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdClearEmissionRelatedDiagnosticData(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestEmissionRelatedDiagnosticTroubleCodes(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestOnBoardMonitoringTestResultsService06(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestEmissionRelatedDiagnosticTroubleCodesService07(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestVehicleInformation(const PduInfoType *pduRxData,PduInfoType *pduTxData); void DspObdRequestEmissionRelatedDiagnosticTroubleCodesWithPermanentStatus(const PduInfoType *pduRxData,PduInfoType *pduTxData); boolean DspCheckSessionLevel(Dcm_DspSessionRowType const* const* sessionLevelRefTable); boolean DspCheckSecurityLevel(Dcm_DspSecurityRowType const* const* securityLevelRefTable); void DspCancelPendingRequests(void); #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) void DspResponsePendingConfirmed(PduIdType confirmPduId); #endif boolean DspDslCheckSessionSupported(uint8 session); void DspCheckProtocolStartRequests(void); /* * DSD */ void DsdInit(void); void DsdMain(void); void DsdHandleRequest(void); void DsdDspProcessingDone(Dcm_NegativeResponseCodeType responseCode); void DsdDspProcessingDone_ReadDataByPeriodicIdentifier(Dcm_NegativeResponseCodeType responseCode, boolean supressNRC); void DsdDataConfirmation(PduIdType confirmPduId, NotifResultType result); void DsdDslDataIndication(const PduInfoType *pduRxData, const Dcm_DsdServiceTableType *protocolSIDTable, Dcm_ProtocolAddrTypeType addrType, PduIdType txPduId, PduInfoType *pduTxData, PduIdType rxContextPduId, Dcm_ProtocolTransTypeType txType, boolean internalRequest, boolean sendRespPendOnTransToBoot, boolean startupResponseRequest); PduIdType DsdDslGetCurrentTxPduId(void); #if defined(DCM_USE_SERVICE_READDATABYPERIODICIDENTIFIER) || defined(DCM_USE_SERVICE_COMMUNICATIONCONTROL) || (defined(USE_DEM) && defined(DCM_USE_SERVICE_CONTROLDTCSETTING)) || (defined(DCM_USE_SERVICE_INPUTOUTPUTCONTROLBYIDENTIFIER) && defined(DCM_USE_CONTROL_DIDS)) boolean DsdDspCheckServiceSupportedInActiveSessionAndSecurity(uint8 sid); #endif void DsdDspForceResponsePending(void); boolean DsdDspGetResponseRequired(void); #if (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) void DsdResponsePendingConfirmed(PduIdType confirmPduId, NotifResultType result); uint16 DsdDspGetTesterSourceAddress(void); #endif void DsdExternalSetNegResponse(const Dcm_MsgContextType* pMsgContext, Dcm_NegativeResponseCodeType ErrorCode); void DsdExternalProcessingDone(const Dcm_MsgContextType* pMsgContext); boolean DsdLookupSubService(uint8 SID, const Dcm_DsdServiceType *sidConfPtr, uint8 subService, const Dcm_DsdSubServiceType **subServicePtr, Dcm_NegativeResponseCodeType *respCode); #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) void DsdSetDspProcessingActive(boolean state); #endif void DsdCancelPendingExternalServices(void); #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL Std_ReturnType DsdDspGetCurrentProtocolRx(PduIdType rxPduId, const Dcm_DslProtocolRxType **protocolRx); #endif void DsdClearSuppressPosRspMsg(void); /* * DSL */ void DslInit(void); void DslMain(void); void DslHandleResponseTransmission(void); void DslDsdProcessingDone(PduIdType rxPduIdRef, DsdProcessingDoneResultType responseResult); void DslTpRxIndicationFromPduR(PduIdType dcmRxPduId, NotifResultType result, boolean internalRequest, boolean startupResponseRequest); Std_ReturnType DslGetActiveProtocol(Dcm_ProtocolType *protocolId); void DslInternal_SetSecurityLevel(Dcm_SecLevelType secLevel); Std_ReturnType DslGetSecurityLevel(Dcm_SecLevelType *secLevel); void DslSetSesCtrlType(Dcm_SesCtrlType sesCtrl); Std_ReturnType DslGetSesCtrlType(Dcm_SesCtrlType *sesCtrlType); void DslTpTxConfirmation(PduIdType dcmTxPduId, NotifResultType result); Std_ReturnType DslInternal_ResponseOnOneDataByPeriodicId(uint8 PericodID, PduIdType rxPduId); Std_ReturnType DslInternal_ResponseOnOneEvent(PduIdType rxPduId, uint8* request, uint8 requestLength); Std_ReturnType DslDspSilentlyStartProtocol(uint8 session, uint8 protocolId, uint16 testerSourceAddress, boolean requestFullComm); Std_ReturnType DslDspResponseOnStartupRequest(uint8 sid, uint8 subFnc, uint8 protocolId, uint16 testerSourceAddress); void DslComModeEntered(uint8 network, DcmComModeType comMode); void DslResetSessionTimeoutTimer(void); boolean DslPduRPduUsedForType2Tx(PduIdType pdurTxPduId, PduIdType *dcmTxPduId); #ifdef DCM_USE_SERVICE_COMMUNICATIONCONTROL Std_ReturnType DslDsdGetProtocolRx(PduIdType rxPduId, const Dcm_DslProtocolRxType **protocolRx); #endif BufReq_ReturnType DslCopyDataToRxBuffer(PduIdType dcmRxPduId, const PduInfoType *pduInfoPtr, PduLengthType *rxBufferSizePtr); BufReq_ReturnType DslStartOfReception(PduIdType dcmRxPduId, PduLengthType tpSduLength, PduLengthType *rxBufferSizePtr, boolean internalRequest); BufReq_ReturnType DslCopyTxData(PduIdType dcmTxPduId, PduInfoType *pduInfoPtr, RetryInfoType *periodData, PduLengthType *txDataCntPtr); #if (DCM_MANUFACTURER_NOTIFICATION == STD_ON) || (DCM_USE_JUMP_TO_BOOT == STD_ON) || defined(DCM_USE_SERVICE_LINKCONTROL) || (defined(DCM_USE_SERVICE_RESPONSEONEVENT) && defined(USE_NVM)) Std_ReturnType Arc_DslGetRxConnectionParams(PduIdType rxPduId, uint16* sourceAddress, Dcm_ProtocolAddrTypeType* reqType, Dcm_ProtocolType *protocolId); #endif void DslDsdSendResponsePending(PduIdType rxPduId); #if (DCM_USE_SPLIT_TASK_CONCEPT == STD_ON) void DslSetDspProcessingActive(PduIdType dcmRxPduId, boolean state); #endif boolean lookupNonDynamicDid(uint16 didNr, const Dcm_DspDidType **didPtr); boolean lookupDynamicDid(uint16 didNr, const Dcm_DspDidType **didPtr); Dcm_NegativeResponseCodeType readDidData(const Dcm_DspDidType *didPtr, PduInfoType *pduTxData, uint16 *txPos, ReadDidPendingStateType *pendingState, uint16 *pendingDid, uint16 *pendingSignalIndex, uint16 *pendingDataLen, uint16 *didIndex, uint16 didStartIndex, uint16 *didDataStartPos); Dcm_NegativeResponseCodeType getDidData(const Dcm_DspDidType *didPtr, const PduInfoType *pduTxData, uint16 *txPos, ReadDidPendingStateType *pendingState, uint16 *pendingDidLen, uint16 *pendingSignalIndex, uint16 *didDataStartPos, boolean includeDID); void getDidLength(const Dcm_DspDidType *didPtr, uint16 *length, uint16* nofDatas); #ifdef DCM_USE_SERVICE_RESPONSEONEVENT /* DCM ROE */ void DCM_ROE_Init(void); void DCM_ROE_PollDataIdentifiers(void); boolean DCM_ROE_IsActive(void); Dcm_NegativeResponseCodeType DCM_ROE_Start(uint8 storageState, uint8 eventWindowTime, PduIdType rxPduId, PduInfoType *pduTxData); Dcm_NegativeResponseCodeType DCM_ROE_Stop(uint8 storageState, uint8 eventWindowTime, PduInfoType *pduTxData); Dcm_NegativeResponseCodeType DCM_ROE_ClearEventList(uint8 storageState, uint8 eventWindowTime, PduInfoType *pduTxData); Dcm_NegativeResponseCodeType DCM_ROE_GetEventList(uint8 storageState, PduInfoType *pduTxData); Dcm_NegativeResponseCodeType DCM_ROE_AddDataIdentifierEvent(uint8 eventWindowTime, uint8 storageState, uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength, PduInfoType *pduTxData); void Dcm_ROE_MainFunction(void); void DcmRoeProtocolStartNotification(boolean started); void DcmRoeCheckProtocolStartRequest(void); #endif void DcmResetDiagnosticActivity(void); void DcmResetDiagnosticActivityOnSessionChange(Dcm_SesCtrlType newSession); void DcmCancelPendingRequests(void); Std_ReturnType DcmRequestStartProtocol(DcmProtocolRequesterType requester, uint8 session, uint8 testerSrcAddr, uint8 protocolId, boolean requestFullComm); void DcmSetProtocolStartRequestsAllowed(boolean allowed); void DcmExecuteStartProtocolRequest(void); Std_ReturnType ReadSRSignal(const Dcm_DspDataType *dataPtr, uint16 bitPosition, uint8 *dataBuffer); Std_ReturnType WriteSRSignal(const Dcm_DspDataType *dataPtr, uint16 bitPosition, const uint8 *dataBuffer); uint16 GetNofAffectedBytes(DcmDspDataEndianessType endianess, uint16 startBitPos, uint16 bitLength); #endif /* DCM_INTERNAL_H_ */
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_Internal.h
C
unknown
16,404
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ //lint -w2 Static code analysis warning level #include <string.h> #include "Dcm.h" #include "Dcm_Internal.h" #include "MemMap.h" #ifndef DCM_NOT_SERVICE_COMPONENT #include "Rte_Dcm.h" #endif #if defined(USE_NVM) #include "NvM.h" #if (NVM_SET_RAM_BLOCK_STATUS_API == STD_ON) #define ROE_USE_RAM_BLOCK_STATUS #endif #endif #ifdef DCM_USE_SERVICE_RESPONSEONEVENT #define DCM_MAX_NUMBER_OF_ROE_EVENTS 4 /* Max number of active ROE events */ #define DCM_ROE_INFINITE_WINDOW 0x02 #define ROE_INVALID_EVENT (uint16)0x0 #ifndef DCM_ROE_NVM_BLOCK_ID #define DCM_ROE_NVM_BLOCK_ID 0 #endif #ifndef DCM_ROE_NVM_BLOCK_SIZE #define DCM_ROE_NVM_BLOCK_SIZE 0 #endif #define INVALID_PDU 0xffff /* This enum describes the internal statue of ROE. */ typedef enum { ROE_INIT, /* Never been activated (hence no valid DCM_ROE_RxPduId) */ ROE_ACTIVE, /* Active and may trigger responses */ ROE_INACTIVE /* Inactive but a valid DCM_ROE_RxPduId exists */ } DCM_ROE_InternalStateType; typedef struct { const Dcm_DspDidType *didPtr; uint16 eventTypeRecord; uint16 bufferStart; uint16 bufferLength; /* same as did length including did ids */ uint8 serviceToRespondTo[DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH]; uint8 serviceResponseLength; } Dcm_ROE_EventType; #if defined(USE_NVM) typedef struct { uint16 eventTypeRecord; uint8 serviceToRespondTo[DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH]; uint8 serviceResponseLength; }Dcm_ROE_StoredEventType; typedef struct { PduIdType rxPdu; boolean active; Dcm_ROE_StoredEventType events[DCM_MAX_NUMBER_OF_ROE_EVENTS]; }Dcm_ROE_StorageType; Dcm_ROE_StorageType Dcm_ROE_StorageBuffer = {.active = FALSE}; #if defined(ROE_USE_RAM_BLOCK_STATUS) static boolean PendingNvmSetRamBlockStatus = FALSE; #endif #endif static PduIdType DCM_ROE_RxPduId; static DCM_ROE_InternalStateType Dcm_ROE_InternalState = ROE_INIT; static uint8 Dcm_ROE_DataIdentifierBuffer[DCM_ROE_BUFFER_SIZE] = {0}; #if (DCM_ROE_INTERNAL_DIDS == STD_ON) /* @req DCM523 */ static uint8 Dcm_ROE_DataIdentifierTempBuffer[DCM_ROE_BUFFER_SIZE] = {0}; #endif static uint16 Dcm_ROE_FirstFreeBufferIndex = 0; static Dcm_ROE_EventType Dcm_ROE_Events[DCM_MAX_NUMBER_OF_ROE_EVENTS]; static uint8 Dcm_ROE_NofEvents = 0; static boolean protocolStartRequested = FALSE; #if defined(ROE_USE_RAM_BLOCK_STATUS) /** * Tries to set NvM block changed */ static Std_ReturnType setNvMBlockChanged(NvM_BlockIdType blockId) { NvM_RequestResultType requestResult = NVM_REQ_PENDING; Std_ReturnType ret = E_OK; if( 0 != blockId ) { ret = NvM_GetErrorStatus(blockId, &requestResult); if((E_OK == ret) && (requestResult != NVM_REQ_PENDING) ) { (void)NvM_SetRamBlockStatus( blockId, TRUE ); } else { ret = E_NOT_OK; } } return ret; } #endif #if defined(USE_NVM) /** * Stores event and service to respond to in buffer written to NvM */ static Std_ReturnType storeROEDataIdentifierEvent(uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength) { Std_ReturnType ret = E_NOT_OK; uint8 storeIndex = 0; boolean done = FALSE; /* Check if already stored */ for( uint8 i = 0; (i < DCM_MAX_NUMBER_OF_ROE_EVENTS) && !done; i++ ) { if( (ROE_INVALID_EVENT == Dcm_ROE_StorageBuffer.events[i].eventTypeRecord) || (eventTypeRecord == Dcm_ROE_StorageBuffer.events[i].eventTypeRecord) ) { storeIndex = i; ret = E_OK; if(eventTypeRecord == Dcm_ROE_StorageBuffer.events[i].eventTypeRecord) { done = TRUE; } } } if((E_OK == ret) && (ROE_INVALID_EVENT == Dcm_ROE_StorageBuffer.events[storeIndex].eventTypeRecord)) { Dcm_ROE_StorageBuffer.events[storeIndex].eventTypeRecord = eventTypeRecord; memcpy(Dcm_ROE_StorageBuffer.events[storeIndex].serviceToRespondTo, serviceToRespondTo, serviceToRespondToLength); Dcm_ROE_StorageBuffer.events[storeIndex].serviceResponseLength = serviceToRespondToLength; } return ret; } /** * Removes all stored event from buffer written to NvM */ static void removeROEDataIdentifierEvents(void) { #if defined(ROE_USE_RAM_BLOCK_STATUS) boolean eventRemoved = FALSE; #endif for( uint8 i = 0; i < DCM_MAX_NUMBER_OF_ROE_EVENTS; i++ ) { if( ROE_INVALID_EVENT != Dcm_ROE_StorageBuffer.events[i].eventTypeRecord ) { Dcm_ROE_StorageBuffer.events[i].eventTypeRecord = ROE_INVALID_EVENT; memset(Dcm_ROE_StorageBuffer.events[i].serviceToRespondTo, 0, DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH); Dcm_ROE_StorageBuffer.events[i].serviceResponseLength = 0; #if defined(ROE_USE_RAM_BLOCK_STATUS) eventRemoved = TRUE; #endif } } #if defined(ROE_USE_RAM_BLOCK_STATUS) if( eventRemoved && (E_OK != setNvMBlockChanged(DCM_ROE_NVM_BLOCK_ID)) ) { PendingNvmSetRamBlockStatus = TRUE; } #endif } /** * Adds stored events on startup */ static void addStoredROEEvents(void) { for( uint8 i = 0; i < DCM_MAX_NUMBER_OF_ROE_EVENTS; i++ ) { if( ROE_INVALID_EVENT != Dcm_ROE_StorageBuffer.events[i].eventTypeRecord ) { if( E_OK != Dcm_Arc_AddDataIdentifierEvent(Dcm_ROE_StorageBuffer.events[i].eventTypeRecord, Dcm_ROE_StorageBuffer.events[i].serviceToRespondTo, Dcm_ROE_StorageBuffer.events[i].serviceResponseLength)) { Dcm_ROE_StorageBuffer.events[i].eventTypeRecord = ROE_INVALID_EVENT; } } } } /** * Validates the size of the NvM block */ #if !defined(HOST_TEST) static void validateROEBlockSize(uint32 actual, uint32 expected) { if(actual != expected) { /* Ending up here means that the configured block size * for ROE events differs from the actual size of the * buffer (or DCM_ROE_NVM_BLOCK_SIZE is not defined). */ while(1) {}; } } #endif /** * Stores active flag and pduId to NvM */ static void storeROEActive(boolean active, PduIdType rxPduId) { if( active != Dcm_ROE_StorageBuffer.active ) { Dcm_ROE_StorageBuffer.active = active; Dcm_ROE_StorageBuffer.rxPdu = rxPduId; #if defined(ROE_USE_RAM_BLOCK_STATUS) if( E_OK != setNvMBlockChanged(DCM_ROE_NVM_BLOCK_ID) ) { PendingNvmSetRamBlockStatus = TRUE; } #endif } } #endif /* Function: ReadDidData * Description: Reads DID data including all referred data */ static boolean ReadDidData(const Dcm_DspDidType *didPtr, uint8* buffer, uint16* length) { uint16 didIndex = 0; uint16 didStartIndex = 0; uint16 pendingDid = 0; uint16 pendingDidLen = 0; uint16 pendingSignalIndex = 0; uint16 didDataStartPos = 0; ReadDidPendingStateType pendingState = DCM_READ_DID_IDLE; PduInfoType pduTxData = { .SduDataPtr = buffer, .SduLength = DCM_ROE_BUFFER_SIZE }; Dcm_NegativeResponseCodeType responseCode = readDidData(didPtr, &pduTxData, length, &pendingState, &pendingDid, &pendingSignalIndex, &pendingDidLen, &didIndex, didStartIndex, &didDataStartPos); if( DCM_E_POSITIVERESPONSE == responseCode ) { return TRUE; } else { return FALSE; } } /* Function: NotifyExternalEvents * Description: Calls the activate function for external events */ static Std_ReturnType NotifyExternalEvents(Dcm_RoeStateType state) { for (uint8 indx=0;indx<Dcm_ROE_NofEvents;indx++) { if ((Dcm_ROE_Events[indx].didPtr->DspDidRoeActivateFnc != NULL) && (E_NOT_OK == Dcm_ROE_Events[indx].didPtr->DspDidRoeActivateFnc(Dcm_ROE_Events[indx].didPtr->DspDidRoeEventId, state))) { return E_NOT_OK; } } return E_OK; } /** * Adds preconfigured events to ROE list */ static void addPreconfiguredEvents(void) { const Dcm_ArcROEDidPreconfigType *ROEPreConfig = NULL; /* Add preconfigured events */ if( E_OK == Dcm_Arc_GetROEPreConfig(&ROEPreConfig) ) { if( (NULL != ROEPreConfig) && (NULL != ROEPreConfig->ROEDids)) { for( uint8 i = 0; i < ROEPreConfig->NofROEDids; i++ ) { if( E_OK != Dcm_Arc_AddDataIdentifierEvent(ROEPreConfig->ROEDids[i].DID, ROEPreConfig->ROEDids[i].ServiceToRespondTo, ROEPreConfig->ROEDids[i].ServiceToRespondToLength)) { /* Could not add event. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_INTEGRATION_ERROR); } } } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_INTEGRATION_ERROR); } } } /* Function: DCM_ROE_Init * Description: Initializes the module */ void DCM_ROE_Init(void) { Dcm_ROE_InternalState = ROE_INIT; Dcm_ROE_FirstFreeBufferIndex = 0; Dcm_ROE_NofEvents = 0; protocolStartRequested = FALSE; memset(Dcm_ROE_DataIdentifierBuffer, 0, sizeof(Dcm_ROE_DataIdentifierBuffer)); memset(Dcm_ROE_Events, 0, sizeof(Dcm_ROE_Events)); #if (DCM_ROE_INTERNAL_DIDS == STD_ON) memset(Dcm_ROE_DataIdentifierTempBuffer, 0, sizeof(Dcm_ROE_DataIdentifierTempBuffer)); #endif /* Add preconfigured events */ addPreconfiguredEvents(); #if defined(USE_NVM) #if !defined(HOST_TEST) validateROEBlockSize((uint32)DCM_ROE_NVM_BLOCK_SIZE, (uint32)sizeof(Dcm_ROE_StorageBuffer)); #endif /* Add events stored in NvRam */ addStoredROEEvents(); #endif } /** * Function called first main function after init to allow ROE to request * protocol start request */ void DcmRoeCheckProtocolStartRequest(void) { #if defined(USE_NVM) /* Check if ROE was stored as active. If it was, request start of protocol. */ if( Dcm_ROE_StorageBuffer.active && (INVALID_PDU != Dcm_ROE_StorageBuffer.rxPdu)) { uint16 srcAddr; Dcm_ProtocolType protocolId; Dcm_ProtocolAddrTypeType reqType; if( E_OK == Arc_DslGetRxConnectionParams(Dcm_ROE_StorageBuffer.rxPdu, &srcAddr, &reqType, &protocolId) ) { if( E_OK == DcmRequestStartProtocol(DCM_REQ_ROE, DCM_DEFAULT_SESSION, protocolId, (uint8)srcAddr, FALSE) ) { protocolStartRequested = TRUE; } else { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_RESPONSE); } } } #endif } /** * Notification that a requested protocol has been started (or not) */ void DcmRoeProtocolStartNotification(boolean started) { if( protocolStartRequested ) { if( started ) { uint8 dummySduData[8]; PduInfoType pduRxData; pduRxData.SduDataPtr = dummySduData; (void)DCM_ROE_Start(0, 0, Dcm_ROE_StorageBuffer.rxPdu, &pduRxData); protocolStartRequested = FALSE; } } else { /* Have not requested a start.. */ DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } } /* Function: DCM_ROE_IsActive * Description: Returns true if the ROE function is active otherwise false */ boolean DCM_ROE_IsActive(void) { return (Dcm_ROE_InternalState == ROE_ACTIVE); } /* Function: DCM_ROE_Start * Description: Handles the ROE start subfunction and compiles a response */ Dcm_NegativeResponseCodeType DCM_ROE_Start(uint8 storageState, uint8 eventWindowTime, PduIdType rxPduId, PduInfoType *pduTxData) { /* @req Dcm127 */ DCM_ROE_RxPduId = rxPduId; Dcm_ROE_InternalState = ROE_INACTIVE; /* Got proper RxPduId */ /* @req DCM525 The Dcm_RestartROE() calls the activate functions for external events */ if (E_OK == Dcm_RestartROE()) { pduTxData->SduDataPtr[1] = 0x05 | storageState; pduTxData->SduDataPtr[2] = 0; /* numberOfIdentifiedEvents (N/A) */ pduTxData->SduDataPtr[3] = eventWindowTime; /* Mirror event time, shall not be used */ pduTxData->SduLength = 4; if(storageState != 0) { storeROEActive(TRUE, DCM_ROE_RxPduId); } return DCM_E_POSITIVERESPONSE; } else { /* @req DCM679 */ return DCM_E_REQUESTOUTOFRANGE; } } /* Function: DCM_ROE_Stop * Description: Handles the ROE stop subfunction and compiles a response */ Dcm_NegativeResponseCodeType DCM_ROE_Stop(uint8 storageState, uint8 eventWindowTime, PduInfoType *pduTxData) { /* @req DCM526 The Dcm_StopROE() calls the activate functions for external events */ if (E_OK == Dcm_StopROE()) { if(0 != storageState) { storeROEActive(FALSE, INVALID_PDU); } pduTxData->SduDataPtr[1] = 0x00 | storageState; pduTxData->SduDataPtr[2] = 0; /* numberOfIdentifiedEvents (N/A) */ pduTxData->SduDataPtr[3] = eventWindowTime; /* Mirror event time, shall not be used */ pduTxData->SduLength = 4; return DCM_E_POSITIVERESPONSE; } else { /* @req DCM679 */ return DCM_E_REQUESTOUTOFRANGE; } } /* Function: DCM_ROE_ClearEventList * Description: Handles the ROE clear event list and compiles a response */ Dcm_NegativeResponseCodeType DCM_ROE_ClearEventList(uint8 storageState, uint8 eventWindowTime, PduInfoType *pduTxData) { if ((Dcm_ROE_InternalState == ROE_ACTIVE) && (E_NOT_OK == Dcm_StopROE())) { /* @req DCM679 */ return DCM_E_REQUESTOUTOFRANGE; } else { Dcm_ROE_NofEvents = 0; #if defined(USE_NVM) removeROEDataIdentifierEvents(); #endif pduTxData->SduDataPtr[1] = 0x06 | storageState; pduTxData->SduDataPtr[2] = 0; /* numberOfIdentifiedEvents (N/A) */ pduTxData->SduDataPtr[3] = eventWindowTime; /* Mirror event time, shall not be used */ pduTxData->SduLength = 4; return DCM_E_POSITIVERESPONSE; } } /* Function: DCM_ROE_GetEventList * Description: Handles the ROE get event list and compiles a response */ Dcm_NegativeResponseCodeType DCM_ROE_GetEventList(uint8 storageState, PduInfoType *pduTxData) { uint8 responseByteIndx = 1; pduTxData->SduDataPtr[responseByteIndx++] = 0x04 | storageState; /* eventType */ pduTxData->SduDataPtr[responseByteIndx++] = (Dcm_ROE_InternalState == ROE_ACTIVE) ? Dcm_ROE_NofEvents : 0; if( Dcm_ROE_InternalState == ROE_ACTIVE ) { for (uint8 i = 0; i < Dcm_ROE_NofEvents; i++) { /* Check if the data fits in the response */ if (pduTxData->SduLength <= (responseByteIndx + 4 + Dcm_ROE_Events[i].serviceResponseLength)) { return DCM_E_RESPONSETOOLONG; } pduTxData->SduDataPtr[responseByteIndx++] = 0x03; /* eventTypeOfActiveEvent */ pduTxData->SduDataPtr[responseByteIndx++] = DCM_ROE_INFINITE_WINDOW; /* eventWindowTime */ pduTxData->SduDataPtr[responseByteIndx++] = (uint8)(Dcm_ROE_Events[i].eventTypeRecord >> 8); /* eventTypeRecord */ pduTxData->SduDataPtr[responseByteIndx++] = (uint8)(Dcm_ROE_Events[i].eventTypeRecord & 0xFF); /* eventTypeRecord */ for (uint8 j=0;j<Dcm_ROE_Events[i].serviceResponseLength;j++) { pduTxData->SduDataPtr[responseByteIndx++] = Dcm_ROE_Events[i].serviceToRespondTo[j]; } } } pduTxData->SduLength = responseByteIndx; return DCM_E_POSITIVERESPONSE; } /* Function: checkROEPreCondition * Description: Checks preconditions for DCM_ROE_AddDataIdentifierEvent */ static Dcm_NegativeResponseCodeType checkROEPreCondition(uint8 eventWindowTime, uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength, PduInfoType *pduTxData) { /* Only supporting serviceToRespondTo = ReadDataByIdentifier, * eventWindowTime = infinite * the response service must at least contain one byte */ if ((serviceToRespondToLength < 1) || (serviceToRespondTo[0] != SID_READ_DATA_BY_IDENTIFIER) || (eventWindowTime != DCM_ROE_INFINITE_WINDOW)) { return DCM_E_REQUESTOUTOFRANGE; } /* Check that the event buffer is not full and that the service length is within range */ if ((Dcm_ROE_NofEvents >= DCM_MAX_NUMBER_OF_ROE_EVENTS) || (serviceToRespondToLength > DCM_ROE_MAX_SERVICE_TO_RESPOND_TO_LENGTH)) { return DCM_E_REQUESTOUTOFRANGE; } /* Add the event to the event list */ if (!lookupNonDynamicDid(eventTypeRecord, &Dcm_ROE_Events[Dcm_ROE_NofEvents].didPtr)) { return DCM_E_REQUESTOUTOFRANGE; } /* Check that the eventTypeRecord isn't already in the list */ for (uint8 indx=0; indx<Dcm_ROE_NofEvents;indx++) { if (Dcm_ROE_Events[indx].eventTypeRecord == eventTypeRecord) { return DCM_E_REQUESTOUTOFRANGE; } } /* Check that a positive response will fit in the tx buffer */ if( (NULL != pduTxData) && ((serviceToRespondToLength + 5u) > pduTxData->SduLength) ) { return DCM_E_RESPONSETOOLONG; } return DCM_E_POSITIVERESPONSE; } /* Function: DCM_ROE_AddDataIdentifierEvent * Description: Handles the ROE on change of data identifier and compiles a response */ Dcm_NegativeResponseCodeType DCM_ROE_AddDataIdentifierEvent(uint8 eventWindowTime, uint8 storageState, uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength, PduInfoType *pduTxData) { /* @req Dcm522 */ uint8 responseByteIndx = 1; uint16 length = 0; uint16 nofDids = 0; /* Check preconditions */ Dcm_NegativeResponseCodeType NRC = checkROEPreCondition(eventWindowTime,eventTypeRecord,serviceToRespondTo,serviceToRespondToLength,pduTxData); if( NRC != DCM_E_POSITIVERESPONSE ) { return NRC; } /* Allocate space in the buffer */ Dcm_ROE_Events[Dcm_ROE_NofEvents].bufferStart = Dcm_ROE_FirstFreeBufferIndex; getDidLength(Dcm_ROE_Events[Dcm_ROE_NofEvents].didPtr, &length, &nofDids); length += (nofDids * 2); /* Add the lenght for the dids */ Dcm_ROE_Events[Dcm_ROE_NofEvents].bufferLength = length; Dcm_ROE_FirstFreeBufferIndex += length; Dcm_ROE_Events[Dcm_ROE_NofEvents].eventTypeRecord = eventTypeRecord; memcpy(Dcm_ROE_Events[Dcm_ROE_NofEvents].serviceToRespondTo, serviceToRespondTo, serviceToRespondToLength); Dcm_ROE_Events[Dcm_ROE_NofEvents].serviceResponseLength = serviceToRespondToLength; Dcm_ROE_NofEvents++; #if defined(USE_NVM) /* @req DCM709 */ if( 0 != storageState ) { if(E_OK != storeROEDataIdentifierEvent(eventTypeRecord, serviceToRespondTo, serviceToRespondToLength) ) { DCM_DET_REPORTERROR(DCM_GLOBAL_ID, DCM_E_UNEXPECTED_EXECUTION); } else { #if defined(ROE_USE_RAM_BLOCK_STATUS) if( E_OK != setNvMBlockChanged(DCM_ROE_NVM_BLOCK_ID) ) { PendingNvmSetRamBlockStatus = TRUE; } #endif } } #endif /* Put together a response */ if (pduTxData != NULL ) { pduTxData->SduDataPtr[responseByteIndx++] = 0x03 | storageState; /* eventType */ pduTxData->SduDataPtr[responseByteIndx++] = 0; /* numberOfIdentifiedEvents */ pduTxData->SduDataPtr[responseByteIndx++] = eventWindowTime; /* eventTimeWindow */ pduTxData->SduDataPtr[responseByteIndx++] = (eventTypeRecord >> 8)&0xFF; /* eventTypeRecord High byte */ pduTxData->SduDataPtr[responseByteIndx++] = eventTypeRecord&0xFF; /* eventTypeRecord Low byte */ for (uint8 i=0;i<serviceToRespondToLength;i++) { pduTxData->SduDataPtr[responseByteIndx++] = serviceToRespondTo[i]; /* service to respond to */ } pduTxData->SduLength = responseByteIndx; } return DCM_E_POSITIVERESPONSE; } /* Function: DCM_ROE_PollDataIdentifiers * Description:This function is used for internally managed data identifiers, it polls each identifier and * sends a response if it has changed */ #if DCM_ROE_INTERNAL_DIDS == STD_ON void DCM_ROE_PollDataIdentifiers(void) { /* @req DCM524 */ /* Used to save the current event being checked, used to not cause that a single event is being sent all the * time if changed all the time */ static uint16 indx = 0; if (Dcm_ROE_InternalState == ROE_ACTIVE) { if (indx >= Dcm_ROE_NofEvents) { indx = 0; } for (;indx<Dcm_ROE_NofEvents;indx++) { uint16 startIndex = 0; if ((Dcm_ROE_Events[indx].didPtr->DspDidRoeActivateFnc != NULL) || !ReadDidData(Dcm_ROE_Events[indx].didPtr, Dcm_ROE_DataIdentifierTempBuffer, &startIndex)) { continue; /* A failing read will not cause a diagnostic response, the old data will be kept */ } if ( memcmp(Dcm_ROE_DataIdentifierTempBuffer, &Dcm_ROE_DataIdentifierBuffer[Dcm_ROE_Events[indx].bufferStart], startIndex) != 0) { /* The data has changed trigger an internal diagnostic request */ /* @req DCM128 */ (void)DslInternal_ResponseOnOneEvent(DCM_ROE_RxPduId, Dcm_ROE_Events[indx].serviceToRespondTo, Dcm_ROE_Events[indx].serviceResponseLength); break; } } } } #endif /* Function: Dcm_TriggerOnEvent * Description: Triggers an ROE response for the specified id. It is only possible * to trigger responses for external events. Called from the application using a service * interface. */ Std_ReturnType Dcm_TriggerOnEvent(uint8 RoeEventId) { /** @req DCM521 Returning E_NOT_OK when an event is not triggered (other cases than invalid id) */ uint8 indx = 0; if (Dcm_ROE_InternalState != ROE_ACTIVE) { return E_NOT_OK; } for (indx = 0; indx < Dcm_ROE_NofEvents; indx++) { if ((Dcm_ROE_Events[indx].didPtr->DspDidRoeActivateFnc != NULL) && (Dcm_ROE_Events[indx].didPtr->DspDidRoeEventId == RoeEventId)) { /* If the request buffer is full, this function will return E_NOT_OK */ /* @req DCM582 *//* @req DCM128 *//* @req DCM129 */ return DslInternal_ResponseOnOneEvent(DCM_ROE_RxPduId, Dcm_ROE_Events[indx].serviceToRespondTo, Dcm_ROE_Events[indx].serviceResponseLength); } } if (indx == Dcm_ROE_NofEvents) { /* Did not find and ROE event with matching id */ return E_NOT_OK; } return E_OK; } /* Function: Dcm_StopROE * Description: Stops the ROE. Called from the application using a service interface. */ Std_ReturnType Dcm_StopROE(void) { /** @req DCM730 */ Std_ReturnType status = NotifyExternalEvents(DCM_ROE_UNACTIVE); if (status == E_OK) { /* Not allowed to leave ROE_INIT since no RxPduId is set */ Dcm_ROE_InternalState = (Dcm_ROE_InternalState == ROE_INIT) ? ROE_INIT : ROE_INACTIVE; } return status; } /* Function: Dcm_RestartROE * Description: Restarts the ROE. It must have been initially started by a diagnostic request * so that the RxPduId is saved and may be used when sending a response. Called from the * application using a service interface. */ Std_ReturnType Dcm_RestartROE(void) { /** @req DCM731 *//** @req DCM714 */ Std_ReturnType status; /* Cannot start if not been start by a diagnostic request since no valid RxPduId */ if (Dcm_ROE_InternalState == ROE_INIT) { return E_NOT_OK; } status = NotifyExternalEvents(DCM_ROE_ACTIVE); if (status == E_OK) { /* Read data that will be used for comparison in the poll routine */ for (uint8 indx=0;indx<Dcm_ROE_NofEvents;indx++) { uint16 startIndex = 0; if ((Dcm_ROE_Events[indx].didPtr->DspDidRoeActivateFnc == NULL)) { (void)ReadDidData(Dcm_ROE_Events[indx].didPtr, &Dcm_ROE_DataIdentifierBuffer[Dcm_ROE_Events[indx].bufferStart], &startIndex); } } /* @req Dcm714 */ Dcm_ROE_InternalState = ROE_ACTIVE; } return status; } /* Function: Dcm_Arc_AddDataIdentifierEvent * Description: This function is used to add data identifer events internally e.g at start up. */ Std_ReturnType Dcm_Arc_AddDataIdentifierEvent(uint16 eventTypeRecord, const uint8* serviceToRespondTo, uint8 serviceToRespondToLength) { if (DCM_ROE_AddDataIdentifierEvent(DCM_ROE_INFINITE_WINDOW, 0, eventTypeRecord, serviceToRespondTo, serviceToRespondToLength, NULL) != DCM_E_POSITIVERESPONSE) { return E_NOT_OK; } else { return E_OK; } } /** * Main service function for ROE */ void Dcm_ROE_MainFunction(void) { #if defined(ROE_USE_RAM_BLOCK_STATUS) if(PendingNvmSetRamBlockStatus) { if( E_OK == setNvMBlockChanged(DCM_ROE_NVM_BLOCK_ID) ) { PendingNvmSetRamBlockStatus = FALSE; } } #endif } #if defined(USE_NVM) /** * Init block callback for use by NvM */ void Dcm_Arc_InitROEBlock(void) { Dcm_ROE_StorageBuffer.active = FALSE; Dcm_ROE_StorageBuffer.rxPdu = INVALID_PDU; removeROEDataIdentifierEvents(); } #endif #endif /* End of file */
2301_81045437/classic-platform
diagnostic/Dcm/src/Dcm_ROE.c
C
unknown
28,084
#Dem obj-$(USE_DEM) += Dem.o ifeq ($(filter Dem_Extension.o,$(obj-y)),) obj-$(USE_DEM_EXTENSION) += Dem_Extension.o endif obj-$(USE_DEM) += Dem_Debounce.o obj-$(USE_DEM) += Dem_LCfg.o obj-$(USE_DEM) += Dem_NvM.o inc-$(USE_DEM) += $(ROOTDIR)/diagnostic/Dem/inc inc-$(USE_DEM) += $(ROOTDIR)/diagnostic/Dem/src vpath-$(USE_DEM) += $(ROOTDIR)/diagnostic/Dem/src
2301_81045437/classic-platform
diagnostic/Dem/Dem.mod.mk
Makefile
unknown
369
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_H_ #define DEM_H_ /* @req DEM628 */ #define DEM_MODULE_ID 54u #define DEM_VENDOR_ID 60u #define DEM_AR_RELEASE_MAJOR_VERSION 4u #define DEM_AR_RELEASE_MINOR_VERSION 0u #define DEM_AR_RELEASE_REVISION_VERSION 3u #define DEM_SW_MAJOR_VERSION 5u #define DEM_SW_MINOR_VERSION 19u #define DEM_SW_PATCH_VERSION 0u #define DEM_AR_MAJOR_VERSION DEM_AR_RELEASE_MAJOR_VERSION #define DEM_AR_MINOR_VERSION DEM_AR_RELEASE_MINOR_VERSION #define DEM_AR_PATCH_VERSION DEM_AR_RELEASE_REVISION_VERSION #include "Dem_Types.h" #include "Dem_Cfg.h" #include "Dem_Lcfg.h" #include "Dem_IntErrId.h" /** @req DEM115 */ #include "Dem_IntEvtId.h" #include "Dem_EnableCondId.h" #include <limits.h> /** @req DEM153 */ /** @req DEM154 */ /** @req DEM024 *//* Realized in Dem_IntErrId.h and Dem_IntEvtId.h */ // #include "Rte_Dem.h" #if (DEM_DEV_ERROR_DETECT == STD_ON) // Error codes reported by this module defined by AUTOSAR /** @req DEM116 */ /** @req DEM173 */ #define DEM_E_PARAM_CONFIG 0x10u #define DEM_E_PARAM_POINTER 0x11u #define DEM_E_PARAM_DATA 0x12u #define DEM_E_PARAM_LENGTH 0x13u #define DEM_E_UNINIT 0x20u #define DEM_E_NODATAAVAILABLE 0x30u #define DEM_E_WRONG_CONDITION 0x40u // Other error codes reported by this module #define DEM_E_CONFIG_PTR_INVALID 0x50u #define DEM_E_EXT_DATA_TOO_BIG 0x52u #define DEM_E_PRE_INIT_EXT_DATA_BUFF_FULL 0x53u #define DEM_E_MEM_EVENT_BUFF_FULL 0x54u #define DEM_E_MEM_EXT_DATA_BUFF_FULL 0x55u #define DEM_E_FF_TOO_BIG 0x56u #define DEM_E_PRE_INIT_FF_DATA_BUFF_FULL 0x57u #define DEM_E_MEM_FF_DATA_BUFF_FULL 0x58u #define DEM_E_OBD_NOT_ALLOWED_IN_SEC_MEM 0x59u #define DEM_E_MEMORY_CORRUPT 0x5Au #define DEM_E_SEQUENCE_ERROR 0xfdu #define DEM_E_UNEXPECTED_EXECUTION 0xfeu #define DEM_E_NOT_IMPLEMENTED_YET 0xffu // Service ID in this module #define DEM_PREINIT_ID 0x01u #define DEM_INIT_ID 0x02u #define DEM_SHUTDOWN_ID 0x03u #define DEM_SETEVENTSTATUS_ID 0x04u #define DEM_RESETEVENTSTATUS_ID 0x05u #define DEM_SETOPERATIONCYCLESTATE_ID 0x08u #define DEM_GETEVENTSTATUS_ID 0x0Au #define DEM_GETEVENTFAILED_ID 0x0Bu #define DEM_GETEVENTTESTED_ID 0x0Cu #define DEM_GETDTCOFEVENT_ID 0x0Du #define DEM_GETSEVERITYOFDTC_ID 0x0Eu #define DEM_REPORTERRORSTATUS_ID 0x0Fu #define DEM_SETDTCFILTER_ID 0x13u #define DEM_GETSTATUSOFDTC_ID 0x15u #define DEM_GETDTCSTATUSAVAILABILITYMASK_ID 0x16u #define DEM_GETNUMBEROFFILTEREDDTC_ID 0x17u #define DEM_GETNEXTFILTEREDDTC_ID 0x18u #define DEM_DISABLEDTCRECORDUPDATE_ID 0x1Au #define DEM_ENABLEDTCRECORDUPDATE_ID 0x1Bu #define DEM_GETFREEZEFRAMEDATABYDTC_ID 0x1Du #define DEM_GETSIZEOFFREEZEFRAMEBYDTC_ID 0x1Fu #define DEM_GETEXTENDEDDATARECORDBYDTC_ID 0x20u #define DEM_GETSIZEOFEXTENDEDDATARECORDBYDTC_ID 0x21u #define DEM_CLEARDTC_ID 0x22u #define DEM_DISABLEDTCSETTING_ID 0x24u #define DEM_ENABLEDTCSETTING_ID 0x25u #define DEM_GETINDICATORSTATUS_ID 0x29u #define DEM_GETEVENTEXTENDEDDATARECORD_ID 0x30u #define DEM_GETEVENTFREEZEFRAMEDATA_ID 0x31u #define DEM_GETEVENTMEMORYOVERFLOW_ID 0x32u #define DEM_SETDTCSUPPRESSION_ID 0x33u #define DEM_SETEVENTAVAILABLE_ID 0x37u /* ASR 4.2.2 API */ #define DEM_GETNEXTFILTEREDRECORD_ID 0x3au #define DEM_GETTRANSLATIONTYPE_ID 0x3cu #define DEM_SETENABLECONDITION_ID 0x39u #define DEM_GETFAULTDETECTIONCOUNTER_ID 0x3Eu #define DEM_SETFREEZEFRAMERECORDFILTER_ID 0x3Fu #define DEM_DLTGETALLEXTENDEDDATARECORDS_ID 0x40u #define DEM_DLTGETMOSTRECENTFREEZEFRAMERECORDDATA_ID 0x41u #define DEM_READDATAOFOBDFREEZEFRAME_ID 0X52u #define DEM_GETDTCOFOBDFREEZEFRAME_ID 0x53u #define DEM_MAINFUNCTION_ID 0x55u #define DEM_REPIUMPRFAULTDETECT_ID 0x73u #define DEM_UPDATE_EVENT_STATUS_ID 0x80u #define DEM_MERGE_EVENT_STATUS_ID 0x81u #define DEM_GET_EXTENDED_DATA_ID 0x82u #define DEM_STORE_EXT_DATA_PRE_INIT_ID 0x83u #define DEM_STORE_EVENT_MEM_ID 0x84u #define DEM_STORE_EXT_DATA_MEM_ID 0x85u #define DEM_PREDEBOUNCE_NONE_ID 0x86u #define DEM_PREDEBOUNCE_COUNTER_BASED_ID 0x87u #define DEM_GET_FREEZEFRAME_ID 0x88u #define DEM_STORE_FF_DATA_PRE_INIT_ID 0x89u #define DEM_STORE_FF_DATA_MEM_ID 0x90u #define DEM_PRE_STORE_FF_ID 0x91u #define DEM_CLEAR_PRE_STORED_FF_ID 0x92u #define DEM_READ_DATA_LENGTH_FAILED 0x93u #define DEM_FF_NULLREF 255u #define DEM_GETMONITORSTATUS_ID 0xB5u /* ASR 4.3.0 API */ #define DEM_GLOBAL_ID 0xffu #endif #define DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT UINT32_MAX //when timestamp up to the max value,rearrangement starts. #define DEM_MAX_TIMESTAMP_FOR_PRE_INIT (uint32)(UINT32_MAX/2) /* * Interface for upper layer modules */ #if ( DEM_VERSION_INFO_API == STD_ON ) /** @req DEM111 */ #define Dem_GetVersionInfo(_vi) STD_GET_VERSION_INFO(_vi,DEM) /** @req DEM177 */ /** @req DEM110 */ #endif /* DEM_VERSION_INFO_API */ /* * Interface ECU State Manager <-> DEM */ void Dem_PreInit( const Dem_ConfigType *ConfigPtr ); /** @req DEM179 */ void Dem_Init( void ); /** @req DEM181 */ void Dem_Shutdown( void ); /** @req DEM182 */ /* * Interface for basic software scheduler */ void Dem_MainFunction( void ); /** @req DEM266 */ /* * Interface BSW modules/SW-Components via RTE <-> DEM */ void Dem_ReportErrorStatus(Dem_EventIdType eventId ,Dem_EventStatusType eventStatus); /** @req DEM206 */ #if !defined(USE_RTE) Std_ReturnType Dem_SetEventStatus(Dem_EventIdType eventId, Dem_EventStatusType eventStatus); Std_ReturnType Dem_ResetEventStatus(Dem_EventIdType eventId); #endif Std_ReturnType Dem_SetOperationCycleState(Dem_OperationCycleIdType operationCycleId, Dem_OperationCycleStateType cycleState); /** @req DEM194 */ Std_ReturnType Dem_GetEventStatus(Dem_EventIdType eventId, Dem_EventStatusExtendedType *eventStatusExtended); /** @req DEM195 */ Std_ReturnType Dem_GetEventFailed(Dem_EventIdType eventId, boolean *eventFailed); /** @req DEM196 */ Std_ReturnType Dem_GetEventTested(Dem_EventIdType eventId, boolean *eventTested); /** @req DEM197 */ Std_ReturnType Dem_GetDTCOfEvent(Dem_EventIdType eventId, Dem_DTCFormatType dtcFormat, uint32* dtcOfEvent); /** @req DEM198 */ #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) Std_ReturnType Dem_SetEnableCondition(uint8 EnableConditionID, boolean ConditionFulfilled); /** @req DEM201*/ #endif Std_ReturnType Dem_GetFaultDetectionCounter(Dem_EventIdType eventId, sint8 *counter); /** @req DEM203 */ Std_ReturnType Dem_GetIndicatorStatus( uint8 IndicatorId, Dem_IndicatorStatusType* IndicatorStatus ); /* @req DEM205 */ Std_ReturnType Dem_GetEventFreezeFrameData(Dem_EventIdType EventId, uint8 RecordNumber, boolean ReportTotalRecord, uint16 DataId, uint8* DestBuffer);/* @req DEM558 */ Std_ReturnType Dem_GetEventExtendedDataRecord(Dem_EventIdType EventId, uint8 RecordNumber, uint8* DestBuffer);/* @req DEM557 */ Std_ReturnType Dem_GetEventMemoryOverflow(Dem_DTCOriginType DTCOrigin, boolean *OverflowIndication); /* @req DEM559 */ #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) Std_ReturnType Dem_SetDTCSuppression(uint32 DTC, Dem_DTCFormatType DTCFormat, boolean SuppressionStatus);/* @req 4.2.2/SWS_Dem_01047 *//* @req DEM583 */ #endif Std_ReturnType Dem_SetEventAvailable(Dem_EventIdType EventId, boolean AvailableStatus);/* @req 4.2.2/SWS_Dem_01080 */ /* * Interface DCM <-> DEM */ /* Access DTCs and status information */ Dem_ReturnSetFilterType Dem_SetDTCFilter(uint8 dtcStatusMask, Dem_DTCKindType dtcKind, Dem_DTCFormatType dtcFormat, Dem_DTCOriginType dtcOrigin, Dem_FilterWithSeverityType filterWithSeverity, Dem_DTCSeverityType dtcSeverityMask, Dem_FilterForFDCType filterForFaultDetectionCounter); /** @req DEM208 */ Dem_ReturnSetFilterType Dem_SetFreezeFrameRecordFilter(Dem_DTCFormatType dtcFormat, uint16 *NumberOfFilteredRecords);/* @req DEM209 */ Dem_ReturnGetStatusOfDTCType Dem_GetStatusOfDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, Dem_EventStatusExtendedType* status); /** @req DEM212 */ Std_ReturnType Dem_GetDTCStatusAvailabilityMask(uint8 *dtcStatusMask); /** @req DEM213 */ Dem_ReturnGetNumberOfFilteredDTCType Dem_GetNumberOfFilteredDtc(uint16* numberOfFilteredDTC); /** @req DEM214 */ Dem_ReturnGetNextFilteredDTCType Dem_GetNextFilteredDTC(uint32* dtc, Dem_EventStatusExtendedType* dtcStatus); /** @req DEM215 */ Dem_ReturnGetNextFilteredDTCType Dem_GetNextFilteredRecord(uint32 *DTC, uint8 *RecordNumber); /* @req DEM224 */ Dem_DTCTranslationFormatType Dem_GetTranslationType(void); /** @req DEM230 */ Dem_ReturnGetSeverityOfDTCType Dem_GetSeverityOfDTC(uint32 DTC, Dem_DTCSeverityType* DTCSeverity);/** @req DEM232 */ /* Access extended data records and FreezeFrame data */ Dem_ReturnDisableDTCRecordUpdateType Dem_DisableDTCRecordUpdate(uint32 DTC, Dem_DTCOriginType DTCOrigin);/* @req DEM233 */ Std_ReturnType Dem_EnableDTCRecordUpdate(void);/* @req DEM234 */ Dem_ReturnGetFreezeFrameDataByDTCType Dem_GetFreezeFrameDataByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin,uint8 recordNumber, uint8* destBuffer, uint16* bufSize);/** @req DEM236 */ Dem_ReturnGetSizeOfFreezeFrameType Dem_GetSizeOfFreezeFrameByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 recordNumber, uint16* sizeOfFreezeFrame);/** @req DEM238 */ Dem_ReturnGetExtendedDataRecordByDTCType Dem_GetExtendedDataRecordByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 extendedDataNumber, uint8 *destBuffer, uint16 *bufSize); /** @req DEM239 */ Dem_ReturnGetSizeOfExtendedDataRecordByDTCType Dem_GetSizeOfExtendedDataRecordByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 extendedDataNumber, uint16 *sizeOfExtendedDataRecord); /** @req DEM240 */ /* DTC storage */ /** @req DEM241 Deviation from specification. Prototype exists regardless if RTE is used or not. The specification states that it should be prototyped by the RTE but this causes a compilation warning since Dem.h is included from the Dcm */ Dem_ReturnClearDTCType Dem_ClearDTC(uint32 dtc, Dem_DTCFormatType dtcFormat, Dem_DTCOriginType dtcOrigin); Dem_ReturnControlDTCStorageType Dem_DisableDTCSetting(Dem_DTCGroupType dtcGroup, Dem_DTCKindType dtcKind); /** @req DEM242 */ Dem_ReturnControlDTCStorageType Dem_EnableDTCSetting(Dem_DTCGroupType dtcGroup, Dem_DTCKindType dtcKind); /** @req DEM243 */ /* * OBD-specific Interfaces */ Std_ReturnType Dem_ReadDataOfOBDFreezeFrame(uint8 PID, uint8 DataElementIndexOfPid, uint8* DestBuffer, uint8* BufSize);/* @req DEM327 */ Std_ReturnType Dem_GetDTCOfOBDFreezeFrame(uint8 FrameNumber, uint32* DTC );/* @req DEM624 */ #if (DEM_OBD_SUPPORT == STD_ON) Std_ReturnType Dem_SetEventDisabled(Dem_EventIdType EventId); Std_ReturnType Dem_DcmReadDataOfPID01(uint8* PID01value); Std_ReturnType Dem_DcmReadDataOfPID41(uint8* PID41value); Std_ReturnType Dem_RepIUMPRDenLock(Dem_RatioIdType RatioID); Std_ReturnType Dem_RepIUMPRDenRelease(Dem_RatioIdType RatioID); Std_ReturnType Dem_RepIUMPRFaultDetect(Dem_RatioIdType RatioID); Std_ReturnType Dem_SetIUMPRDenCondition(Dem_IumprDenomCondIdType ConditionId, Dem_IumprDenomCondStatusType ConditionStatus); Std_ReturnType Dem_GetIUMPRDenCondition(Dem_IumprDenomCondIdType ConditionId, Dem_IumprDenomCondStatusType* ConditionStatus); #if (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_SPARK) /* DEM357 */ Std_ReturnType Dem_GetInfoTypeValue08(uint8* Iumprdata08); #elif (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_COMPR) /* DEM358 */ Std_ReturnType Dem_GetInfoTypeValue0B(uint8* Iumprdata0B); #endif #endif /* * Interface DLT <-> DEM */ #if (DEM_TRIGGER_DLT_REPORTS == STD_ON) Std_ReturnType Dem_DltGetAllExtendedDataRecords(Dem_EventIdType EventId, uint8* DestBuffer, uint8* BufSize); /** @req DEM637 */ Std_ReturnType Dem_DltGetMostRecentFreezeFrameRecordData(Dem_EventIdType EventId, uint8* DestBuffer, uint8* BufSize);/** @req DEM636 */ #endif Std_ReturnType Dem_GetMonitorStatus(Dem_EventIdType EventID, Dem_MonitorStatusType* MonitorStatus);/** @req 4.3.0/SWS_Dem_91007 */ #endif /*DEM_H_*/
2301_81045437/classic-platform
diagnostic/Dem/inc/Dem.h
C
unknown
13,317
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_LCFG_H_ #define DEM_LCFG_H_ #include "Dem_Types.h" #if defined(USE_DCM) #include "Dcm_Types.h" /** @req DEM176.Dcm */ #endif /* * Callback function prototypes */ // ClearEventAllowed typedef Std_ReturnType (*Dem_CallbackClearEventAllowedFncType)(boolean *Allowed); /* @req DEM563 */ // EventDataChanged typedef Std_ReturnType (*Dem_CallbackEventDataChangedFncTypeWithId)(Dem_EventIdType EventId);/* @req DEM562 */ typedef Std_ReturnType (*Dem_CallbackEventDataChangedFncTypeWithoutId)(void); typedef union { Dem_CallbackEventDataChangedFncTypeWithId eventDataChangedWithId; Dem_CallbackEventDataChangedFncTypeWithoutId eventDataChangedWithoutId; }Dem_CallbackEventDataChangedFncType; typedef struct { boolean UsePort; Dem_CallbackEventDataChangedFncType CallbackEventDataChangedFnc; }Dem_CallbackEventDataChangedType; // InitMonitorForEvent typedef Std_ReturnType (*Dem_CallbackInitMonitorForEventFncType)(Dem_InitMonitorReasonType InitMonitorReason); /** @req DEM256 *//** @req DEM376 *//** @req DEM003 */ // InitMonitorForFunction typedef Std_ReturnType (*Dem_CallbackInitMonitorForFunctionFncType)(void); /** !req DEM258 */ // EventStatusChanged typedef Std_ReturnType (*Dem_CallbackEventStatusChangedFncTypeWithId)(Dem_EventIdType EventId, Dem_EventStatusExtendedType EventStatusOld, Dem_EventStatusExtendedType EventStatusNew); /** @req DEM259 */ typedef Std_ReturnType (*Dem_CallbackEventStatusChangedFncTypeWithoutId)(Dem_EventStatusExtendedType EventStatusOld, Dem_EventStatusExtendedType EventStatusNew); /** @req DEM259 */ typedef union { Dem_CallbackEventStatusChangedFncTypeWithId eventStatusChangedWithId; Dem_CallbackEventStatusChangedFncTypeWithoutId eventStatusChangedWithoutId; }Dem_CallbackEventStatusChangedFncType; // DTCStatusChanged typedef Std_ReturnType (*Dem_CallbackDTCStatusChangedFncType)(uint8 DTCStatusOld, uint8 DTCStatusNew); /** !req DEM260 */ // DIDServices /** @req DEM261 *//* */ typedef Std_ReturnType (*Dem_CallbackReadDataFncType)(uint8 *Data);/* @req DEM564 */ // GetFaultDetectionCounter typedef Std_ReturnType (*Dem_CallbackGetFaultDetectionCounterFncType)(sint8 *EventIdFaultDetectionCounter); /** @req DEM263 */ typedef uint8 Dem_InternalDataElementType; #define DEM_NO_ELEMENT 0u #define DEM_OCCCTR 1u #define DEM_FAULTDETCTR 2u #define DEM_MAXFAULTDETCTR 3u #define DEM_CONFIRMATIONCNTR 4u #define DEM_AGINGCTR 5u #define DEM_OVFLIND 6u typedef enum { DEM_UPDATE_RECORD_NO, DEM_UPDATE_RECORD_YES, DEM_UPDATE_RECORD_VOLATILE, } Dem_UpdateRuleType; #define DEM_NON_EMISSION_RELATED 0u/* Used for events without DTC and events with non-emission related DTC */ #define DEM_EMISSION_RELATED 1u #define DEM_EMISSION_RELATED_MIL_ACTIVATING 2u typedef uint32 Dem_Arc_EventDTCKindType; /* * DemGeneral types */ // 10.2.25 DemEnableCondition typedef struct { boolean EnableConditionStatus; // uint8 EnableConditionID; // Optional } Dem_EnableConditionType; typedef struct { uint8 nofEnableConditions; const Dem_EnableConditionType * const *EnableCondition; }Dem_EnableConditionGroupType; // 10.2.30 DemExtendedDataRecordClass typedef struct { uint8 RecordNumber; // (1) uint16 DataSize; // (1) Dem_UpdateRuleType UpdateRule; /* @req DEM466 */ Dem_CallbackReadDataFncType CallbackGetExtDataRecord; // (1) Dem_InternalDataElementType InternalDataElement; /* @req DEM469 */ } Dem_ExtendedDataRecordClassType; // 10.2.13 DemExtendedDataClass typedef struct { const Dem_ExtendedDataRecordClassType *const ExtendedDataRecordClassRef[DEM_MAX_NR_OF_RECORDS_IN_EXTENDED_DATA+1]; // (1..253) } Dem_ExtendedDataClassType; // 10.2.8 DemPidOrDid typedef struct { const uint16 DidIdentifier; // (0..1) Dem_CallbackReadDataFncType DidReadFnc; // (0..1) const uint8 PidIdentifier; // (0..1) uint8 PidOrDidSize; // (1) Dem_CallbackReadDataFncType PidReadFnc; // (0..1) boolean Arc_EOL; } Dem_PidOrDidType; // 10.2.18 DemFreezeFrameClass typedef struct { const Dem_PidOrDidType * const * FFIdClassRef; // (1..255)/** @req DEM039 *//** @req DEM040 */ uint16 NofXids; Dem_FreezeFrameKindType FFKind; // (1) } Dem_FreezeFrameClassType; /* * DemConfigSetType types */ // 10.2.6 DemCallbackDTCStatusChanged typedef struct { Dem_CallbackDTCStatusChangedFncType CallbackDTCStatusChangedFnc; // (0..1) } Dem_CallbackDTCStatusChangedType; // 10.2.26 DemCallbackInitMForF typedef struct { Dem_CallbackInitMonitorForFunctionFncType CallbackInitMForF; // (0..1) } Dem_CallbackInitMForFType; // 10.2.17 DemDTCClass typedef struct { #if defined(HOST_TEST) Arc_Dem_DTC *DTCRef; // (1) #else const Arc_Dem_DTC *DTCRef; // (1) #endif const Dem_EventIdType *Events; // List of events referencing DTC uint16 DTCIndex; // Index of the DTC uint16 NofEvents; // Number of events referencing DTC // const Dem_CallbackDTCStatusChangedType *CallbackDTCStatusChanged; // (0..*) // const Dem_CallbackInitMForFType *CallbackInitMForF; // (0..*) Dem_DTCSeverityType DTCSeverity; // (0..1) Optional /* @req DEM033 */ boolean Arc_EOL; } Dem_DTCClassType; // 10.2.5 DemCallbackEventStatusChanged typedef struct { Dem_CallbackEventStatusChangedFncType CallbackEventStatusChangedFnc; // (0..1) boolean UsePort; boolean Arc_EOL; } Dem_CallbackEventStatusChangedType; typedef enum { DEM_FAILURE_CYCLE_EVENT = 0, DEM_FAILURE_CYCLE_INDICATOR }DemIndicatorFailureSourceType; typedef struct { uint16 IndicatorBufferIndex; uint8 IndicatorId; Dem_IndicatorStatusType IndicatorBehaviour;/* @req DEM511 */ uint8 IndicatorFailureCycleThreshold;/* @req DEM500 */ Dem_OperationCycleStateType *IndicatorFailureCycle;/* @req DEM504 */ uint8 IndicatorHealingCycleThreshold; Dem_OperationCycleStateType IndicatorHealingCycle; DemIndicatorFailureSourceType IndicatorFailureCycleSource; boolean *IndicatorValid; boolean Arc_EOL; } Dem_IndicatorAttributeType; // 10.2.23 DemPreDebounceMonitorInternal typedef struct { Dem_CallbackGetFaultDetectionCounterFncType CallbackGetFDCntFnc; // (1) } Dem_PreDebounceMonitorInternalType; // 10.2.22 DemPreDebounceFrequencyBased typedef uint8 Dem_PreDebounceFrequencyBasedType; // 10.2.24 DemPreDebounceTimeBased typedef struct{ uint32 TimeFailedThreshold; uint32 TimePassedThreshold; uint16 Index; }Dem_PreDebounceTimeBasedType; // 10.2.20 typedef struct { Dem_PreDebounceNameType PreDebounceName; // (1) union { const Dem_PreDebounceMonitorInternalType *PreDebounceMonitorInternal; // (0..1) const Dem_PreDebounceCounterBasedType *PreDebounceCounterBased; // (0..1) const Dem_PreDebounceFrequencyBasedType *PreDebounceFrequencyBased; // (0..1) const Dem_PreDebounceTimeBasedType *PreDebounceTimeBased; // (0..1) } PreDebounceAlgorithm; } Dem_PreDebounceAlgorithmClassType; typedef struct { uint8 Threshold; } Arc_FailureCycleCounterThreshold; // 10.2.14 DemEventClass typedef struct { const Arc_FailureCycleCounterThreshold *FailureCycleCounterThresholdRef; // (1) /* @req DEM529 */ const Dem_EnableConditionGroupType *EnableConditionGroupRef; // (0..*) Optional /* @req DEM446 */ const Dem_PreDebounceAlgorithmClassType *PreDebounceAlgorithmClass; // (0..255) (Only 0..1 supported) /* @req DEM413 */ const Dem_IndicatorAttributeType *IndicatorAttribute; // (0..255) const boolean *EventAvailableByCalibration; const uint8 *AgingCycleCounterThresholdPtr; // (0..1) Optional /* @req DEM493 */ const Dem_OperationCycleIdType *FailureCycleRef; // (1) /* @req DEM528 */ boolean ConsiderPtoStatus; // (1) Dem_DTCOriginType EventDestination; // (1 Arccore specific) uint8 EventPriority; // (1) /* @req DEM382 */ boolean FFPrestorageSupported; // (1) /* @req DEM002 */ boolean AgingAllowed; // (1) Dem_OperationCycleIdType OperationCycleRef; // (1) Dem_OperationCycleIdType AgingCycleRef; // (1) /* @req DEM494 */ Dem_EventOBDReadinessGroup OBDReadinessGroup; // (0..1) Optional // Dem_OEMSPecific } Dem_EventClassType; typedef struct { uint8 FreezeFrameRecordNumber[DEM_MAX_RECORD_NUMBERS_IN_FF_REC_NUM_CLASS + 1]; }Dem_FreezeFrameRecNumClass; typedef uint8 Dem_FreezeFrameClassTypeRefIndex; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) typedef struct { Dem_FreezeFrameClassTypeRefIndex FreezeFrameClassIdx; }Dem_CombinedDTCCalibType; typedef struct { const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClassRef; const Dem_ExtendedDataClassType *ExtendedDataClassRef; const Dem_CombinedDTCCalibType *Calib; const Dem_DTCClassType *DTCClassRef; Dem_EventIdType CombinedEventId; uint8 MaxNumberFreezeFrameRecords; uint8 Priority; Dem_DTCOriginType MemoryDestination; }Dem_CombinedDTCCfgType; #endif // 10.2.12 DemEventParameter typedef struct { const Dem_EventClassType *EventClass; // (1) const Dem_ExtendedDataClassType *ExtendedDataClassRef; // (0..1) /* @req DEM460 */ //const Dem_FreezeFrameClassType *FreezeFrameClassRef; // (0..1) /* @req DEM460 */ const Dem_FreezeFrameClassTypeRefIndex *FreezeFrameClassRefIdx; // (0..1) /* @req DEM460 */ const Dem_CallbackInitMonitorForEventFncType CallbackInitMforE; // (0..1) const Dem_CallbackEventStatusChangedType *CallbackEventStatusChanged; // (0..) const Dem_CallbackClearEventAllowedFncType CallbackClearEventAllowed; // (0..1) const Dem_CallbackEventDataChangedType *CallbackEventDataChanged; // (0..1) const Dem_DTCClassType *DTCClassRef; // (0..1) const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClassRef; // (1) #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) uint16 CombinedDTCCID; #endif uint16 EventID; // (1) Dem_EventKindType EventKind; // (1) uint8 MaxNumberFreezeFrameRecords; // (1) /* @req DEM337 *//* @req DEM582 */ Dem_Arc_EventDTCKindType *EventDTCKind; boolean Arc_EOL; } Dem_EventParameterType; typedef struct { uint8 EventListSize; const Dem_EventIdType *EventList; }Dem_IndicatorType; // 10.2.19 DemGroupOfDTC typedef struct { uint32 DemGroupDTCs; boolean Arc_EOL; }Dem_GroupOfDtcType; // 10.2.9 DemConfigSet typedef struct { const Dem_EventParameterType *EventParameter; // (0..65535) const Dem_DTCClassType *DTCClass; // (1..16777214) const Dem_GroupOfDtcType *GroupOfDtc; const Dem_EnableConditionType *EnableCondition; const Dem_FreezeFrameClassType *GlobalOBDFreezeFrameClassRef;/* @req DEM291 */ const Dem_FreezeFrameClassType *GlobalFreezeFrameClassRef; const Dem_IndicatorType *Indicators; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) const Dem_CombinedDTCCfgType *CombinedDTCConfig; #endif } Dem_ConfigSetType; // 10.2.2 Dem typedef struct { const Dem_ConfigSetType *ConfigSet; // (1) } Dem_ConfigType; /* ****************************************************************************************************** * WARNING: DO NOT CHANGE THESE STRUCTURES WITHOUT UPDATED THE DEM GENERATOR!! * ******************************************************************************************************/ typedef struct { #if (DEM_USE_TIMESTAMPS == STD_ON) uint32 timeStamp; #endif uint16 dataSize; Dem_EventIdType eventId; Dem_FreezeFrameKindType kind; uint8 recordNumber; uint8 data[DEM_MAX_SIZE_FF_DATA]; } FreezeFrameRecType; // Types for storing different event aging counter typedef struct { Dem_EventIdType eventId; uint8 agingCounter;/** @req Dem019 */ } HealingRecType; /* ****************************************************************************************************** * * ******************************************************************************************************/ #if (DEM_OBD_SUPPORT == STD_ON) typedef struct { Dem_RatioIdType RatioId; Dem_IUMPRGroup IumprGroup; const Dem_EventParameterType *DiagnosticEventRef; Dem_RatioKindType RatioKind; } Dem_RatioType; typedef struct { uint16 value; boolean incrementedThisDrivingCycle; } Dem_RatioNumeratorType; typedef struct { uint16 value; boolean incrementedThisDrivingCycle; boolean isLocked; } Dem_RatioDenominatorType; typedef struct { uint16 value; boolean incrementedThisDrivingCycle; } Dem_RatioGeneralDenominatorType; typedef struct { Dem_RatioNumeratorType numerator; Dem_RatioDenominatorType denominator; } Dem_RatioStatusType; typedef struct { uint16 numerator; uint16 denominator; } Dem_RatioStatusNvmType; #if defined(DEM_USE_IUMPR) #ifndef DEM_IUMPR_REGISTERED_COUNT #define DEM_IUMPR_REGISTERED_COUNT 0 #endif typedef struct { Dem_RatioStatusNvmType ratios[DEM_IUMPR_REGISTERED_COUNT]; uint16 generalDenominatorCount; uint16 ignitionCycleCount; } Dem_RatiosNvm; extern const Dem_RatioType Dem_RatiosList[DEM_IUMPR_REGISTERED_COUNT]; #endif typedef uint8 Dem_IumprDenomCondIdType; typedef uint8 Dem_IumprDenomCondStatusType; typedef struct { Dem_IumprDenomCondIdType condition; Dem_IumprDenomCondStatusType status; } Dem_IumprDenomCondType; #define DEM_IUMPR_DEN_COND_COLDSTART (Dem_IumprDenomCondIdType) 0x02 #define DEM_IUMPR_DEN_COND_EVAP (Dem_IumprDenomCondIdType) 0x03 #define DEM_IUMPR_DEN_COND_500MI (Dem_IumprDenomCondIdType) 0x04 #define DEM_IUMPR_GENERAL_INDIVIDUAL_DENOMINATOR (Dem_IumprDenomCondIdType) 0x05 #define DEM_IUMPR_GENERAL_OBDCOND (Dem_IumprDenomCondIdType) 0x06 #define DEM_IUMPR_DEN_STATUS_NOT_REACHED (Dem_IumprDenomCondStatusType) 0x00 #define DEM_IUMPR_DEN_STATUS_REACHED (Dem_IumprDenomCondStatusType) 0x01 #define DEM_IUMPR_DEN_STATUS_INHIBITED (Dem_IumprDenomCondStatusType) 0x02 #endif /* * Make the DEM_Config visible for others. */ extern const Dem_ConfigType DEM_Config; #endif /*DEM_LCFG_H_*/
2301_81045437/classic-platform
diagnostic/Dem/inc/Dem_Lcfg.h
C
unknown
16,615
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_TYPES_H_ #define DEM_TYPES_H_ #include "Std_Types.h" /** @req DEM176.Std */ #include "Rte_Dem_Type.h" /** Enum literals for Dem_DTCFormatType */ #ifndef DEM_DTC_FORMAT_OBD #define DEM_DTC_FORMAT_OBD 0U #endif /* DEM_DTC_FORMAT_OBD */ #ifndef DEM_DTC_FORMAT_UDS #define DEM_DTC_FORMAT_UDS 1U #endif /* DEM_DTC_FORMAT_UDS */ /** Enum literals for Dem_DTCOriginType */ #ifndef DEM_DTC_ORIGIN_NOT_USED #define DEM_DTC_ORIGIN_NOT_USED 0U #endif /* DEM_DTC_ORIGIN_NOT_USED */ #ifndef DEM_DTC_ORIGIN_PRIMARY_MEMORY #define DEM_DTC_ORIGIN_PRIMARY_MEMORY 1U #endif /* DEM_DTC_ORIGIN_PRIMARY_MEMORY */ #ifndef DEM_DTC_ORIGIN_MIRROR_MEMORY #define DEM_DTC_ORIGIN_MIRROR_MEMORY 2U #endif /* DEM_DTC_ORIGIN_MIRROR_MEMORY */ #ifndef DEM_DTC_ORIGIN_PERMANENT_MEMORY #define DEM_DTC_ORIGIN_PERMANENT_MEMORY 3U #endif /* DEM_DTC_ORIGIN_PERMANENT_MEMORY */ #ifndef DEM_DTC_ORIGIN_SECONDARY_MEMORY #define DEM_DTC_ORIGIN_SECONDARY_MEMORY 4U #endif /* DEM_DTC_ORIGIN_SECONDARY_MEMORY */ /** Enum literals for Dem_EventStatusExtendedType */ #ifndef DEM_TEST_FAILED #define DEM_TEST_FAILED 1U #endif /* DEM_TEST_FAILED */ #ifndef DEM_TEST_FAILED_THIS_OPERATION_CYCLE #define DEM_TEST_FAILED_THIS_OPERATION_CYCLE 2U #endif /* DEM_TEST_FAILED_THIS_OPERATION_CYCLE */ #ifndef DEM_PENDING_DTC #define DEM_PENDING_DTC 4U #endif /* DEM_PENDING_DTC */ #ifndef DEM_CONFIRMED_DTC #define DEM_CONFIRMED_DTC 8U #endif /* DEM_CONFIRMED_DTC */ #ifndef DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR #define DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR 16U #endif /* DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR */ #ifndef DEM_TEST_FAILED_SINCE_LAST_CLEAR #define DEM_TEST_FAILED_SINCE_LAST_CLEAR 32U #endif /* DEM_TEST_FAILED_SINCE_LAST_CLEAR */ #ifndef DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE #define DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE 64U #endif /* DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE */ #ifndef DEM_WARNING_INDICATOR_REQUESTED #define DEM_WARNING_INDICATOR_REQUESTED 128U #endif /* DEM_WARNING_INDICATOR_REQUESTED */ /** Enum literals for Dem_EventStatusType */ #ifndef DEM_EVENT_STATUS_PASSED #define DEM_EVENT_STATUS_PASSED 0U #endif /* DEM_EVENT_STATUS_PASSED */ #ifndef DEM_EVENT_STATUS_FAILED #define DEM_EVENT_STATUS_FAILED 1U #endif /* DEM_EVENT_STATUS_FAILED */ #ifndef DEM_EVENT_STATUS_PREPASSED #define DEM_EVENT_STATUS_PREPASSED 2U #endif /* DEM_EVENT_STATUS_PREPASSED */ #ifndef DEM_EVENT_STATUS_PREFAILED #define DEM_EVENT_STATUS_PREFAILED 3U #endif /* DEM_EVENT_STATUS_PREFAILED */ /** Enum literals for Dem_OperationCycleStateType */ #ifndef DEM_CYCLE_STATE_START #define DEM_CYCLE_STATE_START 0U #endif /* DEM_CYCLE_STATE_START */ #ifndef DEM_CYCLE_STATE_END #define DEM_CYCLE_STATE_END 1U #endif /* DEM_CYCLE_STATE_END */ /** Enum literals for Dem_ReturnClearDTCType */ #ifndef DEM_CLEAR_OK #define DEM_CLEAR_OK 0U #endif /* DEM_CLEAR_OK */ #ifndef DEM_CLEAR_WRONG_DTC #define DEM_CLEAR_WRONG_DTC 1U #endif /* DEM_CLEAR_WRONG_DTC */ #ifndef DEM_CLEAR_WRONG_DTCORIGIN #define DEM_CLEAR_WRONG_DTCORIGIN 2U #endif /* DEM_CLEAR_WRONG_DTCORIGIN */ #ifndef DEM_CLEAR_WRONG_DTCKIND #define DEM_CLEAR_WRONG_DTCKIND 3U #endif /* DEM_CLEAR_WRONG_DTCKIND */ #ifndef DEM_CLEAR_FAILED #define DEM_CLEAR_FAILED 4U #endif /* DEM_CLEAR_FAILED */ #ifndef DEM_DTC_PENDING #define DEM_DTC_PENDING 5U #endif /* DEM_DTC_PENDING */ #define DEM_EVENT_DESTINATION_END_OF_LIST 0 /* * DTC storage types */ typedef uint8 Dem_DTCTranslationFormatType; #define DEM_DTC_TRANSLATION_ISO15031_6 0x00 #define DEM_DTC_TRANSLATION_ISO14229_1 0x01 #define DEM_DTC_TRANSLATION_SAEJ1939_73 0x02 #define DEM_DTC_TRANSLATION_ISO11992_4 0x03 /* * Dem_DTCGroupType */ typedef uint32 Dem_DTCGroupType; #define DEM_DTC_GROUP_EMISSION_REL_DTCS (Dem_DTCGroupType)0x0 #define DEM_DTC_GROUP_ALL_DTCS (Dem_DTCGroupType)0xffffff /* * Dem status type */ #define DEM_DTC_STATUS_MASK_ALL (uint8)0x00 /* * Dem_FreezeFrameKindType */ typedef uint8 Dem_FreezeFrameKindType; // NOTE: Check type and values #define DEM_FREEZE_FRAME_NON_OBD (Dem_FreezeFrameKindType)0x01 #define DEM_FREEZE_FRAME_OBD (Dem_FreezeFrameKindType)0x02 /* * Dem_EventKindType */ typedef uint8 Dem_EventKindType; // NOTE: Check type and values #define DEM_EVENT_KIND_BSW (Dem_EventKindType)0x01 #define DEM_EVENT_KIND_SWC (Dem_EventKindType)0x02 /* * Dem_PreDebounceNameType */ typedef uint8 Dem_PreDebounceNameType; enum { DEM_NO_PRE_DEBOUNCE, DEM_PRE_DEBOUNCE_COUNTER_BASED, DEM_PRE_DEBOUNCE_TIME_BASED }; /* * Dem_FilterWithSeverityType */ typedef uint8 Dem_FilterWithSeverityType; #define DEM_FILTER_WITH_SEVERITY_YES (Dem_FilterWithSeverityType)0x00 #define DEM_FILTER_WITH_SEVERITY_NO (Dem_FilterWithSeverityType)0x01 /* * Dem_FilterForFDCType */ typedef uint8 Dem_FilterForFDCType; #define DEM_FILTER_FOR_FDC_YES (Dem_FilterForFDCType)0x00 #define DEM_FILTER_FOR_FDC_NO (Dem_FilterForFDCType)0x01 /* * Dem_DTCSeverityType */ typedef uint8 Dem_DTCSeverityType; #define DEM_SEVERITY_NO_SEVERITY 0x00u /* No severity information available */ #define DEM_SEVERITY_MAINTENANCE_ONLY 0x20u #define DEM_SEVERITY_CHECK_AT_NEXT_HALT 0x40u #define DEM_SEVERITY_CHECK_IMMEDIATELY 0x80u /* * Dem_ReturnSetDTCFilterType */ typedef uint8 Dem_ReturnSetFilterType; #define DEM_FILTER_ACCEPTED (Dem_ReturnSetFilterType)0x00 #define DEM_WRONG_FILTER (Dem_ReturnSetFilterType)0x01 /* * Dem_ReturnGetStatusOfDTCType */ typedef uint8 Dem_ReturnGetStatusOfDTCType; #define DEM_STATUS_OK (Dem_ReturnGetStatusOfDTCType)0x00 #define DEM_STATUS_WRONG_DTC (Dem_ReturnGetStatusOfDTCType)0x01 #define DEM_STATUS_WRONG_DTCORIGIN (Dem_ReturnGetStatusOfDTCType)0x02 #define DEM_STATUS_FAILED (Dem_ReturnGetStatusOfDTCType)0x04 #define DEM_STATUS_WRONG_DTCKIND (Dem_ReturnGetStatusOfDTCType)0x03 /* * Dem_ReturnGetNextFilteredDTCType */ typedef uint8 Dem_ReturnGetNextFilteredDTCType; #define DEM_FILTERED_OK (Dem_ReturnGetNextFilteredDTCType)0x00 #define DEM_FILTERED_NO_MATCHING_DTC (Dem_ReturnGetNextFilteredDTCType)0x01 #define DEM_FILTERED_WRONG_DTCKIND (Dem_ReturnGetNextFilteredDTCType)0x02 #define DEM_FILTERED_PENDING (Dem_ReturnGetNextFilteredDTCType)0x03 /* * Dem_ReturnGetNumberOfFilteredDTCType */ typedef uint8 Dem_ReturnGetNumberOfFilteredDTCType; #define DEM_NUMBER_OK (Dem_ReturnGetNumberOfFilteredDTCType)0x00 #define DEM_NUMBER_FAILED (Dem_ReturnGetNumberOfFilteredDTCType)0x01 #define DEM_NUMBER_PENDING (Dem_ReturnGetNumberOfFilteredDTCType)0x02 /* * Dem_ReturnControlDTCStorageType */ typedef uint8 Dem_ReturnControlDTCStorageType; #define DEM_CONTROL_DTC_STORAGE_OK (Dem_ReturnControlDTCStorageType)0x00 #define DEM_CONTROL_DTC_STORAGE_N_OK (Dem_ReturnControlDTCStorageType)0x01 #define DEM_CONTROL_DTC_WRONG_DTCGROUP (Dem_ReturnControlDTCStorageType)0x02 /* * Dem_ReturnControlEventUpdateType */ typedef uint8 Dem_ReturnControlEventUpdateType; #define DEM_CONTROL_EVENT_UPDATE_OK (Dem_ReturnControlEventUpdateType)0x00 #define DEM_CONTROL_EVENT_N_OK (Dem_ReturnControlEventUpdateType)0x01 #define DEM_CONTROL_EVENT_WRONG_DTCGROUP (Dem_ReturnControlEventUpdateType)0x02 /* * Dem_ReturnGetExtendedDataRecordByDTCType */ typedef uint8 Dem_ReturnGetExtendedDataRecordByDTCType; #define DEM_RECORD_OK (Dem_ReturnGetExtendedDataRecordByDTCType)0x00 #define DEM_RECORD_WRONG_DTC (Dem_ReturnGetExtendedDataRecordByDTCType)0x01 #define DEM_RECORD_WRONG_DTCORIGIN (Dem_ReturnGetExtendedDataRecordByDTCType)0x02 #define DEM_RECORD_DTCKIND (Dem_ReturnGetExtendedDataRecordByDTCType)0x03 #define DEM_RECORD_NUMBER (Dem_ReturnGetExtendedDataRecordByDTCType)0x04 #define DEM_RECORD_BUFFERSIZE (Dem_ReturnGetExtendedDataRecordByDTCType)0x05 #define DEM_RECORD_PENDING (Dem_ReturnGetExtendedDataRecordByDTCType)0x06 /* * Dem_ReturnGetDTCByOccurenceTimeType */ typedef uint8 Dem_ReturnGetDTCByOccurenceTimeType; #define DEM_OCCURR_OK (Dem_ReturnGetDTCByOccurenceTimeType)0x00 #define DEM_OCCURR_WRONG_DTCKIND (Dem_ReturnGetDTCByOccurenceTimeType)0x01 #define DEM_OCCURR_FAILED (Dem_ReturnGetDTCByOccurenceTimeType)0x02 /* * Dem_ReturnGetFreezeFrameDataByDTCType */ typedef uint8 Dem_ReturnGetFreezeFrameDataByDTCType; #define DEM_GET_FFDATABYDTC_OK (Dem_ReturnGetFreezeFrameDataByDTCType)0x00 #define DEM_GET_FFDATABYDTC_WRONG_DTC (Dem_ReturnGetFreezeFrameDataByDTCType)0x01 #define DEM_GET_FFDATABYDTC_WRONG_DTCORIGIN (Dem_ReturnGetFreezeFrameDataByDTCType)0x02 #define DEM_GET_FFDATABYDTC_WRONG_DTCKIND (Dem_ReturnGetFreezeFrameDataByDTCType)0x03 #define DEM_GET_FFDATABYDTC_RECORDNUMBER (Dem_ReturnGetFreezeFrameDataByDTCType)0x04 #define DEM_GET_FFDATABYDTC_WRONG_DATAID (Dem_ReturnGetFreezeFrameDataByDTCType)0x05 #define DEM_GET_FFDATABYDTC_BUFFERSIZE (Dem_ReturnGetFreezeFrameDataByDTCType)0x06 #define DEM_GET_ID_PENDING (Dem_ReturnGetFreezeFrameDataByDTCType)0x07 /* * Dem_ReturnGetSizeOfExtendedDataRecordByDTCType */ typedef uint8 Dem_ReturnGetSizeOfExtendedDataRecordByDTCType; #define DEM_GET_SIZEOFEDRBYDTC_OK (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x00 #define DEM_GET_SIZEOFEDRBYDTC_W_DTC (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x01 #define DEM_GET_SIZEOFEDRBYDTC_W_DTCOR (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x02 #define DEM_GET_SIZEOFEDRBYDTC_W_DTCKI (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x03 #define DEM_GET_SIZEOFEDRBYDTC_W_RNUM (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x04 #define DEM_GET_SIZEOFEDRBYDTC_PENDING (Dem_ReturnGetSizeOfExtendedDataRecordByDTCType)0x05 /* * Dem_ReturnGetSizeOfFreezeFrameType */ typedef uint8 Dem_ReturnGetSizeOfFreezeFrameType; #define DEM_GET_SIZEOFFF_OK (Dem_ReturnGetSizeOfFreezeFrameType)0x00 #define DEM_GET_SIZEOFFF_WRONG_DTC (Dem_ReturnGetSizeOfFreezeFrameType)0x01 #define DEM_GET_SIZEOFFF_WRONG_DTCOR (Dem_ReturnGetSizeOfFreezeFrameType)0x02 #define DEM_GET_SIZEOFFF_WRONG_DTCKIND (Dem_ReturnGetSizeOfFreezeFrameType)0x03 #define DEM_GET_SIZEOFFF_WRONG_RNUM (Dem_ReturnGetSizeOfFreezeFrameType)0x04 #define DEM_GET_SIZEOFFF_PENDING (Dem_ReturnGetSizeOfFreezeFrameType)0x05 /******************************************************* * Definitions where the type is declared in Rte_Dem.h * *******************************************************/ /* * DemDTCKindType definitions */ typedef uint8 Dem_DTCKindType; #ifndef DEM_DTC_KIND_ALL_DTCS #define DEM_DTC_KIND_ALL_DTCS (Dem_DTCKindType)0x01 #endif /* DEM_DTC_KIND_ALL_DTCS */ #ifndef DEM_DTC_KIND_EMISSION_REL_DTCS #define DEM_DTC_KIND_EMISSION_REL_DTCS (Dem_DTCKindType)0x02 #endif /* DEM_DTC_KIND_EMISSION_REL_DTCS */ /* * Dem_InitMonitorKindType definitions */ #ifndef DEM_INIT_MONITOR_CLEAR #define DEM_INIT_MONITOR_CLEAR (Dem_InitMonitorReasonType)1 #endif /* DEM_INIT_MONITOR_CLEAR */ #ifndef DEM_INIT_MONITOR_RESTART #define DEM_INIT_MONITOR_RESTART (Dem_InitMonitorReasonType)2 #endif /* DEM_INIT_MONITOR_RESTART */ /* * Dem_IndicatorStatusType definitions */ #ifndef DEM_INDICATOR_OFF #define DEM_INDICATOR_OFF 0U #endif /* DEM_INDICATOR_OFF */ #ifndef DEM_INDICATOR_CONTINUOUS #define DEM_INDICATOR_CONTINUOUS 1U #endif /* DEM_INDICATOR_CONTINUOUS */ #ifndef DEM_INDICATOR_BLINKING #define DEM_INDICATOR_BLINKING 2U #endif /* DEM_INDICATOR_BLINKING */ #ifndef DEM_INDICATOR_BLINK_CONT #define DEM_INDICATOR_BLINK_CONT 3U #endif /* DEM_INDICATOR_BLINK_CONT */ /* * DemOperationCycleType definitions */ enum { DEM_ACTIVE, // Started by DEM on Dem_PreInit and stopped on Dem_Shutdown DEM_POWER, // Power ON/OFF Cycle DEM_IGNITION, // Ignition ON/OF Cycle DEM_WARMUP, // OBD Warm up Cycle DEM_OBD_DCY, // OBD Driving Cycle DEM_OPERATION_CYCLE_ID_ENDMARK };/** @req DEM480 */ /* * Dem_ReturnGetSeverityOfDTCType */ typedef uint8 Dem_ReturnGetSeverityOfDTCType; #define DEM_GET_SEVERITYOFDTC_OK (Dem_ReturnGetSeverityOfDTCType)0x00 #define DEM_GET_SEVERITYOFDTC_WRONG_DTC (Dem_ReturnGetSeverityOfDTCType)0x01 #define DEM_GET_SEVERITYOFDTC_NOSEVERITY (Dem_ReturnGetSeverityOfDTCType)0x02 #define DEM_GET_SEVERITYOFDTC_PENDING (Dem_ReturnGetSeverityOfDTCType)0x03 /* * Dem_ReturnDisableDTCRecordUpdateType */ typedef uint8 Dem_ReturnDisableDTCRecordUpdateType; #define DEM_DISABLE_DTCRECUP_OK (Dem_ReturnDisableDTCRecordUpdateType)0x00 #define DEM_DISABLE_DTCRECUP_WRONG_DTC (Dem_ReturnDisableDTCRecordUpdateType)0x01 #define DEM_DISABLE_DTCRECUP_WRONG_DTCORIGIN (Dem_ReturnDisableDTCRecordUpdateType)0x02 #define DEM_DISABLE_DTCRECUP_PENDING (Dem_ReturnDisableDTCRecordUpdateType)0x03 /* * Dem_ReturnGetSizeOfFreezeFrameByDTCType */ typedef uint8 Dem_ReturnGetSizeOfFreezeFrameByDTCType; //conflict in type check //#define DEM_GET_SIZEOFFF_OK (Dem_ReturnGetSizeOfFreezeFrameByDTCType)0x00 //#define DEM_GET_SIZEOFFF_WRONG_DTC (Dem_ReturnGetSizeOfFreezeFrameByDTCType)0x01 //#define DEM_GET_SIZEOFFF_WRONG_DTCOR (Dem_ReturnGetSizeOfFreezeFrameByDTCType)0x02 //#define DEM_GET_SIZEOFFF_WRONG_RNUM (Dem_ReturnGetSizeOfFreezeFrameByDTCType)0x03 //#define DEM_GET_SIZEOFFF_PENDING (Dem_ReturnGetSizeOfFreezeFrameByDTCType)0x04 /* * Dem_ReturnGetFreezeFrameDataByDTCType */ //typedef uint8 Dem_ReturnGetFreezeFrameDataByDTCType; //#define DEM_GET_FFDATABYDTC_OK (Dem_ReturnGetFreezeFrameDataByDTCType)0x00 //#define DEM_GET_FFDATABYDTC_WRONG_DTC (Dem_ReturnGetFreezeFrameDataByDTCType)0x01 //#define DEM_GET_FFDATABYDTC_WRONG_DTCORIGIN (Dem_ReturnGetFreezeFrameDataByDTCType)0x02 //#define DEM_GET_FFDATABYDTC_WRONG_RECORDNUMBER (Dem_ReturnGetFreezeFrameDataByDTCType)0x03 //#define DEM_GET_FFDATABYDTC_WRONG_BUFFERSIZE (Dem_ReturnGetFreezeFrameDataByDTCType)0x04 #define DEM_GET_FFDATABYDTC_PENDING (Dem_ReturnGetFreezeFrameDataByDTCType)0x05 #define DEM_RECORD_WRONG_NUMBER (Dem_ReturnGetExtendedDataRecordByDTCType)0x03 /* Type from Dem 4.3.0. Used by FiM. Should be moved but kept here as it is not used in Dem service component. */ typedef uint8 Dem_MonitorStatusType; #define DEM_MONITOR_STATUS_TF 0x01u #define DEM_MONITOR_STATUS_TNCTOC 0x02u /* * DemOBDEngineType */ #define DEM_IGNITION_COMPR 0x00 #define DEM_IGNITION_SPARK 0x01 /* * DemEventOBDReadinessGroup */ /* @req DEM349 */ typedef uint8 Dem_EventOBDReadinessGroup; #define DEM_OBD_RDY_NONE (Dem_EventOBDReadinessGroup)0x00 #define DEM_OBD_RDY_AC (Dem_EventOBDReadinessGroup)0x01 #define DEM_OBD_RDY_BOOSTPR (Dem_EventOBDReadinessGroup)0x02 #define DEM_OBD_RDY_CAT (Dem_EventOBDReadinessGroup)0x03 #define DEM_OBD_RDY_CMPRCMPT (Dem_EventOBDReadinessGroup)0x04 #define DEM_OBD_RDY_EGSENS (Dem_EventOBDReadinessGroup)0x05 #define DEM_OBD_RDY_ERG (Dem_EventOBDReadinessGroup)0x06 #define DEM_OBD_RDY_EVAP (Dem_EventOBDReadinessGroup)0x07 #define DEM_OBD_RDY_FLSYS (Dem_EventOBDReadinessGroup)0x08 #define DEM_OBD_RDY_HCCAT (Dem_EventOBDReadinessGroup)0x09 #define DEM_OBD_RDY_HTCAT (Dem_EventOBDReadinessGroup)0x0A #define DEM_OBD_RDY_MISF (Dem_EventOBDReadinessGroup)0x0B #define DEM_OBD_RDY_NOXCAT (Dem_EventOBDReadinessGroup)0x0C #define DEM_OBD_RDY_O2SENS (Dem_EventOBDReadinessGroup)0x0D #define DEM_OBD_RDY_O2SENSHT (Dem_EventOBDReadinessGroup)0x0E #define DEM_OBD_RDY_PMFLT (Dem_EventOBDReadinessGroup)0x0F #define DEM_OBD_RDY_SECAIR (Dem_EventOBDReadinessGroup)0x10 typedef uint8 Dem_IUMPRGroup; #define DEM_IUMPR_AFRI1 (Dem_IUMPRGroup)0x00 #define DEM_IUMPR_AFRI2 (Dem_IUMPRGroup)0x01 #define DEM_IUMPR_BOOSTPRS (Dem_IUMPRGroup)0x02 #define DEM_IUMPR_CAT1 (Dem_IUMPRGroup)0x03 #define DEM_IUMPR_CAT2 (Dem_IUMPRGroup)0x04 #define DEM_IUMPR_EGR (Dem_IUMPRGroup)0x05 #define DEM_IUMPR_EGSENSOR (Dem_IUMPRGroup)0x06 #define DEM_IUMPR_EVAP (Dem_IUMPRGroup)0x07 #define DEM_IUMPR_FLSYS (Dem_IUMPRGroup)0x08 #define DEM_IUMPR_NMHCCAT (Dem_IUMPRGroup)0x09 #define DEM_IUMPR_NOXADSORB (Dem_IUMPRGroup)0x0A #define DEM_IUMPR_NOXCAT (Dem_IUMPRGroup)0x0B #define DEM_IUMPR_OXS1 (Dem_IUMPRGroup)0x0C #define DEM_IUMPR_OXS2 (Dem_IUMPRGroup)0x0D #define DEM_IUMPR_PF1 (Dem_IUMPRGroup)0x0E #define DEM_IUMPR_PF2 (Dem_IUMPRGroup)0x0F #define DEM_IUMPR_PMFILTER (Dem_IUMPRGroup)0x10 #define DEM_IUMPR_PRIVATE (Dem_IUMPRGroup)0x11 #define DEM_IUMPR_SAIR (Dem_IUMPRGroup)0x12 #define DEM_IUMPR_SECOXS1 (Dem_IUMPRGroup)0x13 #define DEM_IUMPR_SECOXS2 (Dem_IUMPRGroup)0x14 typedef uint8 Dem_RatioKindType; #define DEM_RATIO_API (Dem_RatioKindType) 0x00 #define DEM_RATIO_OBSERVER (Dem_RatioKindType) 0x01 #endif /*DEM_TYPES_H_*/
2301_81045437/classic-platform
diagnostic/Dem/inc/Dem_Types.h
C
unknown
17,770
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /*lint -w2 */ /* INPROVEMENT: This note should be enabled */ /*lint -e9025 */ /* * General requirements */ /* @req DEM126 */ /* !req DEM151 Partially */ /* @req DEM152 */ /* !req DEM013 Only 14229-1 format supported */ /* @req DEM645 Both UDS and OBD format supported */ /* @req DEM277 Both UDS and OBD format supported */ /* @req DEM113 */ /* @req DEM267 */ /* !req DEM268 */ /* @req DEM364 */ /* @req DEM114 */ /* @req DEM124 */ /* @req DEM370 */ /* @req DEM386 UDS status bit 0 transitions */ /* @req DEM389 UDS status bit 1 transitions */ /* @req DEM390 UDS status bit 2 transitions */ /* @req DEM391 UDS status bit 3 transitions */ /* @req DEM392 UDS status bit 4 transitions */ /* @req DEM393 UDS status bit 5 transitions */ /* @req DEM394 UDS status bit 6 transitions */ /* @req DEM395 UDS status bit 7 transitions */ /* @req 4.2.2/SWS_Dem_01102 DTC suppression shall not stop event processing of the corresponding DTC. */ /* @req DEM551 *//* Block write triggered if configured*/ /* @req DEM552 *//* Block write not triggered if occurance has reached ImmediateNvStorageLimit */ /* @req DEM536 *//* Event combination type 1 and 2 supported */ #include <string.h> #include "Dem.h" #if defined(USE_NVM) #include "NvM.h" /** @req DEM176.NvM */ #endif #include "SchM_Dem.h" #include "MemMap.h" #include "Cpu.h" #include "Dem_Types.h" #include "Dem_Lcfg.h" #include "Dem_Internal.h" #if defined(USE_DEM_EXTENSION) #include "Dem_Extension.h" #endif #define USE_DEBUG_PRINTF #include "debug.h" #if defined(USE_RTE) /*lint -e18 duplicate declarations hidden behinde ifdef */ #include "Rte_Dem.h" #endif #if (DEM_TRIGGER_DLT_REPORTS == STD_ON) #include "Dlt.h" #endif #if defined(USE_FIM) #include "FiM.h" #endif #include "Dem_NvM.h" /* * Local defines */ #define DEM_EXT_DATA_IN_PRE_INIT (DEM_MAX_NUMBER_EXT_DATA_PRE_INIT > 0) #define DEM_EXT_DATA_IN_PRI_MEM ((DEM_MAX_NUMBER_EXT_DATA_PRI_MEM > 0) && ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON))) #define DEM_EXT_DATA_IN_SEC_MEM ((DEM_MAX_NUMBER_EXT_DATA_SEC_MEM > 0) && (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON)) #define DEM_FF_DATA_IN_PRE_INIT (DEM_MAX_NUMBER_FF_DATA_PRE_INIT > 0) #define DEM_FF_DATA_IN_PRI_MEM ((DEM_MAX_NUMBER_FF_DATA_PRI_MEM > 0) && ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON))) #define DEM_FF_DATA_IN_SEC_MEM ((DEM_MAX_NUMBER_FF_DATA_SEC_MEM > 0) && (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON)) #define DEM_DEFAULT_EVENT_STATUS (DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR | DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE) #define DEM_PRESTORAGE_FF_DATA_IN_MEM (DEM_MAX_NUMBER_PRESTORED_FF > 0) #define DEM_PID_IDENTIFIER_SIZE_OF_BYTES 1 // OBD #define DEM_FAILURE_CNTR_MAX 255 #define DEM_AGING_CNTR_MAX 255 #define DEM_INDICATOR_CNTR_MAX 255 #define DEM_OCCURENCE_COUNTER_MAX 0xFFFF #define MOST_RECENT_FF_RECORD 0xFF #define FREE_PERMANENT_DTC_ENTRY 0u #define ALL_EXTENDED_DATA_RECORDS 0xFF #define IS_VALID_EXT_DATA_RECORD(_x) ((0x01 <= (_x)) && (0xEF >= (_x))) #define IS_VALID_EVENT_ID(_x) (((_x) > 0) && ((_x) <= DEM_EVENT_ID_LAST_VALID_ID)) #define IS_VALID_INDICATOR_ID(_x) ((_x) < DEM_NOF_INDICATORS) #define IS_SUPPORTED_ORIGIN(_x) ((DEM_DTC_ORIGIN_PRIMARY_MEMORY == (_x)) || (DEM_DTC_ORIGIN_SECONDARY_MEMORY == (_x))) #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) #define NUM_STORED_BITS 2u #define NOF_EVENTS_PER_BYTE (8u/NUM_STORED_BITS) #define GET_UDSBIT_BYTE_INDEX(_eventId) (((_eventId)-1u)/NOF_EVENTS_PER_BYTE) #define GET_UDS_STARTBIT(_eventId) ((((_eventId)-1u)%NOF_EVENTS_PER_BYTE)*2u) #define UDS_BITMASK 3u #define UDS_TFSLC_BIT 0u #define UDS_TNCSLC_BIT 1u #define UDS_STATUS_BIT_MAGIC UDS_BITMASK #define UDS_STATUS_BIT_MAGIC_INDEX ((DEM_MAX_NUMBER_EVENT + (NOF_EVENTS_PER_BYTE - 1u))/NOF_EVENTS_PER_BYTE) #endif #define DEM_REC_NUM_AND_NUM_DIDS_SIZE 2u #define VALIDATE_RV(_exp,_api,_err,_rv ) \ if( !(_exp) ) { \ DET_REPORTERROR(DEM_MODULE_ID, 0, _api, _err); \ return _rv; \ } #define VALIDATE_NO_RV(_exp,_api,_err ) \ if( !(_exp) ) { \ DET_REPORTERROR(DEM_MODULE_ID, 0, _api, _err); \ return; \ } #if (DEM_PTO_SUPPORT == STD_ON) #error "DEM_PTO_SUPPORT is set to STD_ON, this is not supported by the code." #endif #if !((DEM_TYPE_OF_DTC_SUPPORTED == DEM_DTC_TRANSLATION_ISO15031_6) || (DEM_TYPE_OF_DTC_SUPPORTED == DEM_DTC_TRANSLATION_ISO14229_1)) #error "DEM_TYPE_OF_DTC_SUPPORTED is not set to ISO15031-6 or ISO14229-1. Only these are supported by the code." #endif #if !defined(USE_DEM_EXTENSION) #if defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) #error "DEM_FREEZE_FRAME_CAPTURE cannot be DEM_TRIGGER_EXTENSION since Dem extension is not used!" #endif #if defined(DEM_EXTENDED_DATA_CAPTURE_EXTENSION) #error "DEM_EXTENDED_DATA_CAPTURE cannot be DEM_TRIGGER_EXTENSION since Dem extension is not used!" #endif #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) #error "DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION cannot be used since Dem extension is not used!" #endif #if defined(DEM_FAILURE_PROCESSING_DEM_EXTENSION) #error "DEM_FAILURE_PROCESSING_DEM_EXTENSION cannot be used since Dem extension is not used!" #endif #if defined(DEM_AGING_PROCESSING_DEM_EXTENSION) #error "DEM_AGING_PROCESSING_DEM_EXTENSION cannot be used since Dem extension is not used!" #endif #endif #if defined(DEM_EXTENDED_DATA_CAPTURE_EVENT_MEMORY_STORAGE) #error "DEM_EXTENDED_DATA_CAPTURE_EVENT_MEMORY_STORAGE is not supported!" #endif #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) || (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) || (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) #define DEM_USE_MEMORY_FUNCTIONS #endif #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) #define DEM_ASSERT(_exp) switch (1) {case 0: break; case (_exp): break; } #endif #if (DEM_TEST_FAILED_STORAGE == STD_ON) #define GET_STORED_STATUS_BITS(_x) ((_x) & (DEM_TEST_FAILED_SINCE_LAST_CLEAR | DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR | DEM_PENDING_DTC | DEM_CONFIRMED_DTC | DEM_TEST_FAILED)) #else #define GET_STORED_STATUS_BITS(_x) ((_x) & (DEM_TEST_FAILED_SINCE_LAST_CLEAR | DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR | DEM_PENDING_DTC | DEM_CONFIRMED_DTC)) #endif #define IS_VALID_EVENT_STATUS(_x) ((DEM_EVENT_STATUS_PREPASSED == _x) || (DEM_EVENT_STATUS_PASSED == _x) || (DEM_EVENT_STATUS_PREFAILED == _x) || (DEM_EVENT_STATUS_FAILED == _x)) #if (DEM_NOF_EVENT_INDICATORS > 0) #define DEM_USE_INDICATORS #endif #define TO_OBD_FORMAT(_x) ((_x)<<8u) #define IS_VALID_DTC_FORMAT(_x) ((DEM_DTC_FORMAT_UDS == (_x)) || (DEM_DTC_FORMAT_OBD == (_x))) #if (DEM_IMMEDIATE_NV_STORAGE == STD_ON) #define DEM_USE_IMMEDIATE_NV_STORAGE #endif #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) #define TO_COMBINED_EVENT_ID(_x) ((_x) | 0x8000u) #define IS_COMBINED_EVENT_ID(_x) (0u != ((_x) & 0x8000u)) #define TO_COMBINED_EVENT_CFG_IDX(_x) ((_x) & (uint16)(~0x8000u)) #define IS_VALID_COMBINED_ID(_x) ((_x) < DEM_NOF_COMBINED_DTCS) /* Clear all combined event aging counter when sub event failes */ #define DEM_CLEAR_COMBINED_AGING_COUNTERS_ON_FAIL #if 0 /* Require all sub events tested and passed to process aging */ #define DEM_COMBINED_DTC_STATUS_AGING #endif #endif /* * Local types */ // DtcFilterType typedef struct { Dem_EventStatusExtendedType dtcStatusMask; Dem_DTCKindType dtcKind; Dem_DTCOriginType dtcOrigin; Dem_FilterWithSeverityType filterWithSeverity; Dem_DTCSeverityType dtcSeverityMask; Dem_FilterForFDCType filterForFaultDetectionCounter; uint16 DTCIndex; Dem_DTCFormatType dtcFormat; } DtcFilterType; // FreezeFrameRecordFilterType typedef struct { uint16 ffIndex; Dem_DTCFormatType dtcFormat; } FreezeFrameRecordFilterType; // DisableDtcStorageType typedef struct { boolean settingDisabled; Dem_DTCGroupType dtcGroup; Dem_DTCKindType dtcKind; } DisableDtcSettingType; // State variable typedef enum { DEM_UNINITIALIZED = 0, DEM_PREINITIALIZED, DEM_INITIALIZED, DEM_SHUTDOWN } Dem_StateType; /** @req DEM169 */ static Dem_StateType demState = DEM_UNINITIALIZED; #if defined(USE_FIM) static boolean DemFiMInit = FALSE; #endif // Help pointer to configuration set static const Dem_ConfigSetType *configSet; /* * Allocation of DTC filter parameters */ static DtcFilterType dtcFilter; /* * Allocation of freeze frame record filter */ static FreezeFrameRecordFilterType ffRecordFilter; /* * Allocation of Disable/Enable DTC setting parameters */ static DisableDtcSettingType disableDtcSetting; /* * Allocation of operation cycle state list */ /* NOTE: Do not change this without also changing generation of measurement tags */ static Dem_OperationCycleStateType operationCycleStateList[DEM_OPERATION_CYCLE_ID_ENDMARK]; /* * Allocation of local event status buffer */ /* NOTE: Do not change this without also changing generation of measurement tags */ static EventStatusRecType eventStatusBuffer[DEM_MAX_NUMBER_EVENT]; /* * Allocation of pre-init event memory (used between pre-init and init). Only one * memory regardless of event destination. */ #if ( DEM_FF_DATA_IN_PRE_INIT ) static FreezeFrameRecType preInitFreezeFrameBuffer[DEM_MAX_NUMBER_FF_DATA_PRE_INIT]; #endif #if ( DEM_EXT_DATA_IN_PRE_INIT ) static ExtDataRecType preInitExtDataBuffer[DEM_MAX_NUMBER_EXT_DATA_PRE_INIT]; #endif /* * Allocation of primary event memory ramlog (after init) in uninitialized memory */ #define ADMIN_MAGIC 0xBABE /** @req DEM162 */ #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) #define PRI_MEM_EVENT_BUFFER_ADMIN_INDEX DEM_MAX_NUMBER_EVENT_PRI_MEM EventRecType priMemEventBuffer[DEM_MAX_NUMBER_EVENT_PRI_MEM + 1];/* + 1 for admin data */ static boolean priMemOverflow = FALSE;/* @req DEM397 */ #if ( DEM_FF_DATA_IN_PRI_MEM ) FreezeFrameRecType priMemFreezeFrameBuffer[DEM_MAX_NUMBER_FF_DATA_PRI_MEM]; #endif #if (DEM_EXT_DATA_IN_PRI_MEM) ExtDataRecType priMemExtDataBuffer[DEM_MAX_NUMBER_EXT_DATA_PRI_MEM]; #endif #endif /* * Allocation of secondary event memory ramlog (after init) in uninitialized memory */ /** @req DEM162 */ #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) #define SEC_MEM_EVENT_BUFFER_ADMIN_INDEX DEM_MAX_NUMBER_EVENT_SEC_MEM EventRecType secMemEventBuffer[DEM_MAX_NUMBER_EVENT_SEC_MEM + 1];/* + 1 for admin data */ static boolean secMemOverflow = FALSE;/* @req DEM397 */ #if (DEM_FF_DATA_IN_SEC_MEM) FreezeFrameRecType secMemFreezeFrameBuffer[DEM_MAX_NUMBER_FF_DATA_SEC_MEM]; #endif #if (DEM_EXT_DATA_IN_SEC_MEM) ExtDataRecType secMemExtDataBuffer[DEM_MAX_NUMBER_EXT_DATA_SEC_MEM]; #endif #endif /* * Allocation of permanent event memory ramlog (after init) in uninitialized memory */ /** @req DEM162 */ #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) #define PERM_MEM_EVENT_BUFFER_ADMIN_INDEX DEM_MAX_NUMBER_EVENT_PERM_MEM PermanentDTCType permMemEventBuffer[DEM_MAX_NUMBER_EVENT_PERM_MEM]; /* Free entry == 0u */ #endif /* * Allocation of event memory for pre storage of freeze frames */ /** @req DEM191 */ #if ( DEM_PRESTORAGE_FF_DATA_IN_MEM ) FreezeFrameRecType memPreStoreFreezeFrameBuffer[DEM_MAX_NUMBER_PRESTORED_FF]; #endif #if defined(DEM_USE_MEMORY_FUNCTIONS) && (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) /* Buffer for storing subset of UDS status bits for all events */ uint8 statusBitSubsetBuffer[DEM_MEM_STATUSBIT_BUFFER_SIZE]; #endif #if (DEM_USE_TIMESTAMPS == STD_ON) /* Timestamp for events */ static uint32 Event_TimeStamp = 0; /* Timestamp for extended data */ static uint32 ExtData_TimeStamp = 0; /* *Allocation of freezeFrame storage timestamp,record the time order */ /**private variable for freezeframe */ static uint32 FF_TimeStamp = 0; #endif #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) typedef struct { boolean SuppressedByDTC:1;/*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean SuppressedByEvent:1;/*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ }DemDTCSuppressionType; static DemDTCSuppressionType DemDTCSuppressed[DEM_NOF_DTCS]; #endif #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) static boolean DemEnableConditions[DEM_NUM_ENABLECONDITIONS]; #endif #define NO_DTC_DISABLED 0xFFFFFFFFUL typedef struct { uint32 DTC; Dem_DTCOriginType Origin; }DtcRecordUpdateDisableType; static DtcRecordUpdateDisableType DTCRecordDisabled; #if defined(DEM_USE_INDICATORS) /* @req DEM499 */ #define INDICATOR_FAILED_DURING_FAILURE_CYCLE 1u #define INDICATOR_PASSED_DURING_FAILURE_CYCLE (1u<<1u) #define INDICATOR_FAILED_DURING_HEALING_CYCLE (1u<<2u) #define INDICATOR_PASSED_DURING_HEALING_CYCLE (1u<<3u) typedef struct { Dem_EventIdType EventID; uint16 InternalIndicatorId; uint8 FailureCounter; uint8 HealingCounter; uint8 OpCycleStatus; }IndicatorStatusType; typedef struct { Dem_EventIdType EventID; uint8 IndicatorId; uint8 FailureCounter; uint8 HealingCounter; }IndicatorNvRecType; /* Buffer for storing event indicators internally */ static IndicatorStatusType indicatorStatusBuffer[DEM_NOF_EVENT_INDICATORS]; #if defined(DEM_USE_MEMORY_FUNCTIONS) /* Buffer for storing event indicator status in NvRam */ IndicatorNvRecType indicatorBuffer[DEM_NOF_EVENT_INDICATORS]; #endif #endif #if defined(DEM_USE_IUMPR) // Each index corresponds to RatioID Dem_RatiosNvm iumprBuffer; static Dem_RatioStatusType iumprBufferLocal[DEM_IUMPR_REGISTERED_COUNT]; // IUMPR general denominator buffer Dem_RatioGeneralDenominatorType generalDenominatorBuffer; // IUMPT ignition cycle count buffer uint16 ignitionCycleCountBuffer; // IUMPR additional denominator conditions buffer #define DEM_IUMPR_ADDITIONAL_DENOMINATORS_COUNT 4 static Dem_IumprDenomCondType iumprAddiDenomCondBuffer[DEM_IUMPR_ADDITIONAL_DENOMINATORS_COUNT]; #endif /* * Local functions * */ #ifdef DEM_USE_MEMORY_FUNCTIONS #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) static void SetDefaultUDSStatusBitSubset(void); #endif #if ( DEM_FF_DATA_IN_PRE_INIT || DEM_FF_DATA_IN_PRI_MEM ) static boolean storeOBDFreezeFrameDataMem(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin); #endif #if ( DEM_FF_DATA_IN_PRE_INIT || DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM ) static boolean storeFreezeFrameDataMem(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin); #endif static boolean deleteFreezeFrameDataMem(const Dem_EventParameterType *eventParam, Dem_DTCOriginType origin, boolean combinedDTC); static boolean deleteExtendedDataMem(const Dem_EventParameterType *eventParam, Dem_DTCOriginType origin, boolean combinedDTC); #endif static Std_ReturnType getEventFailed(Dem_EventIdType eventId, boolean *eventFailed); #if (DEM_USE_TIMESTAMPS == STD_ON) && defined(DEM_USE_MEMORY_FUNCTIONS) #if (DEM_UNIT_TEST == STD_ON) void rearrangeEventTimeStamp(uint32 *timeStamp); #else static void rearrangeEventTimeStamp(uint32 *timeStamp); #endif #endif #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) static void storeEventIndicators(const Dem_EventParameterType *eventParam); #endif static Std_ReturnType getEventStatus(Dem_EventIdType eventId, Dem_EventStatusExtendedType *eventStatusExtended); static void getFFClassReference(const Dem_EventParameterType *eventParam, Dem_FreezeFrameClassType **ffClassTypeRef); static Dem_FreezeFrameClassTypeRefIndex getFFIdx(const Dem_EventParameterType *eventParam); #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) uint8 getEventAgingCntr(const Dem_EventParameterType *eventParameter); #endif #if (DEM_UNIT_TEST == STD_ON) /* * Procedure: zeroPriMemBuffers * Description: Fill the primary buffers with zeroes */ /*lint -efunc(714, demZeroPriMemBuffers) */ void demZeroPriMemBuffers(void) { #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) memset(priMemEventBuffer, 0, sizeof(priMemEventBuffer)); priMemOverflow = FALSE; #if (DEM_FF_DATA_IN_PRI_MEM) memset(priMemFreezeFrameBuffer, 0, sizeof(priMemFreezeFrameBuffer)); #endif #if (DEM_EXT_DATA_IN_PRI_MEM) memset(priMemExtDataBuffer, 0, sizeof(priMemExtDataBuffer)); #endif #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) memset(indicatorBuffer, 0, sizeof(indicatorBuffer)); #endif #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) memset(statusBitSubsetBuffer, 0, sizeof(statusBitSubsetBuffer)); #endif #endif } void demZeroSecMemBuffers(void) { #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) memset(secMemEventBuffer, 0, sizeof(secMemEventBuffer)); secMemOverflow = FALSE; #if ( DEM_FF_DATA_IN_SEC_MEM ) memset(secMemFreezeFrameBuffer, 0, sizeof(secMemFreezeFrameBuffer)); #endif #if ( DEM_EXT_DATA_IN_SEC_MEM ) memset(secMemExtDataBuffer, 0, sizeof(secMemExtDataBuffer)); #endif #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) memset(statusBitSubsetBuffer, 0, sizeof(statusBitSubsetBuffer)); #endif #endif } void demZeroPermMemBuffers(void) { #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) memset(permMemEventBuffer, FREE_PERMANENT_DTC_ENTRY, sizeof(permMemEventBuffer)); #endif } void demZeroPreStoreFFMemBuffer(void) { #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) memset(memPreStoreFreezeFrameBuffer, 0x00, sizeof(memPreStoreFreezeFrameBuffer)); #endif } #if defined(DEM_USE_IUMPR) void demZeroIumprBuffer(void) { memset(&iumprBuffer, 0, sizeof(iumprBuffer)); } void demSetIgnitionCounterToMax(void) { ignitionCycleCountBuffer = 65535; } void demSetDenominatorToMax(Dem_RatioIdType ratioId) { iumprBufferLocal[ratioId].denominator.value = 65535; } void demSetNumeratorToMax(Dem_RatioIdType ratioId) { iumprBufferLocal[ratioId].numerator.value = 65535; } #endif #endif #ifdef DEM_USE_MEMORY_FUNCTIONS static boolean eventIsStoredInMem(Dem_EventIdType eventId, const EventRecType* eventBuffer, uint32 eventBufferSize) { boolean eventIdFound = FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(eventId) ) { /* Entry is for a combined event */ const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; const Dem_DTCClassType *DTCClass = CombDTCCfg->DTCClassRef; for (uint32 i = 0u;((i < eventBufferSize) && (eventIdFound == FALSE)); i++) { for(uint16 evIdx = 0; (evIdx < DTCClass->NofEvents) && (eventIdFound == FALSE); evIdx++) { eventIdFound = (eventBuffer[i].EventData.eventId == DTCClass->Events[evIdx])? TRUE: FALSE; } } } else { for (uint32 i = 0u;((i < eventBufferSize) && (eventIdFound == FALSE)); i++) { eventIdFound = (eventBuffer[i].EventData.eventId == eventId)? TRUE: FALSE; } } #else for (uint32 i = 0u;((i < eventBufferSize) && (eventIdFound == FALSE)); i++) { eventIdFound = (eventBuffer[i].EventData.eventId == eventId)? TRUE: FALSE; } #endif return eventIdFound; } #endif /** * Determines if a DTC is available or not * @param DTCClass * @return TRUE: DTC available, FALSE: DTC NOT available */ static boolean DTCIsAvailable(const Dem_DTCClassType *DTCClass) { if( (TRUE == DTCClass->DTCRef->DTCUsed) #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) && (FALSE == DemDTCSuppressed[DTCClass->DTCIndex].SuppressedByDTC) && (FALSE == DemDTCSuppressed[DTCClass->DTCIndex].SuppressedByEvent) #endif ) { return TRUE; } else { return FALSE; } } /* * Procedure: checkDtcKind * Description: Return TRUE if "dtcKind" match the events DTCKind or "dtcKind" * is "DEM_DTC_KIND_ALL_DTCS" otherwise FALSE. */ static boolean checkDtcKind(Dem_DTCKindType dtcKind, const Dem_EventParameterType *eventParam) { boolean result = FALSE; if( (NULL != eventParam->DTCClassRef) && (DTCIsAvailable(eventParam->DTCClassRef) == TRUE) ) { result = ( (dtcKind == DEM_DTC_KIND_ALL_DTCS) || (DEM_NON_EMISSION_RELATED != (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind) )? TRUE: FALSE; } return result; } /** * Checks if event status matches current filter. * @param filterMask * @param eventStatus * @return */ static boolean checkDtcStatusMask(Dem_EventStatusExtendedType filterMask, Dem_EventStatusExtendedType eventStatus) { boolean result = FALSE; if( (DEM_DTC_STATUS_MASK_ALL == filterMask) || (0 != (eventStatus & filterMask)) ) { result = TRUE; } return result; } /** * Checks if DTC is available on specific format * @param eventParam * @param dtcFormat * @return TRUE: DTC is available on specific format, FALSE: Event is not available on specific format. */ static boolean eventHasDTCOnFormat(const Dem_EventParameterType *eventParam, Dem_DTCFormatType dtcFormat) { boolean ret = FALSE; if(( NULL != eventParam) && (NULL != eventParam->DTCClassRef) ) { ret = ( ((DEM_DTC_FORMAT_UDS == dtcFormat) && (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->UDSDTC)) || ((DEM_DTC_FORMAT_OBD == dtcFormat) && (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->OBDDTC)))? TRUE: FALSE; } return ret; } /** * Checks if DTC is avalailable on specific format. * @param eventParam * @param dtcFormat * @return */ static boolean DTCISAvailableOnFormat(const Dem_DTCClassType *DTCClass, Dem_DTCFormatType dtcFormat) { boolean ret = FALSE; if( NULL != DTCClass ) { ret = ( ((DEM_DTC_FORMAT_UDS == dtcFormat) && (DEM_NO_DTC != DTCClass->DTCRef->UDSDTC)) || ((DEM_DTC_FORMAT_OBD == dtcFormat) && (DEM_NO_DTC != DTCClass->DTCRef->OBDDTC)))? TRUE: FALSE; } return ret; } /** * Checks if dtc is a DTC group * @param dtc * @param dtcFormat * @param groupLower * @param groupUpper * @return TRUE: dtc is group, FALSE: dtc is NOT a group */ static boolean dtcIsGroup(uint32 dtc, Dem_DTCFormatType dtcFormat, uint32 *groupLower, uint32 *groupUpper) { const Dem_GroupOfDtcType * DTCGroups = configSet->GroupOfDtc; boolean groupFound = FALSE; if( DEM_DTC_FORMAT_UDS == dtcFormat ) { while( (FALSE == DTCGroups->Arc_EOL) && (FALSE == groupFound) ) { if( dtc == DTCGroups->DemGroupDTCs ) { *groupLower = DTCGroups->DemGroupDTCs; groupFound = TRUE; } DTCGroups++; } *groupUpper = DTCGroups->DemGroupDTCs - 1u; } return groupFound; } /* * Procedure: checkDtcGroup * Description: Return TRUE if "dtc" match the events DTC or "dtc" is * "DEM_DTC_GROUP_ALL_DTCS" otherwise FALSE. */ /** * Checks is event has DTC matching "dtc". "dtc" can be a group or a specific DTC * @param dtc * @param eventParam * @param dtcFormat * @param checkFormat * @return TRUE: event has DTC matching "dtc", FALSE: DTC does NOT have DTC matching "dtc" */ static boolean checkDtcGroup(uint32 dtc, const Dem_EventParameterType *eventParam, Dem_DTCFormatType dtcFormat) { /* NOTE: dtcFormat determines the format of dtc */ boolean result = FALSE; if( (NULL != eventParam->DTCClassRef) && (TRUE == DTCIsAvailable(eventParam->DTCClassRef)) ) { if( DEM_DTC_GROUP_ALL_DTCS == dtc ) { result = (DEM_DTC_FORMAT_UDS == dtcFormat) ? (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->UDSDTC) : (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->OBDDTC); } else if( DEM_DTC_GROUP_EMISSION_REL_DTCS == dtc ) { result = (DEM_DTC_FORMAT_UDS == dtcFormat) ? ((DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->UDSDTC) && (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->OBDDTC)) : (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->OBDDTC); } else { /* Not "ALL DTCs" */ if( TRUE == eventHasDTCOnFormat(eventParam, dtcFormat) ) { uint32 DTCGroupLower; uint32 DTCGroupUpper; if( TRUE == dtcIsGroup(dtc, dtcFormat, &DTCGroupLower, &DTCGroupUpper) ) { if( DEM_DTC_FORMAT_UDS == dtcFormat ) { result = ((eventParam->DTCClassRef->DTCRef->UDSDTC >= DTCGroupLower) && (eventParam->DTCClassRef->DTCRef->UDSDTC < DTCGroupUpper))? TRUE: FALSE; } else { result = ((eventParam->DTCClassRef->DTCRef->OBDDTC >= DTCGroupLower) && (eventParam->DTCClassRef->DTCRef->OBDDTC < DTCGroupUpper))? TRUE: FALSE; } } else { result = (DEM_DTC_FORMAT_UDS == dtcFormat) ? (dtc == eventParam->DTCClassRef->DTCRef->UDSDTC) : (dtc == TO_OBD_FORMAT(eventParam->DTCClassRef->DTCRef->OBDDTC)); } } } } return result; } #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /** * Checks if an event is emission related and MIL activating * @param eventParam * @return TRUE: event is emission related, FALSE: event is not emission related */ static boolean eventIsEmissionRelatedMILActivating(const Dem_EventParameterType *eventParam) { boolean ret = FALSE; if( DEM_EMISSION_RELATED_MIL_ACTIVATING == (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind ) { ret = TRUE; } return ret; } #endif #if (DEM_OBD_DISPLACEMENT_SUPPORT == STD_ON) && (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) && defined (DEM_USE_MEMORY_FUNCTIONS) /** * Checks if an event is emission related * @param eventParam * @return TRUE: event is emission related, FALSE: event is not emission related */ static boolean eventIsEmissionRelated(const Dem_EventParameterType *eventParam) { boolean ret = FALSE; if( (DEM_EMISSION_RELATED_MIL_ACTIVATING == (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind) || (DEM_EMISSION_RELATED == (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind) ){ ret = TRUE; } return ret; } #endif /* * Procedure: checkDtcOrigin * Description: Return TRUE if "dtcOrigin" match any of the events DTCOrigin otherwise FALSE. */ static inline boolean checkDtcOrigin(Dem_DTCOriginType dtcOrigin, const Dem_EventParameterType *eventParam, boolean allowPermanentMemory) { boolean originMatch = FALSE; if( (TRUE == allowPermanentMemory) && (DEM_DTC_ORIGIN_PERMANENT_MEMORY == dtcOrigin) ) { #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /* Check if dtc is stored in permanent memory*/ /* @req DEM301 */ if( TRUE == eventIsEmissionRelatedMILActivating(eventParam) ) { for( uint32 i = 0; (i < DEM_MAX_NUMBER_EVENT_PERM_MEM) && (FALSE == originMatch); i++) { if( eventParam->DTCClassRef->DTCRef->OBDDTC == permMemEventBuffer[i].OBDDTC) { /* DTC is stored */ originMatch = TRUE; } } } #endif } else { originMatch = (eventParam->EventClass->EventDestination == dtcOrigin)? TRUE: FALSE; } return originMatch; } /** * Return TRUE if "dtcSeverityMask" match the DTC severity otherwise FALSE. * @param dtcSeverityMask * @param DTCClass * @return */ static boolean checkDtcSeverityMask(const Dem_DTCSeverityType dtcSeverityMask, const Dem_DTCClassType *DTCClass) { return ((NULL_PTR != DTCClass) && ( 0 != (DTCClass->DTCSeverity & dtcSeverityMask)))? TRUE: FALSE; } /* * Procedure: lookupEventStatusRec * Description: Returns the pointer to event id parameters of "eventId" in "*eventStatusBuffer", * if not found NULL is returned. */ void lookupEventStatusRec(Dem_EventIdType eventId, EventStatusRecType **const eventStatusRec) { if ( IS_VALID_EVENT_ID(eventId)) { *eventStatusRec = &eventStatusBuffer[eventId - 1]; } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_UNEXPECTED_EXECUTION); *eventStatusRec = NULL; } } /* * Procedure: lookupEventIdParameter * Description: Returns the pointer to event id parameters of "eventId" in "*eventIdParam", * if not found NULL is returned. */ void lookupEventIdParameter(Dem_EventIdType eventId, const Dem_EventParameterType **const eventIdParam) { const Dem_EventParameterType *EventIdParamList = configSet->EventParameter; if (IS_VALID_EVENT_ID(eventId)) { *eventIdParam = &EventIdParamList[eventId - 1]; } else { *eventIdParam = NULL; } } /* * Procedure: checkEntryValid * Description: Returns whether event id "eventId" is a valid entry in primary memory */ #ifdef DEM_USE_MEMORY_FUNCTIONS static boolean checkEntryValid(Dem_EventIdType eventId, Dem_DTCOriginType origin, boolean allowCombinedID){ const Dem_EventParameterType *EventIdParam = NULL; EventStatusRecType *eventStatusRec = NULL; boolean isValid = FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (TRUE == allowCombinedID) && IS_COMBINED_EVENT_ID(eventId) ) { if( IS_VALID_COMBINED_ID(TO_COMBINED_EVENT_CFG_IDX(eventId)) ) { /* ID is valid, but is it valid for the destination */ const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; if( (origin == CombDTCCfg->MemoryDestination) && (TRUE == DTCIsAvailable(CombDTCCfg->DTCClassRef)) ) { isValid = TRUE; } } } else { if( !IS_COMBINED_EVENT_ID(eventId) ) { lookupEventIdParameter(eventId, &EventIdParam); if (NULL != EventIdParam) { // Event was found lookupEventStatusRec(eventId, &eventStatusRec); // Event should be stored in destination memory? isValid = (checkDtcOrigin(origin, EventIdParam, FALSE) && (NULL != eventStatusRec) && eventStatusRec->isAvailable)? TRUE: FALSE; } else { // The event did not exist } } } #else (void)allowCombinedID; lookupEventIdParameter(eventId, &EventIdParam); if (NULL != EventIdParam) { // Event was found lookupEventStatusRec(eventId, &eventStatusRec); // Event should be stored in destination memory? isValid = ((TRUE == checkDtcOrigin(origin, EventIdParam, FALSE)) && (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable))? TRUE: FALSE; } else { // The event did not exist } #endif return isValid; } #endif /** * Checks if an operation cycle is started * @param opCycle * @return */ boolean operationCycleIsStarted(Dem_OperationCycleIdType opCycle) { boolean isStarted = FALSE; if (opCycle < DEM_OPERATION_CYCLE_ID_ENDMARK) { if (operationCycleStateList[opCycle] == DEM_CYCLE_STATE_START) { isStarted = TRUE; } } return isStarted; } #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) static boolean failureCycleIsStarted(const Dem_EventParameterType *eventParam) { return operationCycleIsStarted((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef)); } static boolean faultConfirmationCriteriaFulfilled(const Dem_EventParameterType *eventParam, const EventStatusRecType *eventStatusRecPtr) { if(((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef) != DEM_OPERATION_CYCLE_ID_ENDMARK) && (eventStatusRecPtr->failureCounter >= eventParam->EventClass->FailureCycleCounterThresholdRef->Threshold) ) { return TRUE; } else { return FALSE; } } static void handleFaultConfirmation(const Dem_EventParameterType *eventParam, EventStatusRecType *eventStatusRecPtr) { if( (TRUE == failureCycleIsStarted(eventParam)) && (FALSE == eventStatusRecPtr->failedDuringFailureCycle) ) { if( eventStatusRecPtr->failureCounter < DEM_FAILURE_CNTR_MAX ) { eventStatusRecPtr->failureCounter++; eventStatusRecPtr->errorStatusChanged = TRUE; } /* @req DEM530 */ if( TRUE == faultConfirmationCriteriaFulfilled(eventParam, eventStatusRecPtr )) { eventStatusRecPtr->eventStatusExtended |= DEM_CONFIRMED_DTC; eventStatusRecPtr->errorStatusChanged = TRUE; } eventStatusRecPtr->failedDuringFailureCycle = TRUE; } } #endif #if defined(DEM_USE_INDICATORS) /** * Resets healing and failure counter for event indicators * @param eventParam * @return TRUE: counter value changed, FALSE: no change */ static boolean resetIndicatorCounters(const Dem_EventParameterType *eventParam) { boolean countersChanged = FALSE; if( (NULL != eventParam->EventClass->IndicatorAttribute ) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ){ const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL) { if( (0 != indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter) || (0 != indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter)) { countersChanged = TRUE; } indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter = 0; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter = 0; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus = 0; indAttrPtr++; } } #if defined(DEM_USE_MEMORY_FUNCTIONS) if(TRUE == countersChanged) { storeEventIndicators(eventParam); } #endif return countersChanged; } /** * Checks if indicator failure cycle is started * @param eventParam * @param indAttr * @return TRUE: Failure cycle is started, FALSE: failure cycle not started */ static boolean indicatorFailureCycleIsStarted(const Dem_EventParameterType *eventParam, const Dem_IndicatorAttributeType *indAttr) { if(DEM_FAILURE_CYCLE_INDICATOR == indAttr->IndicatorFailureCycleSource) { return operationCycleIsStarted((Dem_OperationCycleStateType)*(indAttr->IndicatorFailureCycle)); } else { return operationCycleIsStarted((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef)); } } /** * Checks if failure criteria for indicator is fulfilled * @param eventParam * @param indicatorAttribute * @return TRUE: criteria fulfilled, FALSE: criteria not fulfilled */ static boolean indicatorFailFulfilled(const Dem_EventParameterType *eventParam, const Dem_IndicatorAttributeType *indicatorAttribute) { boolean fulfilled = FALSE; uint8 thresHold; Dem_OperationCycleIdType opCyc; if( DEM_FAILURE_CYCLE_INDICATOR == indicatorAttribute->IndicatorFailureCycleSource ) { thresHold = indicatorAttribute->IndicatorFailureCycleThreshold; opCyc = ((Dem_OperationCycleStateType)*(indicatorAttribute->IndicatorFailureCycle)); } else { thresHold = eventParam->EventClass->FailureCycleCounterThresholdRef->Threshold; opCyc = (Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef); } /* @req DEM501 */ if( (opCyc < DEM_OPERATION_CYCLE_ID_ENDMARK) && (indicatorStatusBuffer[indicatorAttribute->IndicatorBufferIndex].FailureCounter >= thresHold) ) { fulfilled = TRUE; } return fulfilled; } /** * Checks if warningIndicatorOnCriteria is fulfilled for an event * @param eventParam * @return TRUE: criteria fulfilled, FALSE: criteria not fulfilled */ static boolean warningIndicatorOnCriteriaFulfilled(const Dem_EventParameterType *eventParam) { boolean fulfilled = FALSE; if( (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ) { const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; /* @req DEM566 */ while( (FALSE == indAttrPtr->Arc_EOL) && (FALSE == fulfilled) ) { fulfilled = indicatorFailFulfilled(eventParam, indAttrPtr); indAttrPtr++; } } return fulfilled; } /** * Checks if indicator healing cycle is started * @param indAttr * @return TRUE: Healing cycle is started, FALSE: Healing cycle not started */ static boolean indicatorHealingCycleIsStarted(const Dem_IndicatorAttributeType *indAttr) { return operationCycleIsStarted(indAttr->IndicatorHealingCycle); } /** * Prepares indicator status for a new failure/healing cycle * @param operationCycleId */ static void indicatorOpCycleStart(Dem_OperationCycleIdType operationCycleId) { Dem_OperationCycleIdType failCyc; const Dem_EventParameterType *eventIdParamList = configSet->EventParameter; uint16 indx = 0; while( FALSE == eventIdParamList[indx].Arc_EOL ) { if( NULL != eventIdParamList[indx].EventClass->IndicatorAttribute ) { const Dem_IndicatorAttributeType *indAttrPtr = eventIdParamList[indx].EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL) { if( operationCycleId == indAttrPtr->IndicatorHealingCycle ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus &= (uint8)~(INDICATOR_FAILED_DURING_HEALING_CYCLE | INDICATOR_PASSED_DURING_HEALING_CYCLE); } if( DEM_FAILURE_CYCLE_INDICATOR == indAttrPtr->IndicatorFailureCycleSource ) { failCyc = ((Dem_OperationCycleStateType)*indAttrPtr->IndicatorFailureCycle); } else { failCyc = (Dem_OperationCycleIdType)*(eventIdParamList[indx].EventClass->FailureCycleRef); } if( operationCycleId == failCyc ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus &= (uint8)~(INDICATOR_FAILED_DURING_FAILURE_CYCLE | INDICATOR_PASSED_DURING_FAILURE_CYCLE); } indAttrPtr++; } } indx++; } } /** * Checks if warningIndicatorOffCriteria is fulfilled for an event * @param eventParam * @return TRUE: criteria fulfilled, FALSE: criteria not fulfilled */ static boolean warningIndicatorOffCriteriaFulfilled(const Dem_EventParameterType *eventParam) { return (FALSE == warningIndicatorOnCriteriaFulfilled(eventParam))? TRUE :FALSE; } /** * Handles end of operation cycles for indicators * @param operationCycleId * @param eventStatusRecPtr * @return TRUE: Counter updated for at least one event */ static boolean indicatorOpCycleEnd(Dem_OperationCycleIdType operationCycleId, EventStatusRecType *eventStatusRecPtr) { /* @req DEM502 */ /* @req DEM505 */ Dem_OperationCycleIdType failCyc; boolean counterChanged = FALSE; uint8 healingCounterOld = 0u; uint8 failureCounterOld = 0u; const Dem_EventParameterType *eventParam = eventStatusRecPtr->eventParamRef; if( (NULL != eventParam) && (NULL != eventParam->EventClass->IndicatorAttribute)&& (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ) { const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL) { healingCounterOld = indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter; failureCounterOld = indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter; if( (operationCycleId == indAttrPtr->IndicatorHealingCycle) && (0 == (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_HEALING_CYCLE)) && (0 != (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_PASSED_DURING_HEALING_CYCLE)) && (TRUE == indicatorFailFulfilled(eventParam, indAttrPtr))) { /* Passed and didn't fail during the healing cycle */ if( indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter < DEM_INDICATOR_CNTR_MAX ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter++; } if( indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter >= indAttrPtr->IndicatorHealingCycleThreshold ) { /* @req DEM503 */ /* Healing condition fulfilled. * Should we reset failure counter here? */ indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter = 0; } } if( DEM_FAILURE_CYCLE_INDICATOR == indAttrPtr->IndicatorFailureCycleSource ) { failCyc = ((Dem_OperationCycleStateType)*indAttrPtr->IndicatorFailureCycle); } else { failCyc = (Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef); } if( (operationCycleId == failCyc) && (0 == (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_FAILURE_CYCLE)) && (0 != (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_PASSED_DURING_FAILURE_CYCLE)) && (FALSE == indicatorFailFulfilled(eventParam, indAttrPtr))) { /* Passed and didn't fail during the failure cycle. * Reset failure counter */ indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter = 0; } if( (healingCounterOld != indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter) || (failureCounterOld != indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter) ) { counterChanged = TRUE; } indAttrPtr++; } /* @req DEM533 */ if( TRUE == warningIndicatorOffCriteriaFulfilled(eventParam)) { eventStatusRecPtr->eventStatusExtended &= ~DEM_WARNING_INDICATOR_REQUESTED; } #if defined(DEM_USE_MEMORY_FUNCTIONS) if(TRUE == counterChanged) { storeEventIndicators(eventParam); } #endif } return counterChanged; } /** * Performs clearing of indicator healing counter if conditions fulfilled. * NOTE: This functions should only be called when event is FAILED. * @param eventParam * @param indAttrPtr */ static inline void handleHealingCounterOnFailed(const Dem_EventParameterType *eventParam, const Dem_IndicatorAttributeType *indAttrPtr) { #if defined(DEM_HEALING_COUNTER_CLEAR_ON_FAIL_DURING_FAILURE_CYCLE) if( TRUE == indicatorFailureCycleIsStarted(eventParam, indAttrPtr) ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter = 0; } #elif defined(DEM_HEALING_COUNTER_CLEAR_ON_FAIL_DURING_FAILURE_OR_HEALING_CYCLE) if( (TRUE == indicatorFailureCycleIsStarted(eventParam, indAttrPtr)) || (TRUE == indicatorHealingCycleIsStarted(indAttrPtr)) ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter = 0; } #elif defined(DEM_HEALING_COUNTER_CLEAR_ON_ALL_FAIL) (void)eventParam;/*lint !e920*/ indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter = 0; #else #error "Dem: Unknown healing counter clear behavior" #endif } /** * Handles updating of indicator failure counter and status bits * @param eventParam * @param eventStatusRecPtr * @param eventStatus * @return TRUE: counter was updated, FALSE: counter was not updated */ static boolean handleIndicators(const Dem_EventParameterType *eventParam, EventStatusRecType *eventStatusRecPtr, Dem_EventStatusType eventStatus) { /* @req DEM506 */ /* @req DEM510 */ boolean cntrChanged = FALSE; if( (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ){ const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL) { switch(eventStatus) { case DEM_EVENT_STATUS_FAILED: if( TRUE == indicatorFailureCycleIsStarted(eventParam, indAttrPtr) ) { if( (0 == (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_FAILURE_CYCLE)) && (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter < DEM_INDICATOR_CNTR_MAX) ) { /* First fail during this failure cycle and incrementing failure counter would not overflow */ indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter++; cntrChanged = TRUE; } indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus |= INDICATOR_FAILED_DURING_FAILURE_CYCLE; } if( TRUE == indicatorHealingCycleIsStarted(indAttrPtr) ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus |= INDICATOR_FAILED_DURING_HEALING_CYCLE; } break; case DEM_EVENT_STATUS_PASSED: if( TRUE == indicatorFailureCycleIsStarted(eventParam, indAttrPtr) ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus |= INDICATOR_PASSED_DURING_FAILURE_CYCLE; } if( TRUE == indicatorHealingCycleIsStarted(indAttrPtr) ) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus |= INDICATOR_PASSED_DURING_HEALING_CYCLE; } break; default: break; } if( DEM_EVENT_STATUS_FAILED == eventStatus ) { handleHealingCounterOnFailed(eventParam, indAttrPtr); } indAttrPtr++; } /* @req DEM566 */ if( TRUE == warningIndicatorOnCriteriaFulfilled(eventParam)) { eventStatusRecPtr->eventStatusExtended |= DEM_WARNING_INDICATOR_REQUESTED; } } return cntrChanged; } #if defined(DEM_USE_MEMORY_FUNCTIONS) /** * Stores indicators for an event in memory destined for NvRam * @param eventParam */ static void storeEventIndicators(const Dem_EventParameterType *eventParam) { const Dem_IndicatorAttributeType *indAttr; if( (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ){ indAttr = eventParam->EventClass->IndicatorAttribute; while( FALSE == indAttr->Arc_EOL) { indicatorBuffer[indAttr->IndicatorBufferIndex].EventID = indicatorStatusBuffer[indAttr->IndicatorBufferIndex].EventID; indicatorBuffer[indAttr->IndicatorBufferIndex].FailureCounter = indicatorStatusBuffer[indAttr->IndicatorBufferIndex].FailureCounter; indicatorBuffer[indAttr->IndicatorBufferIndex].HealingCounter = indicatorStatusBuffer[indAttr->IndicatorBufferIndex].HealingCounter; indicatorBuffer[indAttr->IndicatorBufferIndex].IndicatorId = indAttr->IndicatorId; indAttr++; } } } /** * Merges indicator status read from NvRam with status held in ram */ static void mergeIndicatorBuffers(void) { const Dem_EventParameterType *eventParam; const Dem_IndicatorAttributeType *indAttr; for(uint32 i = 0; i < DEM_NOF_EVENT_INDICATORS; i++) { if(IS_VALID_EVENT_ID(indicatorBuffer[i].EventID) && IS_VALID_INDICATOR_ID(indicatorBuffer[i].IndicatorId)) { /* Valid event and indicator. Check that it is a valid indicator for this event */ eventParam = NULL; lookupEventIdParameter(indicatorBuffer[i].EventID, &eventParam); if((NULL != eventParam) && (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ){ indAttr = eventParam->EventClass->IndicatorAttribute; while(FALSE == indAttr->Arc_EOL) { if( indAttr->IndicatorId == indicatorBuffer[i].IndicatorId ) { /* Update healing counter. */ if( (0 != (indicatorStatusBuffer[indAttr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_FAILURE_CYCLE)) || (0 != (indicatorStatusBuffer[indAttr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_HEALING_CYCLE))) { /* Failed at some point during PreInit. */ indicatorStatusBuffer[indAttr->IndicatorBufferIndex].HealingCounter = 0; } else { indicatorStatusBuffer[indAttr->IndicatorBufferIndex].HealingCounter = indicatorBuffer[i].HealingCounter; } /* Update failure counter */ if( (DEM_INDICATOR_CNTR_MAX - indicatorBuffer[i].FailureCounter) > indicatorStatusBuffer[indAttr->IndicatorBufferIndex].FailureCounter) { indicatorStatusBuffer[indAttr->IndicatorBufferIndex].FailureCounter += indicatorBuffer[i].FailureCounter; } else { indicatorStatusBuffer[indAttr->IndicatorBufferIndex].FailureCounter = DEM_INDICATOR_CNTR_MAX; } } indAttr++; } } } } #ifdef DEM_USE_MEMORY_FUNCTIONS /* Transfer content of indicatorStatusBuffer to indicatorBuffer */ eventParam = configSet->EventParameter; while( FALSE == eventParam->Arc_EOL ) { storeEventIndicators(eventParam); eventParam++; } /* IMPROVEMENT: Only call this if the content of memory was changed */ /* IMPROVEMENT: Add handling of immediate storage */ Dem_NvM_SetIndicatorBlockChanged(FALSE); #endif } #endif #endif #if (DEM_USE_TIMESTAMPS == STD_ON) && defined (DEM_USE_MEMORY_FUNCTIONS) static void setEventTimeStamp(EventStatusRecType *eventStatusRecPtr) { if( DEM_INITIALIZED == demState ) { if( Event_TimeStamp >= DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT ) { rearrangeEventTimeStamp(&Event_TimeStamp); } eventStatusRecPtr->timeStamp = Event_TimeStamp; Event_TimeStamp++; } else { eventStatusRecPtr->timeStamp = Event_TimeStamp; if( Event_TimeStamp < DEM_MAX_TIMESTAMP_FOR_PRE_INIT ) { Event_TimeStamp++; } } } #endif #if (defined(DEM_USE_INDICATORS) && (DEM_OBD_DISPLACEMENT_SUPPORT == STD_ON)) || (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /** * Checks if event currently activates MIL * @param eventParam * @return */ static boolean eventActivatesMIL(const Dem_EventParameterType *eventParam) { boolean fulfilled = FALSE; if( (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ) { #if defined(DEM_USE_INDICATORS) const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; /* @req DEM566 */ while( (FALSE == indAttrPtr->Arc_EOL) && (FALSE == fulfilled) ) { if( DEM_MIL_INIDICATOR_ID == indAttrPtr->IndicatorId ) { fulfilled |= indicatorFailFulfilled(eventParam, indAttrPtr); } indAttrPtr++; } #endif } return fulfilled; } #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /* !req DEM300 Do we handle according to regulations? */ /** * Stores a permanent DTC * @param DTCRef * @return TRUE: buffer was updated, FALSE: buffer NOT updated */ static boolean storeDTCPermanentMemory(const Arc_Dem_DTC *DTCRef) { boolean alreadyStored = FALSE; boolean freeEntryFound = FALSE; boolean stored = FALSE; uint32 storeIndex = 0; /* Check if it is already stored and if there is a free entry */ for( uint32 i = 0; (i < DEM_MAX_NUMBER_EVENT_PERM_MEM) && (FALSE == alreadyStored); i++) { if( FREE_PERMANENT_DTC_ENTRY == permMemEventBuffer[i].OBDDTC ) { /* Found a free entry */ freeEntryFound = TRUE; storeIndex = i; } if( DTCRef->OBDDTC == permMemEventBuffer[i].OBDDTC) { /* DTC already stored */ alreadyStored = TRUE; } } if( (FALSE == alreadyStored) && (TRUE == freeEntryFound) ) { permMemEventBuffer[storeIndex].OBDDTC = DTCRef->OBDDTC; stored = TRUE; } return stored; } /** * Deletes a permanent DTC * @param DTCRef * @return TRUE: buffer was updated, FALSE: buffer NOT updated */ static boolean deleteDTCPermanentMemory(const Arc_Dem_DTC *DTCRef) { boolean deleted = FALSE; /* Check if it is already stored and if there is a free entry */ for( uint32 i = 0; (i < DEM_MAX_NUMBER_EVENT_PERM_MEM) && (FALSE == deleted); i++) { if( DTCRef->OBDDTC == permMemEventBuffer[i].OBDDTC) { /* DTC already stored */ permMemEventBuffer[i].OBDDTC = FREE_PERMANENT_DTC_ENTRY; deleted = TRUE; } } return deleted; } /** * Check if a DTC is a valid OBD DTC * @param dtc * @return */ static boolean isValidPermanentOBDDTC(uint32 dtc) { boolean validDTC = FALSE; const Dem_EventParameterType *eventParam = configSet->EventParameter; while( (FALSE == eventParam->Arc_EOL) && (FALSE == validDTC)) { if( (DEM_EMISSION_RELATED_MIL_ACTIVATING == (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind) && (NULL != eventParam->DTCClassRef)){ if( dtc == eventParam->DTCClassRef->DTCRef->OBDDTC ) { validDTC = TRUE; } } eventParam++; } return validDTC; } /** * Checks if condition for storing a permanent DTC is fulfilled * @param eventParam * @param evtStatus * @return TRUE: condition fulfilled, FALSE: condition NOT fulfilled */ static boolean permanentDTCStorageConditionFulfilled(const Dem_EventParameterType *eventParam, Dem_EventStatusExtendedType evtStatus) { boolean fulfilled = FALSE; if( TRUE == eventIsEmissionRelatedMILActivating(eventParam) ) { /* This event has an emission related DTC. * Check if it is confirmed and activates MIL */ if( (0u != (evtStatus & DEM_CONFIRMED_DTC)) && (TRUE == eventActivatesMIL(eventParam)) ) { /* Condition for storing as permanent is fulfilled*/ fulfilled = TRUE; } } return fulfilled; } /** * Handles storage of permanent DTCs * @param eventParam * @param evtStatus * @return TRUE: permanent memory updated, FALSE: permanent memory NOT updated */ static boolean handlePermanentDTCStorage(const Dem_EventParameterType *eventParam, Dem_EventStatusExtendedType evtStatus) { boolean memoryUpdated = FALSE; if( TRUE == permanentDTCStorageConditionFulfilled(eventParam, evtStatus) ) { /* Try store as permanent DTC */ memoryUpdated = storeDTCPermanentMemory(eventParam->DTCClassRef->DTCRef); } return memoryUpdated; } /** * Handles erasing permanent DTCs. * NOTE: May only be called on operation cycle end! * @param eventParam * @param evtStatus */ static boolean handlePermanentDTCErase(const EventStatusRecType *eventRec, Dem_OperationCycleIdType operationCycleId) { boolean MILHealOK = TRUE; const Dem_EventParameterType *eventParam = eventRec->eventParamRef; /* Check if emission related */ boolean permanentMemoryUpdated = FALSE; if( TRUE == eventIsEmissionRelatedMILActivating(eventParam) ) { /* This event has an emission related DTC. * Check if it currently activates MIL */ if( FALSE == eventActivatesMIL(eventParam)) { #if defined(DEM_USE_INDICATORS) if( (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ) { const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; /* @req DEM566 */ while( (FALSE == indAttrPtr->Arc_EOL) && (FALSE != MILHealOK)) { if( DEM_MIL_INIDICATOR_ID == indAttrPtr->IndicatorId ) { if( (operationCycleId != indAttrPtr->IndicatorHealingCycle) || (0u != (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_FAILED_DURING_HEALING_CYCLE)) || (0u == (indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus & INDICATOR_PASSED_DURING_HEALING_CYCLE))) { /* Failed or did not pass. */ MILHealOK = FALSE; } } indAttrPtr++; } } #endif if(TRUE == MILHealOK) { /* Delete permanent DTC */ permanentMemoryUpdated = deleteDTCPermanentMemory(eventParam->DTCClassRef->DTCRef); } } } return permanentMemoryUpdated; } /** * */ static void ValidateAndUpdatePermanentBuffer(void) { boolean newDataStored = FALSE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; #endif /* Validate entries in the buffer */ for( uint32 i = 0; i < DEM_MAX_NUMBER_EVENT_PERM_MEM; i++) { if( FALSE == isValidPermanentOBDDTC(permMemEventBuffer[i].OBDDTC)) { /* DTC is not a valid permanent DTC */ permMemEventBuffer[i].OBDDTC = FREE_PERMANENT_DTC_ENTRY; } } /* Insert emission relates DTCs which are currently confirmed and activating MIL */ for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if( DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId ) { if(TRUE == handlePermanentDTCStorage(eventStatusBuffer[i].eventParamRef, eventStatusBuffer[i].eventStatusExtended) ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventStatusBuffer[i].eventParamRef->DTCClassRef) && (TRUE == eventStatusBuffer[i].eventParamRef->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusBuffer[i].occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } #endif newDataStored = TRUE; } } } /* Set block changed if new data was stored */ if( TRUE == newDataStored ) { /* !req DEM590 */ #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) Dem_NvM_SetPermanentBlockChanged(immediateStorage); #else Dem_NvM_SetPermanentBlockChanged(FALSE); #endif } } #endif /* DEM_USE_PERMANENT_MEMORY_SUPPORT */ #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) static void ValidateAndUpdatePreStoredFreezeFramesBuffer(void) { const Dem_EventParameterType *eventParam; boolean ffDeleted = FALSE; /* Validate entries in the buffer */ for( uint32 i = 0; i < DEM_MAX_NUMBER_PRESTORED_FF; i++) { if (0u != memPreStoreFreezeFrameBuffer[i].eventId) { lookupEventIdParameter(memPreStoreFreezeFrameBuffer[i].eventId, &eventParam); if (NULL != eventParam ) { if (FALSE == eventParam->EventClass->FFPrestorageSupported) { memset(&memPreStoreFreezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); ffDeleted = TRUE; } } else { /* Invalid ID. Deletet it. */ memset(&memPreStoreFreezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); ffDeleted = TRUE; } } } /* Set block changed if new data was stored */ if( TRUE == ffDeleted ) { Dem_NvM_SetPreStoreFreezeFrameBlockChanged(FALSE); } } #endif static void notifyEventStatusChange(const Dem_EventParameterType *eventParam, Dem_EventStatusExtendedType oldStatus, Dem_EventStatusExtendedType newStatus) { uint8 j = 0; if( NULL != eventParam ) { if( NULL != eventParam->CallbackEventStatusChanged ) { /* @req Dem016 */ /* @req Dem615 */ while( FALSE == eventParam->CallbackEventStatusChanged[j].Arc_EOL ) { if( TRUE == eventParam->CallbackEventStatusChanged[j].UsePort ) { (void)eventParam->CallbackEventStatusChanged[j].CallbackEventStatusChangedFnc.eventStatusChangedWithoutId(oldStatus, newStatus); } else { (void)eventParam->CallbackEventStatusChanged[j].CallbackEventStatusChangedFnc.eventStatusChangedWithId(eventParam->EventID, oldStatus, newStatus); } j++; } } #if defined(USE_RTE) && (DEM_GENERAL_EVENT_STATUS_CB == STD_ON) /* @req Dem616 */ (void)Rte_Call_GeneralCBStatusEvt_EventStatusChanged(eventParam->EventID, oldStatus, newStatus); #endif #if (DEM_TRIGGER_DLT_REPORTS == STD_ON) /* @req Dem517 */ Dlt_DemTriggerOnEventStatus(eventParam->EventID, oldStatus, newStatus); #endif #if defined(USE_FIM) && (DEM_TRIGGER_FIM_REPORTS == STD_ON) /* @req Dem029 */ if( TRUE == DemFiMInit ) { FiM_DemTriggerOnMonitorStatus(eventParam->EventID); } #endif } } static void notifyEventDataChanged(const Dem_EventParameterType *eventParam) { /* @req DEM474 */ if( (NULL != eventParam) && (NULL != eventParam->CallbackEventDataChanged)) { /* @req Dem618 */ if( TRUE == eventParam->CallbackEventDataChanged->UsePort ) { (void)eventParam->CallbackEventDataChanged->CallbackEventDataChangedFnc.eventDataChangedWithoutId(); } else { (void)eventParam->CallbackEventDataChanged->CallbackEventDataChangedFnc.eventDataChangedWithId(eventParam->EventID); } } #if defined(USE_RTE) && (DEM_GENERAL_EVENT_DATA_CB == STD_ON) /* @req Dem619 */ if( NULL != eventParam ) { (void)Rte_Call_GeneralCBDataEvt_EventDataChanged(eventParam->EventID); } #endif } static void setDefaultEventStatus(EventStatusRecType *eventStatusRecPtr) { eventStatusRecPtr->eventId = DEM_EVENT_ID_NULL; eventStatusRecPtr->eventParamRef = NULL; eventStatusRecPtr->fdcInternal = 0; eventStatusRecPtr->UDSFdc = 0; eventStatusRecPtr->maxUDSFdc = 0; eventStatusRecPtr->occurrence = 0; eventStatusRecPtr->eventStatusExtended = DEM_DEFAULT_EVENT_STATUS; eventStatusRecPtr->errorStatusChanged = FALSE; eventStatusRecPtr->extensionDataChanged = FALSE; eventStatusRecPtr->extensionDataStoreBitfield = 0; #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->failureCounter = 0; eventStatusRecPtr->failedDuringFailureCycle = FALSE; eventStatusRecPtr->passedDuringFailureCycle = FALSE; #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->agingCounter = 0; eventStatusRecPtr->passedDuringAgingCycle = FALSE; eventStatusRecPtr->failedDuringAgingCycle = FALSE; #endif eventStatusRecPtr->timeStamp = 0; } #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_CLEAR_COMBINED_AGING_COUNTERS_ON_FAIL) #if defined(DEM_USE_MEMORY_FUNCTIONS) /** * Reset an existing aging counter in event memory. * @param eventId * @param buffer * @param bufferSize * @param origin */ static void resetAgingCounter(Dem_EventIdType eventId, EventRecType* buffer, uint32 bufferSize, Dem_DTCOriginType origin) { boolean positionFound = FALSE; for (uint32 i = 0uL; (i < bufferSize) && (FALSE == positionFound); i++){ if( buffer[i].EventData.eventId == eventId ) { buffer[i].EventData.agingCounter = 0u; Dem_NvM_SetEventBlockChanged(origin, FALSE); } } } #endif /** * Resets aging counter in memory destination * @param eventId * @param DTCOrigin */ static void resetAgingCounterEvtMem(Dem_EventIdType eventId, Dem_DTCOriginType DTCOrigin) { switch (DTCOrigin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) resetAgingCounter(eventId, priMemEventBuffer, DEM_MAX_NUMBER_EVENT_ENTRY_PRI, DEM_DTC_ORIGIN_PRIMARY_MEMORY); #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) resetAgingCounter(eventId, secMemEventBuffer, DEM_MAX_NUMBER_EVENT_ENTRY_SEC, DEM_DTC_ORIGIN_SECONDARY_MEMORY); #endif break; default: /* Origin not supported */ break; } } /** * Clears aging counter for all other sub-events of a combined event * @param eventParam */ static void clearCombinedEventAgingCounters(const Dem_EventParameterType *eventParam) { EventStatusRecType *eventStatusRecPtr; const Dem_CombinedDTCCfgType *CombDTCCfg; const Dem_DTCClassType *DTCClass; if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; DTCClass = CombDTCCfg->DTCClassRef; for(uint16 i = 0; i < DTCClass->NofEvents; i++) { if( eventParam->EventID != DTCClass->Events[i] ) { eventStatusRecPtr = NULL_PTR; lookupEventStatusRec(DTCClass->Events[i], &eventStatusRecPtr); if( NULL_PTR != eventStatusRecPtr ) { if( (0u != (eventStatusRecPtr->eventStatusExtended & DEM_CONFIRMED_DTC)) && (0u != eventStatusRecPtr->agingCounter) ) { eventStatusRecPtr->agingCounter = 0u; resetAgingCounterEvtMem(DTCClass->Events[i], CombDTCCfg->MemoryDestination); } } } } } } #endif /** * Handles clearing of aging counter. Should only be called when operation cycle * is start and event is qualified as FAILED * @param eventParam * @param eventStatusRecPtr */ static inline void handleAgingCounterOnFailed(const Dem_EventParameterType *eventParam, EventStatusRecType *eventStatusRecPtr) { #if defined(DEM_AGING_COUNTER_CLEAR_ON_FAIL_DURING_FAILURE_CYCLE) if( TRUE == operationCycleIsStarted((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef)) ) { eventStatusRecPtr->agingCounter = 0; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_CLEAR_COMBINED_AGING_COUNTERS_ON_FAIL) clearCombinedEventAgingCounters(eventParam); #endif } #elif defined(DEM_AGING_COUNTER_CLEAR_ON_FAIL_DURING_FAILURE_OR_AGING_CYCLE) if( (TRUE == operationCycleIsStarted((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef))) || (TRUE == operationCycleIsStarted(eventParam->EventClass->AgingCycleRef)) ) { eventStatusRecPtr->agingCounter = 0; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_CLEAR_COMBINED_AGING_COUNTERS_ON_FAIL) clearCombinedEventAgingCounters(eventParam); #endif } #elif defined(DEM_AGING_COUNTER_CLEAR_ON_ALL_FAIL) (void)eventParam;/*lint !e920*/ eventStatusRecPtr->agingCounter = 0; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_CLEAR_COMBINED_AGING_COUNTERS_ON_FAIL) clearCombinedEventAgingCounters(eventParam); #endif #else #error "Dem: Unknown aging counter clear behavior" #endif } #endif #if defined(DEM_USE_IUMPR) /** * Increments IUMPR numerator of a specific component according to legislation * @param RatioID */ static Std_ReturnType incrementIumprNumerator(Dem_RatioIdType ratioId) { Std_ReturnType ret = E_NOT_OK; if (ratioId < DEM_IUMPR_REGISTERED_COUNT) { // is valid ID if (FALSE == iumprBufferLocal[ratioId].numerator.incrementedThisDrivingCycle) { // not incremented this driving cycle if (TRUE == operationCycleIsStarted(DEM_OBD_DCY)) { /* IMPROVEMENT */ uint16 boundEventId = Dem_RatiosList[ratioId].DiagnosticEventRef->EventID; EventStatusRecType* boundEvent; lookupEventStatusRec(boundEventId, &boundEvent); Dem_EventStatusExtendedType boundEventStatus = GET_STORED_STATUS_BITS(boundEvent->eventStatusExtended); /* @req DEM299 */ if (0u == (boundEventStatus & DEM_PENDING_DTC)) { // not pending event // (C) If either the numerator or denominator for a specific component reaches // the maximum value of 65,535 ±2, both numbers shall be divided by two // before either is incremented again to avoid overflow problems. if (iumprBufferLocal[ratioId].numerator.value == 65535) { iumprBufferLocal[ratioId].numerator.value = 32767; iumprBufferLocal[ratioId].denominator.value = iumprBufferLocal[ratioId].denominator.value / 2; } iumprBufferLocal[ratioId].numerator.value++; iumprBufferLocal[ratioId].numerator.incrementedThisDrivingCycle = TRUE; ret = E_OK; } } } } return ret; } /** * Increments IUMPR denominator of a specific component according to legislation * @param RatioID */ static Std_ReturnType incrementIumprDenominator(Dem_RatioIdType ratioId) { Std_ReturnType ret = E_NOT_OK; if (ratioId < DEM_IUMPR_REGISTERED_COUNT) { // is valid ID if (FALSE == iumprBufferLocal[ratioId].denominator.isLocked) { // if denominator is NOT locked if (FALSE == iumprBufferLocal[ratioId].denominator.incrementedThisDrivingCycle) { // not incremented this driving cycle if (TRUE == operationCycleIsStarted(DEM_OBD_DCY)) { /* IMPROVEMENT */ uint16 boundEventId = Dem_RatiosList[ratioId].DiagnosticEventRef->EventID; EventStatusRecType* boundEvent; lookupEventStatusRec(boundEventId, &boundEvent); Dem_EventStatusExtendedType boundEventStatus = GET_STORED_STATUS_BITS(boundEvent->eventStatusExtended); /* @req DEM299 */ if (0u == (boundEventStatus & DEM_PENDING_DTC)) { // not pending event // (C) If either the numerator or denominator for a specific component reaches // the maximum value of 65,535 ±2, both numbers shall be divided by two // before either is incremented again to avoid overflow problems. if (iumprBufferLocal[ratioId].denominator.value == 65535) { iumprBufferLocal[ratioId].denominator.value = 32767; iumprBufferLocal[ratioId].numerator.value = iumprBufferLocal[ratioId].numerator.value / 2; } iumprBufferLocal[ratioId].denominator.value++; iumprBufferLocal[ratioId].denominator.incrementedThisDrivingCycle = TRUE; ret = E_OK; } } } } } return ret; } /** * Resets the incrementedThisDrivingCycle flag to FALSE of all numerators and denominators in IUMPR buffer, * as well as general denominator, if current operating cycle is the bound driving cycle. * * @param operationCycleId */ static void resetIumprFlags(Dem_OperationCycleIdType operationCycleId) { if (operationCycleId == DEM_OBD_DCY) { for (Dem_RatioIdType i = 0; i < DEM_IUMPR_REGISTERED_COUNT; i++) { iumprBufferLocal[i].numerator.incrementedThisDrivingCycle = FALSE; iumprBufferLocal[i].denominator.incrementedThisDrivingCycle = FALSE; } // reset general denominator flags and status generalDenominatorBuffer.incrementedThisDrivingCycle = FALSE; (void) Dem_SetIUMPRDenCondition(DEM_IUMPR_GENERAL_OBDCOND, DEM_IUMPR_DEN_STATUS_NOT_REACHED); } } /** * Increments all unlocked denominators in IUMPR buffer, * if current operating cycle is the bound driving cycle. * @param operationCycleId */ static void incrementUnlockedIumprDenominators(Dem_OperationCycleIdType operationCycleId) { if (operationCycleId == DEM_OBD_DCY) { for (Dem_RatioIdType i = 0; i < DEM_IUMPR_REGISTERED_COUNT; i++) { (void) incrementIumprDenominator(i); } } } /** * Increments observer numerator in IUMPR buffer, * if its bound event is set to pass or failed, must be qualified. */ static void incrementObserverIumprNumerator(Dem_EventIdType eventId, Dem_EventStatusType eventStatus) { /* @req DEM359 */ // find the ratio that has the given event bound to it if (eventStatus == DEM_EVENT_STATUS_FAILED || eventStatus == DEM_EVENT_STATUS_PASSED) { for (uint16 ratioId = 0; ratioId < DEM_IUMPR_REGISTERED_COUNT; ratioId++) { if (Dem_RatiosList[ratioId].RatioKind == DEM_RATIO_OBSERVER && eventId == Dem_RatiosList[ratioId].DiagnosticEventRef->EventID) { (void) incrementIumprNumerator(ratioId); } } } } /** * Initialise IUMPR additional denominator conditions buffer */ static void initIumprAddiDenomCondBuffer() { iumprAddiDenomCondBuffer[0].condition = DEM_IUMPR_DEN_COND_COLDSTART; iumprAddiDenomCondBuffer[1].condition = DEM_IUMPR_DEN_COND_EVAP; iumprAddiDenomCondBuffer[2].condition = DEM_IUMPR_DEN_COND_500MI; iumprAddiDenomCondBuffer[3].condition = DEM_IUMPR_GENERAL_OBDCOND; for (uint8 i = 0; i < DEM_IUMPR_ADDITIONAL_DENOMINATORS_COUNT; i++) { iumprAddiDenomCondBuffer[i].status = DEM_IUMPR_DEN_STATUS_NOT_REACHED; } } /** * Increment ignition cycle counter at the start of ignition cycle */ static void incrementIgnitionCycleCounter(Dem_OperationCycleIdType operationCycleId) { // If the ignition cycle counter reaches the maximum value of 65,535 ±2, the // ignition cycle counter shall rollover and increment to zero on the next // ignition cycle to avoid overflow problems. if (operationCycleId == DEM_IGNITION) { if (ignitionCycleCountBuffer == 65535) { ignitionCycleCountBuffer = 0; } else { ignitionCycleCountBuffer++; } } } #endif /** * Performs event updates when event is qualified as FAILED * @param eventParam * @param eventStatusRecPtr */ static inline void updateEventOnFAILED(const Dem_EventParameterType *eventParam, EventStatusRecType *eventStatusRecPtr) { if (0 == (eventStatusRecPtr->eventStatusExtended & DEM_TEST_FAILED)) { if( eventStatusRecPtr->occurrence < DEM_OCCURENCE_COUNTER_MAX ) { eventStatusRecPtr->occurrence++;/* @req DEM523 *//* @req DEM524 *//* !req DEM625 */ } eventStatusRecPtr->errorStatusChanged = TRUE; } #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) if( TRUE == operationCycleIsStarted(eventParam->EventClass->AgingCycleRef) ) { eventStatusRecPtr->failedDuringAgingCycle = TRUE; } handleAgingCounterOnFailed(eventParam, eventStatusRecPtr); #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) /* Handle fault confirmation *//** @req DEM379.ConfirmedSet */ handleFaultConfirmation(eventParam, eventStatusRecPtr); #endif /** @req DEM036 */ /** @req DEM379.PendingSet */ eventStatusRecPtr->eventStatusExtended |= (DEM_TEST_FAILED | DEM_TEST_FAILED_THIS_OPERATION_CYCLE | DEM_TEST_FAILED_SINCE_LAST_CLEAR | DEM_PENDING_DTC); eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)~(DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR | DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE); } /** * Performs event updates when event is qualified as PASSED * @param eventParam * @param eventStatusRecPtr */ static inline void updateEventOnPASSED(const Dem_EventParameterType *eventParam, EventStatusRecType *eventStatusRecPtr) { if ( 0 != (eventStatusRecPtr->eventStatusExtended & DEM_TEST_FAILED) ) { eventStatusRecPtr->errorStatusChanged = TRUE; } /** @req DEM036 */ eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)~DEM_TEST_FAILED; eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)~(DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR | DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE); #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) if( TRUE == operationCycleIsStarted(eventParam->EventClass->AgingCycleRef) ) { eventStatusRecPtr->passedDuringAgingCycle = TRUE; } #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) if( TRUE == operationCycleIsStarted((Dem_OperationCycleIdType)*(eventParam->EventClass->FailureCycleRef))) { eventStatusRecPtr->passedDuringFailureCycle = TRUE; } #endif } /* * Procedure: updateEventStatusRec * Description: Update the status of "eventId" */ static void updateEventStatusRec(const Dem_EventParameterType *eventParam, Dem_EventStatusType reportedEventStatus, EventStatusRecType *eventStatusRecPtr) { /* IMPROVEMENT: !req DEM544 */ Dem_EventStatusType eventStatus = reportedEventStatus; if (eventStatusRecPtr != NULL) { eventStatus = RunPredebounce(reportedEventStatus, eventStatusRecPtr, eventParam); eventStatusRecPtr->errorStatusChanged = FALSE; eventStatusRecPtr->extensionDataChanged = FALSE; eventStatusRecPtr->indicatorDataChanged = FALSE; eventStatusRecPtr->extensionDataStoreBitfield = 0; #if defined(USE_DEM_EXTENSION) Dem_EventStatusExtendedType eventStatusExtendedBeforeUpdate = eventStatusRecPtr->eventStatusExtended; #endif switch(eventStatus) { case DEM_EVENT_STATUS_FAILED: updateEventOnFAILED(eventParam, eventStatusRecPtr); break; case DEM_EVENT_STATUS_PASSED: updateEventOnPASSED(eventParam, eventStatusRecPtr); break; default: break; } #if defined(DEM_USE_IUMPR) incrementObserverIumprNumerator(eventParam->EventID, eventStatus); #endif #if defined(DEM_USE_INDICATORS) /** @req DEM379.WarningIndicatorSet */ if(TRUE == handleIndicators(eventParam, eventStatusRecPtr, eventStatus)) { eventStatusRecPtr->indicatorDataChanged = TRUE; } #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_UpdateEventstatus(eventStatusRecPtr, eventStatusExtendedBeforeUpdate, eventStatus); #endif eventStatusRecPtr->maxUDSFdc = MAX(eventStatusRecPtr->maxUDSFdc, eventStatusRecPtr->UDSFdc); #if (DEM_USE_TIMESTAMPS == STD_ON) && defined (DEM_USE_MEMORY_FUNCTIONS) if( (TRUE == eventStatusRecPtr->errorStatusChanged) && (eventStatus == DEM_EVENT_STATUS_FAILED) ) { /* Test just failed. Need to set timestamp */ setEventTimeStamp(eventStatusRecPtr); } #endif } } /* * Procedure: mergeEventStatusRec * Description: Update the occurrence counter of status, if not exist a new record is created */ #ifdef DEM_USE_MEMORY_FUNCTIONS static boolean mergeEventStatusRec(const EventRecType *eventRec) { EventStatusRecType *eventStatusRecPtr; const Dem_EventParameterType *eventParam; boolean statusChanged = FALSE; // Lookup event ID lookupEventStatusRec(eventRec->EventData.eventId, &eventStatusRecPtr); lookupEventIdParameter(eventRec->EventData.eventId, &eventParam); if (eventStatusRecPtr != NULL) { // Update occurrence counter. eventStatusRecPtr->occurrence += eventRec->EventData.occurrence; // Merge event status extended with stored // TEST_FAILED_SINCE_LAST_CLEAR should be set if set if set in either eventStatusRecPtr->eventStatusExtended |= (Dem_EventStatusExtendedType)(eventRec->EventData.eventStatusExtended & DEM_TEST_FAILED_SINCE_LAST_CLEAR); // DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR should cleared if cleared in either if((eventRec->EventData.eventStatusExtended & eventStatusRecPtr->eventStatusExtended & DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR) == 0u) { eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)~(Dem_EventStatusExtendedType)DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR; } // DEM_PENDING_DTC and DEM_CONFIRMED_DTC should be set if set in either eventStatusRecPtr->eventStatusExtended |= (Dem_EventStatusExtendedType)(eventRec->EventData.eventStatusExtended & (DEM_PENDING_DTC | DEM_CONFIRMED_DTC)); // DEM_WARNING_INDICATOR_REQUESTED should be set criteria fulfilled #if defined(DEM_USE_INDICATORS) if( TRUE == warningIndicatorOnCriteriaFulfilled(eventParam) ) { eventStatusRecPtr->eventStatusExtended |= DEM_WARNING_INDICATOR_REQUESTED; } #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) // Update confirmation counter if( (DEM_FAILURE_CNTR_MAX - eventRec->EventData.failureCounter) < eventStatusRecPtr->failureCounter) { /* Would overflow */ eventStatusRecPtr->failureCounter = DEM_FAILURE_CNTR_MAX; } else { eventStatusRecPtr->failureCounter += eventRec->EventData.failureCounter; } if( (NULL != eventParam) && (TRUE == faultConfirmationCriteriaFulfilled(eventParam, eventStatusRecPtr)) ) { eventStatusRecPtr->eventStatusExtended |= (Dem_EventStatusExtendedType)DEM_CONFIRMED_DTC; } #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) // Update confirmation counter if( (DEM_AGING_CNTR_MAX - eventRec->EventData.agingCounter) < eventStatusRecPtr->agingCounter) { /* Would overflow */ eventStatusRecPtr->agingCounter = DEM_AGING_CNTR_MAX; } else { eventStatusRecPtr->agingCounter += eventRec->EventData.agingCounter; } #endif #if (DEM_TEST_FAILED_STORAGE == STD_ON) /* @req DEM387 */ /* @req DEM388 */ /* @req DEM525 */ if( 0 != (eventStatusRecPtr->eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE) ) { /* Test has not been completed this operation cycle. Set test failed bit as in stored */ eventStatusRecPtr->eventStatusExtended |= (eventRec->EventData.eventStatusExtended & DEM_TEST_FAILED); } #endif #if (DEM_USE_TIMESTAMPS == STD_ON) if( 0u == (eventStatusRecPtr->eventStatusExtended & DEM_TEST_FAILED_THIS_OPERATION_CYCLE) ) { /* Test has not failed this operation cycle. Means that the that the timestamp * should be set to the one read from NvRam */ eventStatusRecPtr->timeStamp = eventRec->EventData.timeStamp; } #endif if( (eventStatusRecPtr->occurrence != eventRec->EventData.occurrence) || #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) (eventStatusRecPtr->failureCounter != eventRec->EventData.failureCounter) || #endif (GET_STORED_STATUS_BITS(eventStatusRecPtr->eventStatusExtended) != GET_STORED_STATUS_BITS(eventRec->EventData.eventStatusExtended)) ) { statusChanged = TRUE; } if( 0 == (eventStatusRecPtr->eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE) ) { /* Test was completed during preInit, means that the eventStatus was changed in some way */ Dem_EventStatusExtendedType oldStatus = (Dem_EventStatusExtendedType)(GET_STORED_STATUS_BITS(eventRec->EventData.eventStatusExtended)); notifyEventStatusChange(eventStatusRecPtr->eventParamRef, oldStatus, eventStatusRecPtr->eventStatusExtended); } } return statusChanged; } /* * Procedure: resetEventStatusRec * Description: Reset the status record of "eventParam->eventId" from "eventStatusBuffer". */ static void resetEventStatusRec(const Dem_EventParameterType *eventParam) { EventStatusRecType *eventStatusRecPtr; // Lookup event ID lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if (eventStatusRecPtr != NULL) { // Reset event record resetDebounceCounter(eventStatusRecPtr); eventStatusRecPtr->eventStatusExtended = DEM_DEFAULT_EVENT_STATUS;/** @req DEM385 *//** @req DEM440 */ eventStatusRecPtr->errorStatusChanged = FALSE; eventStatusRecPtr->occurrence = 0; #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->failureCounter = 0; eventStatusRecPtr->failedDuringFailureCycle = FALSE; eventStatusRecPtr->passedDuringFailureCycle = FALSE; #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->agingCounter = 0; eventStatusRecPtr->failedDuringAgingCycle = FALSE; eventStatusRecPtr->passedDuringAgingCycle = FALSE; #endif eventStatusRecPtr->timeStamp = 0; } } #endif /* * Procedure: getEventStatusRec * Description: Returns the status record of "eventId" in "eventStatusRec" */ static void getEventStatusRec(Dem_EventIdType eventId, EventStatusRecType *eventStatusRec) { EventStatusRecType *eventStatusRecPtr; // Lookup event ID lookupEventStatusRec(eventId, &eventStatusRecPtr); if (eventStatusRecPtr != NULL) { // Copy the record memcpy(eventStatusRec, eventStatusRecPtr, sizeof(EventStatusRecType)); } else { eventStatusRec->eventId = DEM_EVENT_ID_NULL; } } /** * Sets overflow indication for a specific memory * @param origin * @param overflow */ #ifdef DEM_USE_MEMORY_FUNCTIONS static void setOverflowIndication(Dem_DTCOriginType origin, boolean overflow) { switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) priMemOverflow = overflow; if(overflow != priMemEventBuffer[PRI_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow) { priMemEventBuffer[PRI_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.magic = ADMIN_MAGIC; priMemEventBuffer[PRI_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow = overflow; /* Overflow not stored immediately */ Dem_NvM_SetEventBlockChanged(origin, FALSE); } #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) secMemOverflow = overflow; if( overflow != secMemEventBuffer[SEC_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow ) { secMemEventBuffer[SEC_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.magic = ADMIN_MAGIC; secMemEventBuffer[SEC_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow = overflow; /* Overflow not stored immediately */ Dem_NvM_SetEventBlockChanged(origin, FALSE); } #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: break; } } #endif /** * Returns the overflow indication for a specific memory * @param origin * @return E_OK: Operation successful, E_NOT_OK: Operation failed */ static Std_ReturnType getOverflowIndication(Dem_DTCOriginType origin, boolean *Overflow) { Std_ReturnType ret = E_OK; switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) *Overflow = priMemOverflow; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) *Overflow = secMemOverflow; #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: default: /* Not yet supported */ ret = E_NOT_OK; DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; } return ret; } /** * Returns the occurence counter * @param eventParameter * @return */ static uint16 getEventOccurence(const Dem_EventParameterType *eventParameter) { EventStatusRecType *eventStatusRec = NULL_PTR; uint16 occurence = 0u; if( NULL != eventParameter ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParameter->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParameter->CombinedDTCCID]; CombDTCCfg = &configSet->CombinedDTCConfig[eventParameter->CombinedDTCCID]; for(uint16 evIdx = 0; evIdx < CombDTCCfg->DTCClassRef->NofEvents; evIdx++) { eventStatusRec = NULL_PTR; lookupEventStatusRec(CombDTCCfg->DTCClassRef->Events[evIdx], &eventStatusRec); if( (NULL_PTR != eventStatusRec) && (eventStatusRec->occurrence > occurence) ) { occurence = eventStatusRec->occurrence; } } } else { lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { occurence = eventStatusRec->occurrence; } } #else lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { occurence = eventStatusRec->occurrence; } #endif } return occurence; } static sint8 getEventFDC(const Dem_EventParameterType *eventParameter, boolean maxFDC) { EventStatusRecType *eventStatusRec = NULL_PTR; sint8 FDC = 0; if( NULL != eventParameter ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParameter->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParameter->CombinedDTCCID]; sint8 tempFDC; for(uint16 evIdx = 0; evIdx < CombDTCCfg->DTCClassRef->NofEvents; evIdx++) { eventStatusRec = NULL_PTR; lookupEventStatusRec(CombDTCCfg->DTCClassRef->Events[evIdx], &eventStatusRec); if( NULL_PTR != eventStatusRec ) { tempFDC = (TRUE == maxFDC) ? eventStatusRec->maxUDSFdc : eventStatusRec->UDSFdc; if( tempFDC > FDC ) { FDC = tempFDC; } } } } else { lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { FDC = (TRUE == maxFDC) ? eventStatusRec->maxUDSFdc : eventStatusRec->UDSFdc; } } #else lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { FDC = (TRUE == maxFDC) ? eventStatusRec->maxUDSFdc : eventStatusRec->UDSFdc; } #endif } return FDC; } #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) /** * Gets the aging counter * @param eventParameter * @return */ uint8 getEventAgingCntr(const Dem_EventParameterType *eventParameter) { /* IMPROVEMENT: External aging.. */ EventStatusRecType *eventStatusRec = NULL_PTR; uint8 agingCnt = 0u; if( NULL != eventParameter ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParameter->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParameter->CombinedDTCCID]; agingCnt = 0xFFu; boolean cntrValid = FALSE; for(uint16 evIdx = 0; evIdx < CombDTCCfg->DTCClassRef->NofEvents; evIdx++) { eventStatusRec = NULL_PTR; lookupEventStatusRec(CombDTCCfg->DTCClassRef->Events[evIdx], &eventStatusRec); if( (NULL_PTR != eventStatusRec) && (TRUE == eventStatusRec->eventParamRef->EventClass->AgingAllowed) && (0u != (eventStatusRec->eventStatusExtended & DEM_CONFIRMED_DTC)) ) { if( eventStatusRec->agingCounter < agingCnt ) { agingCnt = eventStatusRec->agingCounter; } cntrValid = TRUE; } } if( FALSE == cntrValid ) { /* @req DEM646 */ agingCnt = 0u; } } else { lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( (NULL_PTR != eventStatusRec) && (TRUE == eventParameter->EventClass->AgingAllowed) ) { agingCnt = eventStatusRec->agingCounter; } } #else lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( (NULL_PTR != eventStatusRec) && (TRUE == eventParameter->EventClass->AgingAllowed) ) { agingCnt = eventStatusRec->agingCounter; } #endif } return agingCnt; } #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) /** * Gets the failure counter * @param eventParameter * @return */ static uint8 getEventFailureCnt(const Dem_EventParameterType *eventParameter) { EventStatusRecType *eventStatusRec = NULL_PTR; uint8 failCnt = 0u; if( NULL != eventParameter ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParameter->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParameter->CombinedDTCCID]; for(uint16 evIdx = 0; evIdx < CombDTCCfg->DTCClassRef->NofEvents; evIdx++) { eventStatusRec = NULL_PTR; lookupEventStatusRec(CombDTCCfg->DTCClassRef->Events[evIdx], &eventStatusRec); if( (NULL_PTR != eventStatusRec) && (eventStatusRec->failureCounter > failCnt) ) { failCnt = eventStatusRec->failureCounter; } } } else { lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { failCnt = eventStatusRec->failureCounter; } } #else lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); if( NULL_PTR != eventStatusRec ) { failCnt = eventStatusRec->failureCounter; } #endif } return failCnt; } #endif /** * Reads internal element * @param eventParameter * @param elementType * @param buf * @param size */ static void getInternalElement( const Dem_EventParameterType *eventParameter, Dem_InternalDataElementType elementType, uint8* buf, uint16 size ) { /* !req DEM592 *//* SIGNIFICANCE not supported */ EventStatusRecType *eventStatusRec; lookupEventStatusRec(eventParameter->EventID, &eventStatusRec); uint16 occurrence; if( (DEM_EVENT_ID_NULL != eventStatusRec->eventId) && (size > 0) ) { memset(buf, 0, (size_t)size); switch(elementType) { case DEM_OCCCTR: /* @req DEM471 */ occurrence = getEventOccurence(eventParameter); if(1 == size) { buf[0] = (uint8)MIN(occurrence, 0xFF); } else { buf[size - 2] = (uint8)((occurrence & 0xff00u) >> 8u); buf[size - 1] = (uint8)(occurrence & 0xffu); } break; case DEM_FAULTDETCTR: /* @req OEM_DEM_10185 */ buf[size - 1] = (uint8)getEventFDC(eventParameter, FALSE); break; case DEM_MAXFAULTDETCTR: buf[size - 1] = (uint8)getEventFDC(eventParameter, TRUE); break; case DEM_OVFLIND: { /* @req DEM473 */ boolean ovflw = FALSE; if( E_OK == getOverflowIndication(eventParameter->EventClass->EventDestination, &ovflw) ) { buf[size - 1] = (TRUE == ovflw) ? 1 : 0; } else { buf[size - 1] = 0; } } break; #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) case DEM_AGINGCTR: /* @req DEM472 *//* !req DEM644 *//* !req DEM647 */ /* @req DEM646 */ /* set to 0 by memset above */ buf[size - 1] = getEventAgingCntr(eventParameter); break; #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) case DEM_CONFIRMATIONCNTR: buf[size - 1] = getEventFailureCnt(eventParameter); break; #endif default: #if defined(USE_DEM_EXTENSION) Dem_Extension_GetExtendedDataInternalElement(eventParameter->EventID, elementType, buf, size); #endif break; } } } #if defined(USE_DEM_EXTENSION) /* * Procedure: lookupDtcEvent * Description: Returns TRUE if the DTC was found and "eventStatusRec" points * to the event record found. */ /* @req 4.2.2/DEM_00915 */ boolean Dem_LookupEventOfUdsDTC(uint32 dtc, EventStatusRecType **eventStatusRec) { boolean dtcFound = FALSE; uint16 i; *eventStatusRec = NULL; for (i = 0; (i < DEM_MAX_NUMBER_EVENT) && (dtcFound == FALSE); i++) { if (eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) { if (eventStatusBuffer[i].eventParamRef->DTCClassRef != NULL) { /* Check DTC. Ignore suppressed DTCs *//* @req DEM587 */ if ((eventStatusBuffer[i].eventParamRef->DTCClassRef->DTCRef->UDSDTC == dtc) && (DTCIsAvailable(eventStatusBuffer[i].eventParamRef->DTCClassRef))) { *eventStatusRec = &eventStatusBuffer[i]; dtcFound = TRUE; } } } } return dtcFound; } #endif /** * Function for finding configuration of UDS DTC. * @param dtc * @param DTCClass * @return */ static boolean LookupUdsDTC(uint32 dtc, const Dem_DTCClassType **DTCClass) { boolean DTCFound = FALSE; const Dem_DTCClassType *DTCClassPtr = configSet->DTCClass; while( FALSE == DTCClassPtr->Arc_EOL ) { if( (DTCClassPtr->DTCRef->UDSDTC == dtc) ) { *DTCClass = DTCClassPtr; DTCFound = DTCIsAvailable(DTCClassPtr); break; } DTCClassPtr++; } return DTCFound; } /** * Gets the UDS status of a DTC in a specific origin. * @param DTCClass * @param DTCOrigin * @param status * @return */ static Dem_ReturnGetStatusOfDTCType GetDTCUDSStatus(const Dem_DTCClassType *DTCClass, Dem_DTCOriginType DTCOrigin, Dem_EventStatusExtendedType *status) { Dem_ReturnGetStatusOfDTCType ret = DEM_STATUS_OK; EventStatusRecType *eventStatusRecPtr; uint8 mask = 0xFFU; uint16 nofEventsInOrigin = 0u; Dem_EventStatusExtendedType temp = 0u; for(uint16 i = 0; (i < DTCClass->NofEvents) && (DEM_STATUS_OK == ret); i++) { eventStatusRecPtr = NULL_PTR; lookupEventStatusRec(DTCClass->Events[i], &eventStatusRecPtr); if( NULL_PTR != eventStatusRecPtr ) { /* Event found for this DTC */ if( TRUE == checkDtcOrigin(DTCOrigin,eventStatusRecPtr->eventParamRef, TRUE) ) { /* NOTE: Should the availability mask be used here? */ /* @req DEM059 */ /* @req DEM441 */ if( TRUE == eventStatusRecPtr->isAvailable ) { temp |= eventStatusRecPtr->eventStatusExtended; nofEventsInOrigin++; } } else { /* Event not available in DTCOrigin */ /** @req DEM172 */ } } else { /* This is unexpected. Fail operation. */ ret = DEM_STATUS_FAILED; } } if( DEM_STATUS_OK == ret ) { if( 0u == nofEventsInOrigin ) { /* No events where found in the origin. */ ret = DEM_STATUS_WRONG_DTCORIGIN; } else if( (DTCClass->NofEvents > 1u) && (0u != nofEventsInOrigin) ) { /* This is a combined DTC. Bits have already been OR-ed above. Now we should and bits. */ /* @req DEM441 */ mask = ((temp & (1u << 5u)) >> 1u) | ((temp & (1u << 1u)) << 5u); mask = (uint8)((~mask) & 0xFFu); } else { /* One event found. Do nomasking. */ } } *status = (temp & mask); return ret; } /* * Procedure: matchEventWithDtcFilter * Description: Returns TRUE if the event pointed by "event" fulfill * the "dtcFilter" global filter settings. */ /** * Checks if a DTC matches the current filter settings. If it matches the UDS status is returned. * @param DTCClass * @param UDSStatus * @return */ static boolean matchDTCWithDtcFilter(const Dem_DTCClassType *DTCClass, Dem_EventStatusExtendedType *UDSStatus) { boolean dtcMatch = FALSE; Dem_EventStatusExtendedType DTCStatus; if( DEM_STATUS_OK == GetDTCUDSStatus(DTCClass, dtcFilter.dtcOrigin, &DTCStatus) ) { /* Status available in origin. */ if ( TRUE == checkDtcStatusMask(dtcFilter.dtcStatusMask, DTCStatus) ) { /* Check the DTC kind. */ if( (dtcFilter.dtcKind == DEM_DTC_KIND_ALL_DTCS) || (DEM_NO_DTC != DTCClass->DTCRef->OBDDTC) ) { /* Check severity */ if ((dtcFilter.filterWithSeverity == DEM_FILTER_WITH_SEVERITY_NO) || ((dtcFilter.filterWithSeverity == DEM_FILTER_WITH_SEVERITY_YES) && (TRUE == checkDtcSeverityMask(dtcFilter.dtcSeverityMask, DTCClass)))) { /* Check fault detection counter. No support for DEM_FILTER_FOR_FDC_YES */ if( dtcFilter.filterForFaultDetectionCounter == DEM_FILTER_FOR_FDC_NO) { /* Check the DTC */ if( (TRUE == DTCIsAvailable(DTCClass)) && (TRUE == DTCISAvailableOnFormat(DTCClass, dtcFilter.dtcFormat)) ) { dtcMatch = TRUE; *UDSStatus = DTCStatus; } } } } } } return dtcMatch; } /* Function: eventDTCRecordDataUpdateDisabled * Description: Checks if update of event related data (extended data or freezeframe data) has been disabled */ static boolean eventDTCRecordDataUpdateDisabled(const Dem_EventParameterType *eventParam) { boolean disabled = FALSE; if( (NO_DTC_DISABLED != DTCRecordDisabled.DTC) && /* There is a disabled DTC */ (NULL != eventParam) && /* Argument ok */ (NULL != eventParam->DTCClassRef) && /* Event has a DTC */ (DEM_NO_DTC != eventParam->DTCClassRef->DTCRef->UDSDTC) && /* And a DTC on UDS format */ (DTCRecordDisabled.DTC == eventParam->DTCClassRef->DTCRef->UDSDTC) && /* The disabled DTC is the DTC of the event */ (DTCRecordDisabled.Origin == eventParam->EventClass->EventDestination)) { /* The disabled origin is the origin of the event */ /* DTC record update for this event is disabled */ disabled = TRUE; } return disabled; } #if (DEM_USE_TIMESTAMPS == STD_ON) #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) || \ ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) || \ (DEM_FF_DATA_IN_PRE_INIT) /* * Functions for rearranging timestamps * * */ /** * Sorts entries in freeze frame buffers. Oldest freeze frame first, etc. Sets a new timestamp (0-"nof ff entries") * Returns the timestamp to use for next stored FF. * @param timeStamp, pointer to timestamp used by caller. Shall be set to the next timestamp to use. */ #if (DEM_UNIT_TEST == STD_ON) void rearrangeFreezeFrameTimeStamp(uint32 *timeStamp) #else static void rearrangeFreezeFrameTimeStamp(uint32 *timeStamp ) #endif { FreezeFrameRecType temp; uint32 i; uint32 j = 0; uint32 k = 0; uint32 bufferIndex; /* These two arrays are looped below must have the same size */ #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM && (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM uint32 ffBufferSizes[2] = {DEM_MAX_NUMBER_FF_DATA_PRI_MEM, DEM_MAX_NUMBER_FF_DATA_SEC_MEM}; FreezeFrameRecType* ffBuffers[2] = {priMemFreezeFrameBuffer, secMemFreezeFrameBuffer}; uint32 nofSupportedDestinations = 2; #elif (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON && DEM_FF_DATA_IN_PRI_MEM) uint32 ffBufferSizes[1] = {DEM_MAX_NUMBER_FF_DATA_PRI_MEM}; FreezeFrameRecType* ffBuffers[1] = {priMemFreezeFrameBuffer}; uint32 nofSupportedDestinations = 1; #elif (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM uint32 ffBufferSizes[1] = {DEM_MAX_NUMBER_FF_DATA_SEC_MEM}; FreezeFrameRecType* ffBuffers[1] = {secMemFreezeFrameBuffer}; uint32 nofSupportedDestinations = 1; #else uint32 ffBufferSizes[1] = {0}; FreezeFrameRecType* ffBuffers[1] = {NULL}; uint32 nofSupportedDestinations = 0; #endif for (bufferIndex = 0; bufferIndex < nofSupportedDestinations; bufferIndex++) { FreezeFrameRecType* ffBuffer = ffBuffers[bufferIndex]; uint32 ffBufferSize = ffBufferSizes[bufferIndex]; /* Bubble sort:rearrange ffBuffer from little to big */ for(i = 0; i < ffBufferSize; i++){ if(ffBuffer[i].eventId != DEM_EVENT_ID_NULL){ for( j = ffBufferSize - 1; j > i; j--){ if(ffBuffer[j].eventId != DEM_EVENT_ID_NULL){ if(ffBuffer[i].timeStamp > ffBuffer[j].timeStamp){ //exchange buffer data memcpy(&temp,&ffBuffer[i],sizeof(FreezeFrameRecType)); memcpy(&ffBuffer[i],&ffBuffer[j],sizeof(FreezeFrameRecType)); memcpy(&ffBuffer[j],&temp,sizeof(FreezeFrameRecType)); } } } ffBuffer[i].timeStamp = k++; } } } /* update the current timeStamp */ *timeStamp = k; } #endif #if (DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) /** * Sorts entries in extended buffers. Oldest extended data first, etc. Sets a new timestamp (0-"nof ff entries") * Returns the timestamp to use for next stored extended data. * @param timeStamp, pointer to timestamp used by caller. Shall be set to the next timestamp to use. */ #if (DEM_UNIT_TEST == STD_ON) void rearrangeExtDataTimeStamp(uint32 *timeStamp) #else static void rearrangeExtDataTimeStamp(uint32 *timeStamp) #endif { ExtDataRecType temp; uint32 i; uint32 j = 0; uint32 k = 0; uint32 bufferIndex; /* These two arrays are looped below must have the same size */ #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_PRI_MEM && (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_SEC_MEM uint32 extBufferSizes[2] = {DEM_MAX_NUMBER_EXT_DATA_PRI_MEM, DEM_MAX_NUMBER_EXT_DATA_SEC_MEM}; ExtDataRecType* extBuffers[2] = {priMemExtDataBuffer, secMemExtDataBuffer}; uint32 nofDestinations = 2; #elif (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON && DEM_EXT_DATA_IN_PRI_MEM) uint32 extBufferSizes[1] = {DEM_MAX_NUMBER_EXT_DATA_PRI_MEM}; ExtDataRecType* extBuffers[1] = {priMemExtDataBuffer}; uint32 nofDestinations = 1; #elif (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON && DEM_EXT_DATA_IN_SEC_MEM) uint32 extBufferSizes[1] = {DEM_MAX_NUMBER_EXT_DATA_SEC_MEM}; ExtDataRecType* extBuffers[1] = {secMemExtDataBuffer}; uint32 nofDestinations = 1; #else uint32 extBufferSizes[1] = {0}; ExtDataRecType* extBuffers[1] = {NULL}; uint32 nofDestinations = 0; #endif for (bufferIndex = 0; bufferIndex < nofDestinations; bufferIndex++) { ExtDataRecType* extBuffer = extBuffers[bufferIndex]; uint32 extBufferSize = extBufferSizes[bufferIndex]; /* Bubble sort:rearrange Buffer from little to big */ for( i = 0; i < extBufferSize; i++ ){ if( DEM_EVENT_ID_NULL != extBuffer[i].eventId ){ for( j = extBufferSize - 1; j > i; j-- ){ if( DEM_EVENT_ID_NULL != extBuffer[j].eventId ){ if( extBuffer[i].timeStamp > extBuffer[j].timeStamp ){ //exchange buffer data memcpy(&temp, &extBuffer[i], sizeof(ExtDataRecType)); memcpy(&extBuffer[i], &extBuffer[j], sizeof(ExtDataRecType)); memcpy(&extBuffer[j], &temp, sizeof(ExtDataRecType)); } } } extBuffer[i].timeStamp = k++; } } } /* update the current timeStamp */ *timeStamp = k; } #endif #if defined(DEM_USE_MEMORY_FUNCTIONS) static void initCurrentEventTimeStamp(uint32 *timeStampPtr) { uint32 highestTimeStamp = 0; /* Rearrange events */ rearrangeEventTimeStamp(timeStampPtr); for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++){ if( DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId ){ eventStatusBuffer[i].timeStamp += *timeStampPtr; if( eventStatusBuffer[i].timeStamp > highestTimeStamp ) { highestTimeStamp = eventStatusBuffer[i].timeStamp; } } } *timeStampPtr = highestTimeStamp + 1; } /* * Functions for initializing timestamps * */ static void initCurrentFreezeFrameTimeStamp(uint32 *timeStampPtr) { #if ( DEM_FF_DATA_IN_PRE_INIT ) uint32 highestTimeStamp = 0; /* Rearrange freeze frames */ rearrangeFreezeFrameTimeStamp(timeStampPtr); for (uint16 i = 0; i<DEM_MAX_NUMBER_FF_DATA_PRE_INIT; i++){ if(preInitFreezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL){ preInitFreezeFrameBuffer[i].timeStamp += *timeStampPtr; if( preInitFreezeFrameBuffer[i].timeStamp > highestTimeStamp ) { highestTimeStamp = preInitFreezeFrameBuffer[i].timeStamp; } } } *timeStampPtr = highestTimeStamp + 1; #endif } static void initCurrentExtDataTimeStamp(uint32 *timeStampPtr) { #if ( DEM_EXT_DATA_IN_PRE_INIT && DEM_FF_DATA_IN_PRE_INIT ) uint32 highestTimeStamp = 0; /* Rearrange extended data in primary memory */ rearrangeExtDataTimeStamp(timeStampPtr); /* Increment the timestamps in the pre init ext data buffer */ for (uint16 i = 0; i < DEM_MAX_NUMBER_EXT_DATA_PRE_INIT; i++){ if( DEM_EVENT_ID_NULL != preInitExtDataBuffer[i].eventId ){ preInitExtDataBuffer[i].timeStamp += *timeStampPtr; if( preInitExtDataBuffer[i].timeStamp > highestTimeStamp ) { highestTimeStamp = preInitExtDataBuffer[i].timeStamp; } } } *timeStampPtr = highestTimeStamp + 1; #else (void)timeStampPtr; #endif } #if (DEM_UNIT_TEST == STD_ON) void rearrangeEventTimeStamp(uint32 *timeStamp) #else static void rearrangeEventTimeStamp(uint32 *timeStamp) #endif { FreezeFrameRecType temp; uint32 bufferIndex; uint32 i; uint32 j = 0; uint32 k = 0; /* These two arrays are looped below must have the same size */ #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) uint32 eventBufferSizes[2] = {DEM_MAX_NUMBER_EVENT_ENTRY_PRI, DEM_MAX_NUMBER_EVENT_ENTRY_SEC}; EventRecType* eventBuffers[2] = {priMemEventBuffer, secMemEventBuffer}; uint32 nofDestinations = 2; #elif (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) uint32 eventBufferSizes[1] = {DEM_MAX_NUMBER_EVENT_ENTRY_PRI}; EventRecType* eventBuffers[1] = {priMemEventBuffer}; uint32 nofDestinations = 1; #elif (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) uint32 eventBufferSizes[1] = {DEM_MAX_NUMBER_EVENT_ENTRY_SEC}; EventRecType* eventBuffers[1] = {secMemEventBuffer}; uint32 nofDestinations = 1; #else uint32 eventBufferSizes[1] = {0}; EventRecType* eventBuffers[1] = {NULL}; uint32 nofDestinations = 0; #endif for (bufferIndex = 0; bufferIndex < nofDestinations; bufferIndex++) { EventRecType* eventBuffer = eventBuffers[bufferIndex]; uint32 eventBufferSize = eventBufferSizes[bufferIndex]; /* Bubble sort:rearrange event buffer from little to big */ for( i = 0; i < eventBufferSize; i++ ){ if( DEM_EVENT_ID_NULL != eventBuffer[i].EventData.eventId ){ for( j = (eventBufferSize - 1); j > i; j-- ) { if( DEM_EVENT_ID_NULL != eventBuffer[j].EventData.eventId ) { if( eventBuffer[i].EventData.timeStamp > eventBuffer[j].EventData.timeStamp ) { //exchange buffer data memcpy(&temp, &eventBuffer[i].EventData, sizeof(EventRecType)); memcpy(&eventBuffer[i].EventData, &eventBuffer[j].EventData, sizeof(EventRecType)); memcpy(&eventBuffer[j].EventData, &temp, sizeof(EventRecType)); } } } eventBuffer[i].EventData.timeStamp = k++; } } } /* update the current timeStamp */ *timeStamp = k; } #endif /* DEM_USE_MEMORY_FUNCTIONS */ #endif /* (DEM_USE_TIMESTAMPS == STD_ON) */ #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && defined (DEM_USE_MEMORY_FUNCTIONS) #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM && (DEM_OBD_DISPLACEMENT_SUPPORT == STD_ON)) /** * Check if an event currently hold the OBD FF * @param eventParam * @return TRUE: Event holds OBD FF. FALSE: event does NOT hold the OBD FF */ static boolean eventHoldsOBDFF(const Dem_EventParameterType *eventParam) { boolean ret = FALSE; Dem_EventIdType idToFind; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else idToFind = eventParam->EventID; #endif for( uint32 i = 0; (i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM) && (FALSE == ret); i++ ) { if( (idToFind == priMemFreezeFrameBuffer[i].eventId) && (DEM_FREEZE_FRAME_OBD == priMemFreezeFrameBuffer[i].kind) ) { ret = TRUE; } } return ret; } #endif /* ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM && (DEM_OBD_DISPLACEMENT_SUPPORT == STD_ON)) */ /** * Checks if an event is an event may be displaced by another * @param candidateEventParam * @param eventParam * @return TRUE: Event may be displaced, FALSE: event may NOT be displaced */ static boolean obdEventDisplacementProhibited(const Dem_EventParameterType *candidateEventParam, const Dem_EventParameterType *eventParam) { #if (DEM_OBD_DISPLACEMENT_SUPPORT == STD_ON) Dem_EventStatusExtendedType evtStatus; boolean prohibited = FALSE; (void)getEventStatus(candidateEventParam->EventID, &evtStatus); if( (TRUE == eventIsEmissionRelated(candidateEventParam)) && ( #if defined(DEM_USE_INDICATORS) (TRUE == eventActivatesMIL(candidateEventParam)) || #endif #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) ((TRUE == eventHoldsOBDFF(candidateEventParam)) && (candidateEventParam->EventClass->EventPriority <= eventParam->EventClass->EventPriority)) || #endif (0u != (evtStatus & DEM_PENDING_DTC))) ) { prohibited = TRUE; } return prohibited; #else return FALSE; #endif } /** * Returns whether event is considered passive or not * @param eventId * @return TRUE: Event passive, FALSE: Event NOT passive */ static boolean getEventPassive(Dem_EventIdType eventId) { boolean eventPassive = FALSE; Dem_EventStatusExtendedType eventStatus = 0u; boolean statusFound = FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; if( DEM_STATUS_OK == GetDTCUDSStatus(CombDTCCfg->DTCClassRef, CombDTCCfg->MemoryDestination, &eventStatus) ) { statusFound = TRUE; } } else { const Dem_EventParameterType *eventParam = NULL; lookupEventIdParameter(eventId, &eventParam); if( NULL != eventParam ) { if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { if( DEM_STATUS_OK == GetDTCUDSStatus(eventParam->DTCClassRef, eventParam->EventClass->EventDestination, &eventStatus) ) { statusFound = TRUE; } } else { if( E_OK == getEventStatus(eventId, &eventStatus) ) { statusFound = TRUE; } } } } #else if( E_OK == getEventStatus(eventId, &eventStatus) ) { statusFound = TRUE; } #endif if( TRUE == statusFound ) { #if (DEM_TEST_FAILED_STORAGE == STD_ON) eventPassive = (0 == (eventStatus & DEM_TEST_FAILED)); #else eventPassive = (0 == (eventStatus & (DEM_TEST_FAILED | DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE))); #endif #if defined(CFG_DEM_TREAT_CONFIRMED_EVENTS_AS_ACTIVE) eventPassive = (0 != (eventStatus & DEM_CONFIRMED_DTC)) ? FALSE : eventPassive; #endif } return eventPassive; } /** * Return the priority of an event * @param eventId * @return Priority of event */ static uint8 getEventPriority(Dem_EventIdType eventId) { uint8 priority = 0xFF; const Dem_EventParameterType *eventParam = NULL; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; priority = CombDTCCfg->Priority; } else { lookupEventIdParameter(eventId, &eventParam); if( NULL != eventParam ) { if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; priority = CombDTCCfg->Priority; } else { priority = eventParam->EventClass->EventPriority; } } } #else lookupEventIdParameter(eventId, &eventParam); if( NULL != eventParam ) { priority = eventParam->EventClass->EventPriority; } #endif return priority; } #if ( DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM || DEM_FF_DATA_IN_PRE_INIT) static Std_ReturnType getFFEventForDisplacement(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *ffBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { /* See figure 25 in ASR 4.0.3 */ /* @req DEM403 */ /* @req DEM404 */ /* @req DEM405 */ /* @req DEM406 */ /* IMPROVEMENT: How do we handle the case when it is an OBD freeze frame that should be stored? * Should they be handled in the same way as "normal" freeze frames? */ Std_ReturnType ret = E_NOT_OK; uint32 removeCandidateIndex = 0; uint32 oldestPassive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint32 oldestActive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint8 eventPrio = 0xFF; boolean eventPassive = FALSE; boolean passiveCandidateFound = FALSE; boolean activeCandidateFound = FALSE; boolean eventDataRemovalProhibited = FALSE; boolean obdProhibitsRemoval = FALSE; const Dem_EventParameterType *candidateEventParam; for( uint32 i = 0; i < bufferSize; i++ ) { if( (DEM_EVENT_ID_NULL != ffBuffer[i].eventId) && (eventParam->EventID != ffBuffer[i].eventId) && (DEM_FREEZE_FRAME_OBD != ffBuffer[i].kind) ) { candidateEventParam = NULL; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* Event id may be a combined id. */ if( IS_COMBINED_EVENT_ID(ffBuffer[i].eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(ffBuffer[i].eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(ffBuffer[i].eventId)]; /* Just grab the first event for this DTC. */ lookupEventIdParameter(CombDTCCfg->DTCClassRef->Events[0u], &candidateEventParam); } else { lookupEventIdParameter(ffBuffer[i].eventId, &candidateEventParam); } #else lookupEventIdParameter(ffBuffer[i].eventId, &candidateEventParam); #endif if(NO_DTC_DISABLED != DTCRecordDisabled.DTC) { eventDataRemovalProhibited = eventDTCRecordDataUpdateDisabled(candidateEventParam); } else { eventDataRemovalProhibited = FALSE; } obdProhibitsRemoval = obdEventDisplacementProhibited(candidateEventParam, eventParam); if( (FALSE == eventDataRemovalProhibited) && (FALSE == obdProhibitsRemoval) ) { /* Check if priority if the event is higher or equal (low numerical value of priority means high priority..) *//* @req DEM383 */ eventPrio = getEventPriority(ffBuffer[i].eventId); eventPassive = getEventPassive(ffBuffer[i].eventId); /* IMPROVEMENT: Remove the one with lowest priority? */ if( (eventParam->EventClass->EventPriority <= eventPrio) && (TRUE == eventPassive) && (oldestPassive_TimeStamp > ffBuffer[i].timeStamp) ) { /* This event has lower or equal priority to the reported event, it is passive * and it is the oldest currently found. A candidate for removal. */ oldestPassive_TimeStamp = ffBuffer[i].timeStamp; removeCandidateIndex = i; passiveCandidateFound = TRUE; } if( FALSE == passiveCandidateFound ) { /* Currently, a passive event with lower or equal priority has not been found. * Check if the priority is less than for the reported event. Store the oldest. */ if( (eventParam->EventClass->EventPriority < eventPrio) && (oldestActive_TimeStamp > ffBuffer[i].timeStamp) ) { oldestActive_TimeStamp = ffBuffer[i].timeStamp; removeCandidateIndex = i; activeCandidateFound = TRUE; } } } } } if( (TRUE == passiveCandidateFound) || (TRUE == activeCandidateFound) ) { *eventToRemove = ffBuffer[removeCandidateIndex].eventId; ret = E_OK; } return ret; } #endif /* DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM || DEM_FF_DATA_IN_PRE_INIT */ #if (DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) static Std_ReturnType getExtDataEventForDisplacement(const Dem_EventParameterType *eventParam, const ExtDataRecType *extDataBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { /* See figure 25 in ASR 4.0.3 */ /* @req DEM403 */ /* @req DEM404 */ /* @req DEM405 */ /* @req DEM406 */ Std_ReturnType ret = E_NOT_OK; uint32 removeCandidateIndex = 0; uint32 oldestPassive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint32 oldestActive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint8 eventPrio = 0xFF; boolean eventPassive = FALSE; boolean passiveCandidateFound = FALSE; boolean activeCandidateFound = FALSE; boolean eventDataRemovalProhibited = FALSE; boolean obdProhibitsRemoval = FALSE; const Dem_EventParameterType *candidateEventParam = NULL; for( uint32 i = 0; i < bufferSize; i++ ) { if( DEM_EVENT_ID_NULL != extDataBuffer[i].eventId ) { /* Check if we are allowed to remove data for this event */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* Event id may be a combined id. */ if( IS_COMBINED_EVENT_ID(extDataBuffer[i].eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(extDataBuffer[i].eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(extDataBuffer[i].eventId)]; /* Just grab the first event for this DTC. */ lookupEventIdParameter(CombDTCCfg->DTCClassRef->Events[0u], &candidateEventParam); } else { lookupEventIdParameter(extDataBuffer[i].eventId, &candidateEventParam); } #else lookupEventIdParameter(extDataBuffer[i].eventId, &candidateEventParam); #endif if(NO_DTC_DISABLED != DTCRecordDisabled.DTC) { eventDataRemovalProhibited = eventDTCRecordDataUpdateDisabled(candidateEventParam); } else { eventDataRemovalProhibited = FALSE; } obdProhibitsRemoval = obdEventDisplacementProhibited(candidateEventParam, eventParam); if( (FALSE == eventDataRemovalProhibited) && (FALSE == obdProhibitsRemoval) ) { /* Check if priority if the event is higher or equal (low numerical value of priority means high priority..) *//* @req DEM383 */ eventPrio = getEventPriority(extDataBuffer[i].eventId); eventPassive = getEventPassive(extDataBuffer[i].eventId); if( (eventParam->EventClass->EventPriority <= eventPrio) && (TRUE == eventPassive) && (oldestPassive_TimeStamp > extDataBuffer[i].timeStamp) ) { /* This event has lower or equal priority to the reported event, it is passive * and it is the oldest currently found. A candidate for removal. */ oldestPassive_TimeStamp = extDataBuffer[i].timeStamp; removeCandidateIndex = i; passiveCandidateFound = TRUE; } if( FALSE == passiveCandidateFound ) { /* Currently, a passive event with lower or equal priority has not been found. * Check if the priority is less than for the reported event. Store the oldest. */ if( (eventParam->EventClass->EventPriority < eventPrio) && (oldestActive_TimeStamp > extDataBuffer[i].timeStamp) ) { oldestActive_TimeStamp = extDataBuffer[i].timeStamp; removeCandidateIndex = i; activeCandidateFound = TRUE; } } } } } if( (TRUE == passiveCandidateFound) || (TRUE == activeCandidateFound) ) { *eventToRemove = extDataBuffer[removeCandidateIndex].eventId; ret = E_OK; } return ret; } #endif /* (DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) */ #ifdef DEM_USE_MEMORY_FUNCTIONS static Std_ReturnType getEventForDisplacement(const Dem_EventParameterType *eventParam, const EventRecType *eventBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { /* See figure 25 in ASR 4.0.3 */ /* @req DEM403 */ /* @req DEM404 */ /* @req DEM405 */ /* @req DEM406 */ Std_ReturnType ret = E_NOT_OK; uint32 removeCandidateIndex = 0; uint32 oldestPassive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint32 oldestActive_TimeStamp = DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT; uint8 eventPrio = 0xFF; boolean eventPassive = FALSE; boolean passiveCandidateFound = FALSE; boolean activeCandidateFound = FALSE; boolean eventDataRemovalProhibited = FALSE; boolean obdProhibitsRemoval = FALSE; const Dem_EventParameterType *candidateEventParam = NULL; for( uint32 i = 0; i < bufferSize; i++ ) { if( DEM_EVENT_ID_NULL != eventBuffer[i].EventData.eventId ) { lookupEventIdParameter(eventBuffer[i].EventData.eventId, &candidateEventParam); if(NO_DTC_DISABLED != DTCRecordDisabled.DTC) { eventDataRemovalProhibited = eventDTCRecordDataUpdateDisabled(candidateEventParam); } else { eventDataRemovalProhibited = FALSE; } obdProhibitsRemoval = obdEventDisplacementProhibited(candidateEventParam, eventParam); if( (FALSE == eventDataRemovalProhibited) && (FALSE == obdProhibitsRemoval) ) { /* Check if priority if the event is higher or equal (low numerical value of priority means high priority..) *//* @req DEM383 */ eventPrio = getEventPriority(eventBuffer[i].EventData.eventId); eventPassive = getEventPassive(eventBuffer[i].EventData.eventId); if( (eventParam->EventClass->EventPriority <= eventPrio) && (TRUE == eventPassive) && (oldestPassive_TimeStamp > eventBuffer[i].EventData.timeStamp) ) { /* This event has lower or equal priority to the reported event, it is passive * and it is the oldest currently found. A candidate for removal. */ oldestPassive_TimeStamp = eventBuffer[i].EventData.timeStamp; removeCandidateIndex = i; passiveCandidateFound = TRUE; } if( FALSE == passiveCandidateFound ) { /* Currently, a passive event with lower or equal priority has not been found. * Check if the priority is less than for the reported event. Store the oldest. */ if( (eventParam->EventClass->EventPriority < eventPrio) && (oldestActive_TimeStamp > eventBuffer[i].EventData.timeStamp) ) { oldestActive_TimeStamp = eventBuffer[i].EventData.timeStamp; removeCandidateIndex = i; activeCandidateFound = TRUE; } } } } } if( (TRUE == passiveCandidateFound) || (TRUE == activeCandidateFound) ) { *eventToRemove = eventBuffer[removeCandidateIndex].EventData.eventId; ret = E_OK; } return ret; } #endif #endif /* DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL */ #if ( DEM_FF_DATA_IN_PRE_INIT ) static boolean lookupFreezeFrameForDisplacementPreInit(const Dem_EventParameterType *eventParam, FreezeFrameRecType **freezeFrame) { boolean freezeFrameFound = FALSE; Dem_EventIdType eventToRemove = DEM_EVENT_ID_NULL; #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) Dem_Extension_GetFFEventForDisplacement(eventParam, preInitFreezeFrameBuffer, DEM_MAX_NUMBER_FF_DATA_PRE_INIT, &eventToRemove); #elif defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) if( E_OK != getFFEventForDisplacement(eventParam, preInitFreezeFrameBuffer, DEM_MAX_NUMBER_FF_DATA_PRE_INIT, &eventToRemove) ) { eventToRemove = DEM_EVENT_ID_NULL; } #else #warning Unsupported displacement #endif if( DEM_EVENT_ID_NULL != eventToRemove ) { /* Freeze frame for a less significant event was found. * Find the all entries in pre init freeze frame buffer and remove these. */ for (uint16 indx = 0; (indx < DEM_MAX_NUMBER_FF_DATA_PRE_INIT); indx++) { if( preInitFreezeFrameBuffer[indx].eventId == eventToRemove ) { memset(&preInitFreezeFrameBuffer[indx], 0, sizeof(FreezeFrameRecType)); if( FALSE == freezeFrameFound ) { *freezeFrame = &preInitFreezeFrameBuffer[indx]; freezeFrameFound = TRUE; } } } #if defined(USE_DEM_EXTENSION) if( TRUE == freezeFrameFound ) { Dem_Extension_EventFreezeFrameDataDisplaced(eventToRemove); } #endif } else { /* Buffer is full and the currently stored data is more significant */ } return freezeFrameFound; } #endif #ifdef DEM_USE_MEMORY_FUNCTIONS #if ( DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM || DEM_FF_DATA_IN_PRE_INIT) static boolean lookupFreezeFrameForDisplacement(const Dem_EventParameterType *eventParam, FreezeFrameRecType **freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize) { boolean freezeFrameFound = FALSE; Dem_EventIdType eventToRemove = DEM_EVENT_ID_NULL; const Dem_EventParameterType *eventToRemoveParam = NULL; #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) Dem_Extension_GetFFEventForDisplacement(eventParam, freezeFrameBuffer, freezeFrameBufferSize, &eventToRemove); #elif defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) if( E_OK != getFFEventForDisplacement(eventParam, freezeFrameBuffer, freezeFrameBufferSize, &eventToRemove) ) { eventToRemove = DEM_EVENT_ID_NULL; } #else #warning Unsupported displacement #endif if( DEM_EVENT_ID_NULL != eventToRemove ) { /* Freeze frame for a less significant event was found. * Find the all entries in freeze frame buffer and remove these. */ for (uint16 indx = 0; (indx < freezeFrameBufferSize); indx++) { if( freezeFrameBuffer[indx].eventId == eventToRemove ) { memset(&freezeFrameBuffer[indx], 0, sizeof(FreezeFrameRecType)); if( FALSE == freezeFrameFound ) { *freezeFrame = &freezeFrameBuffer[indx]; freezeFrameFound = TRUE; } } } #if defined(USE_DEM_EXTENSION) if( TRUE == freezeFrameFound ) { Dem_Extension_EventFreezeFrameDataDisplaced(eventToRemove); } #endif if( TRUE == freezeFrameFound ) { lookupEventIdParameter(eventToRemove, &eventToRemoveParam); /* @req DEM475 */ notifyEventDataChanged(eventToRemoveParam); } } else { /* Buffer is full and the currently stored data is more significant */ } return freezeFrameFound; } #endif /* DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM || DEM_FF_DATA_IN_PRE_INIT */ #endif /* USE_MEMORY_FUNCTIONS */ #endif /* DEM_EVENT_DISPLACEMENT_SUPPORT */ static Std_ReturnType getNofStoredNonOBDFreezeFrames(const Dem_EventParameterType *eventParam, Dem_DTCOriginType origin, uint8 *nofStored) { uint8 nofFound = 0; const FreezeFrameRecType *ffBufferPtr = NULL; uint8 bufferSize = 0; if( DEM_INITIALIZED == demState ) { #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) if (origin == DEM_DTC_ORIGIN_PRIMARY_MEMORY) { ffBufferPtr = &priMemFreezeFrameBuffer[0]; bufferSize = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; } #endif #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) if (origin == DEM_DTC_ORIGIN_SECONDARY_MEMORY) { ffBufferPtr = &secMemFreezeFrameBuffer[0]; bufferSize = DEM_MAX_NUMBER_FF_DATA_SEC_MEM; } #endif #if !((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) && \ !((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) /* Avoid compiler warning when no FF is used */ (void)origin; #endif } else { #if ( DEM_FF_DATA_IN_PRE_INIT ) ffBufferPtr = &preInitFreezeFrameBuffer[0]; bufferSize = DEM_MAX_NUMBER_FF_DATA_PRE_INIT; #endif } Dem_EventIdType idToFind; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else idToFind = eventParam->EventID; #endif for( uint8 i = 0; (i < bufferSize) && (ffBufferPtr != NULL); i++) { if((ffBufferPtr[i].eventId == idToFind) && (DEM_FREEZE_FRAME_NON_OBD == ffBufferPtr[i].kind)) { nofFound++; } } *nofStored = nofFound; return E_OK; } #if (DEM_USE_TIMESTAMPS == STD_ON) #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) || \ ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) || \ (DEM_FF_DATA_IN_PRE_INIT) static void setFreezeFrameTimeStamp(FreezeFrameRecType *freezeFrame) { if( DEM_INITIALIZED == demState ) { if(FF_TimeStamp >= DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT){ rearrangeFreezeFrameTimeStamp(&FF_TimeStamp); } freezeFrame->timeStamp = FF_TimeStamp; FF_TimeStamp++; } else { freezeFrame->timeStamp = FF_TimeStamp; if( FF_TimeStamp < DEM_MAX_TIMESTAMP_FOR_PRE_INIT ) { FF_TimeStamp++; } } } #endif #endif static void getFFClassReference(const Dem_EventParameterType *eventParam, Dem_FreezeFrameClassType **ffClassTypeRef) { Dem_FreezeFrameClassTypeRefIndex ffIdx = getFFIdx(eventParam); if ((ffIdx != DEM_FF_NULLREF) ) { *ffClassTypeRef = (Dem_FreezeFrameClassType *) &(configSet->GlobalFreezeFrameClassRef[ffIdx]); } } #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) || \ ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) || \ (DEM_FF_DATA_IN_PRE_INIT) /* * Procedure: getPidData * Description: get OBD FF data,only called by getFreezeFrameData() */ static void getPidData(const Dem_PidOrDidType *const *const *pidClassPtr, FreezeFrameRecType *const *freezeFrame, uint16 *storeIndexPtr) { uint16 storeIndex = 0; #if (DEM_MAX_NR_OF_PIDS_IN_FREEZEFRAME_DATA > 0) const Dem_PidOrDidType *const *FFIdClassRef; Std_ReturnType callbackReturnCode; uint16 recordSize = 0u; boolean detError = FALSE; FFIdClassRef = *pidClassPtr; //get all pids for (uint16 i = 0; ((i < DEM_MAX_NR_OF_PIDS_IN_FREEZEFRAME_DATA) && (FALSE == FFIdClassRef[i]->Arc_EOL) && (FALSE == detError)); i++) { //get pid length recordSize = FFIdClassRef[i]->PidOrDidSize; /* read out the pid data */ if ((storeIndex + recordSize + DEM_PID_IDENTIFIER_SIZE_OF_BYTES) <= DEM_MAX_SIZE_FF_DATA) { /* store PID */ (*freezeFrame)->data[storeIndex] = FFIdClassRef[i]->PidIdentifier; storeIndex++; /* store data */ if(FFIdClassRef[i]->PidReadFnc != NULL){ callbackReturnCode = FFIdClassRef[i]->PidReadFnc(&(*freezeFrame)->data[storeIndex]); if (callbackReturnCode != E_OK) { memset(&(*freezeFrame)->data[storeIndex], DEM_FREEZEFRAME_DEFAULT_VALUE, (size_t)recordSize); DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GET_FREEZEFRAME_ID, DEM_E_NODATAAVAILABLE); } storeIndex += recordSize; } else { memset(&(*freezeFrame)->data[storeIndex], DEM_FREEZEFRAME_DEFAULT_VALUE, (size_t)recordSize); storeIndex += recordSize; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GET_FREEZEFRAME_ID, DEM_E_FF_TOO_BIG); detError = TRUE;/* Will break the loop */ } } #else (void)pidClassPtr;/*lint !e920*/ (void)freezeFrame;/*lint !e920*/ #endif //store storeIndex,it will be used for judge whether FF contains valid data. *storeIndexPtr = storeIndex; } /* * Procedure: getDidData * Description: get UDS FF data,only called by getFreezeFrameData() */ static void getDidData(const Dem_PidOrDidType *const *const *didClassPtr, FreezeFrameRecType *const *freezeFrame, uint16 *storeIndexPtr) { const Dem_PidOrDidType *const *FFIdClassRef; Std_ReturnType callbackReturnCode; uint16 storeIndex = 0u; uint16 recordSize = 0u; boolean detError = FALSE; FFIdClassRef = *didClassPtr; //get all dids for (uint16 i = 0u; ((i < DEM_MAX_NR_OF_DIDS_IN_FREEZEFRAME_DATA) && (FALSE == FFIdClassRef[i]->Arc_EOL) && (FALSE == detError)); i++) { recordSize = FFIdClassRef[i]->PidOrDidSize; /* read out the did data */ if ((storeIndex + recordSize + DEM_DID_IDENTIFIER_SIZE_OF_BYTES) <= DEM_MAX_SIZE_FF_DATA) { /* store DID */ (*freezeFrame)->data[storeIndex] = (uint8)(FFIdClassRef[i]->DidIdentifier>> 8u) & 0xFFu; storeIndex++; (*freezeFrame)->data[storeIndex] = (uint8)(FFIdClassRef[i]->DidIdentifier & 0xFFu); storeIndex++; /* store data */ if(FFIdClassRef[i]->DidReadFnc!= NULL) { callbackReturnCode = FFIdClassRef[i]->DidReadFnc(&(*freezeFrame)->data[storeIndex]); if (callbackReturnCode != E_OK) { /* @req DEM463 */ memset(&(*freezeFrame)->data[storeIndex], DEM_FREEZEFRAME_DEFAULT_VALUE, (size_t)recordSize); DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GET_FREEZEFRAME_ID, DEM_E_NODATAAVAILABLE); } storeIndex += recordSize; } else { memset(&(*freezeFrame)->data[storeIndex], DEM_FREEZEFRAME_DEFAULT_VALUE, (size_t)recordSize); storeIndex += recordSize; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GET_FREEZEFRAME_ID, DEM_E_FF_TOO_BIG); detError = TRUE;/* Will break the loop */ } } //store storeIndex,it will be used for judge whether FF contains valid data. *storeIndexPtr = storeIndex; } static Std_ReturnType getNextFFRecordNumber(const Dem_EventParameterType *eventParam, uint8 *recNum, Dem_FreezeFrameKindType ffKind, Dem_DTCOriginType origin) { /* @req DEM574 */ Std_ReturnType ret = E_OK; uint8 nofStored = 0; uint8 maxNofRecords; const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClass; if( DEM_FREEZE_FRAME_NON_OBD == ffKind) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; maxNofRecords = CombDTCCfg->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = CombDTCCfg->FreezeFrameRecNumClassRef; } else { maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; } #else maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; #endif if( 0 != maxNofRecords ) { if( E_OK == getNofStoredNonOBDFreezeFrames(eventParam, origin, &nofStored) ) { /* Was ok! */ if( nofStored < maxNofRecords ) { *recNum = FreezeFrameRecNumClass->FreezeFrameRecordNumber[nofStored]; } else { /* @req DEM585 *//* All records stored so update the latest */ if( (0u == nofStored) || (maxNofRecords > 1u) ) { *recNum = FreezeFrameRecNumClass->FreezeFrameRecordNumber[maxNofRecords - 1]; } else { /* Event only has one record and it is already stored */ ret = E_NOT_OK; } } } } else { /* No freeze frames should be stored for this event */ ret = E_NOT_OK; } } else { /* Always record 0 for OBD freeze frames */ *recNum = 0;/* @req DEM291 */ } return ret; } #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) static boolean findPreStoredFreezeFrame(Dem_EventIdType eventId, Dem_FreezeFrameKindType ffKind, FreezeFrameRecType **freezeFrame) { boolean ffFound = FALSE; FreezeFrameRecType *freezeFrameBuffer = &memPreStoreFreezeFrameBuffer[0]; if (freezeFrameBuffer != NULL) { for (uint16 i = 0; (i < DEM_MAX_NUMBER_PRESTORED_FF) && (FALSE == ffFound); i++) { ffFound = ((freezeFrameBuffer[i].eventId == eventId) && (freezeFrameBuffer[i].kind == ffKind) )? TRUE: FALSE; if(TRUE == ffFound) { *freezeFrame = &freezeFrameBuffer[i]; } } } return ffFound; } #endif /* * Procedure: getFreezeFrameData * Description: get FF data according configuration */ static void getFreezeFrameData(const Dem_EventParameterType *eventParam, FreezeFrameRecType *freezeFrame, Dem_FreezeFrameKindType ffKind, Dem_DTCOriginType origin, boolean useCombinedID) { uint16 storeIndex = 0; Dem_FreezeFrameClassType *FreezeFrameLocalClass = NULL; #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) FreezeFrameRecType *preStoredFF = NULL; #endif boolean preStoredFFfound = FALSE; /* clear FF data record */ memset(freezeFrame, 0, sizeof(FreezeFrameRecType )); /* Find out the corresponding FF class */ Dem_FreezeFrameClassTypeRefIndex ffIdx = getFFIdx(eventParam); if( (DEM_FREEZE_FRAME_NON_OBD == ffKind) && (ffIdx != DEM_FF_NULLREF) ) { getFFClassReference(eventParam, &FreezeFrameLocalClass); } else if((DEM_FREEZE_FRAME_OBD == ffKind) && (NULL != configSet->GlobalOBDFreezeFrameClassRef)) { FreezeFrameLocalClass = (Dem_FreezeFrameClassType *) configSet->GlobalOBDFreezeFrameClassRef; } else { FreezeFrameLocalClass = NULL; } /* get the dids */ if(FreezeFrameLocalClass != NULL){ if(FreezeFrameLocalClass->FFIdClassRef != NULL){ if( DEM_FREEZE_FRAME_NON_OBD == ffKind ) { getDidData(&FreezeFrameLocalClass->FFIdClassRef, &freezeFrame, &storeIndex); } else if(DEM_FREEZE_FRAME_OBD == ffKind) { /* Get the pids */ getPidData(&FreezeFrameLocalClass->FFIdClassRef, &freezeFrame, &storeIndex); } else { /* IMPROVEMENT: Det error */ } } } else { /* create an empty FF */ freezeFrame->eventId = DEM_EVENT_ID_NULL; } #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) /* @req DEM464 */ if (eventParam->EventClass->FFPrestorageSupported == TRUE) { /* Look for pre-stored FF in pre-stored buffer */ if (findPreStoredFreezeFrame(eventParam->EventID, ffKind, (FreezeFrameRecType **) &preStoredFF) == TRUE) { if ( preStoredFF != NULL) { /* @req DEM465 */ /* Remove FF from preStored buffer */ memcpy(freezeFrame, preStoredFF, sizeof(FreezeFrameRecType)); memset(preStoredFF, 0, sizeof(FreezeFrameRecType )); Dem_NvM_SetPreStoreFreezeFrameBlockChanged(FALSE); preStoredFFfound = TRUE; } } } #endif if (preStoredFFfound == FALSE) { uint8 recNum = 0; /* Check if any data has been stored and that there is a record number */ if ( (storeIndex != 0) && (E_OK == getNextFFRecordNumber(eventParam, &recNum, ffKind, origin))) {/*lint !e9007 */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID) && (TRUE == useCombinedID) ) { freezeFrame->eventId = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { freezeFrame->eventId = eventParam->EventID; } #else freezeFrame->eventId = eventParam->EventID; #endif freezeFrame->dataSize = storeIndex; freezeFrame->recordNumber = recNum; freezeFrame->kind = ffKind; #if (DEM_USE_TIMESTAMPS == STD_ON) setFreezeFrameTimeStamp(freezeFrame); #endif } else { freezeFrame->eventId = DEM_EVENT_ID_NULL; freezeFrame->dataSize = storeIndex; } } #if !defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) (void)useCombinedID; #endif } #endif #if (defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) && DEM_FF_DATA_IN_PRE_INIT) static void deleteFreezeFrameDataPreInit(const Dem_EventParameterType *eventParam) { /* Delete all freeze frames */ for (uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRE_INIT; i++){ if(preInitFreezeFrameBuffer[i].eventId == eventParam->EventID) { memset(&preInitFreezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); } } } #endif /* * Procedure: storeFreezeFrameDataPreInit * Description: store FF in before preInitFreezeFrameBuffer DEM's full initialization */ #if ( DEM_FF_DATA_IN_PRE_INIT ) static void storeFreezeFrameDataPreInit(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *freezeFrame) { boolean eventIdFound = FALSE; boolean eventIdFreePositionFound=FALSE; uint16 i; /* Check if already stored */ Dem_EventIdType idToFind; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else idToFind = eventParam->EventID; #endif for (i = 0; (i < DEM_MAX_NUMBER_FF_DATA_PRE_INIT) && (FALSE == eventIdFound); i++) { if( DEM_FREEZE_FRAME_NON_OBD == freezeFrame->kind ) { eventIdFound = ( (preInitFreezeFrameBuffer[i].eventId == idToFind) && (preInitFreezeFrameBuffer[i].recordNumber == freezeFrame->recordNumber))? TRUE: FALSE; } else { eventIdFound = ((DEM_EVENT_ID_NULL != preInitFreezeFrameBuffer[i].eventId) && (DEM_FREEZE_FRAME_OBD == preInitFreezeFrameBuffer[i].kind))? TRUE: FALSE; } } if( TRUE == eventIdFound ) { /* Entry found. Overwrite if not an OBD freeze frame*/ if( DEM_FREEZE_FRAME_NON_OBD == preInitFreezeFrameBuffer[i-1].kind ) { /* overwrite existing */ memcpy(&preInitFreezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); } } else { /* lookup first free position */ for (i = 0; (i < DEM_MAX_NUMBER_FF_DATA_PRE_INIT) && (FALSE == eventIdFreePositionFound); i++) { if( preInitFreezeFrameBuffer[i].eventId == DEM_EVENT_ID_NULL ) { eventIdFreePositionFound = TRUE; } } if ( TRUE == eventIdFreePositionFound ) { memcpy(&preInitFreezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); } else { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) /* @req DEM400 */ /* @req DEM407 */ /* do displacement */ FreezeFrameRecType *freezeFrameLocal = NULL; if( TRUE == lookupFreezeFrameForDisplacementPreInit(eventParam, &freezeFrameLocal) ) { memcpy(freezeFrameLocal, freezeFrame, sizeof(FreezeFrameRecType)); } #else /* @req DEM402*/ /* Req is not the Det-error.. */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_FF_DATA_PRE_INIT_ID, DEM_E_PRE_INIT_FF_DATA_BUFF_FULL); #endif } } } #endif #ifdef DEM_USE_MEMORY_FUNCTIONS #if ( DEM_FF_DATA_IN_PRE_INIT ) static boolean isValidRecordNumber(const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClass, uint8 maxNumRecords, uint8 recordNumber) { boolean isValid = FALSE; if( NULL != FreezeFrameRecNumClass ) { for( uint8 i = 0; (i < maxNumRecords) && (FALSE == isValid); i++ ) { if( FreezeFrameRecNumClass->FreezeFrameRecordNumber[i] == recordNumber ) { isValid = TRUE; } } } return isValid; } #endif #if ( DEM_FF_DATA_IN_PRE_INIT ) /** * Transfers non-OBD freeze frame stored in pre-Init buffer to event destination * @param eventId * @param freezeFrameBuffer * @param freezeFrameBufferSize * @param eventHandled * @param origin * @param removeOldFFRecords * @return */ static boolean transferNonOBDFreezeFramesEvtMem(Dem_EventIdType eventId, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, boolean* eventHandled, Dem_DTCOriginType origin, boolean removeOldFFRecords) { /* Note: Don't touch the OBD freeze frame */ uint16 nofStoredMemory = 0u; uint16 nofStoredPreInit = 0u; uint16 nofFFToMove; const Dem_EventParameterType *eventParam; uint8 recordToFind; uint16 findRecordStartIndex = 0u; uint16 setRecordStartIndex = 0u; boolean memoryChanged = FALSE; boolean dataUpdated = FALSE; uint8 maxNofRecords; const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClass; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* Event id may be a combined id. */ if( IS_COMBINED_EVENT_ID(eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(eventId)]; maxNofRecords = CombDTCCfg->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = CombDTCCfg->FreezeFrameRecNumClassRef; /* Just grab the first event for this DTC. */ lookupEventIdParameter(CombDTCCfg->DTCClassRef->Events[0u], &eventParam); } else { lookupEventIdParameter(eventId, &eventParam); maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; } #else lookupEventIdParameter(eventId, &eventParam); maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; #endif /* Count the number of entries in destination memory for the event */ for( uint32 j = 0u; j < freezeFrameBufferSize; j++ ) { if( (eventId == freezeFrameBuffer[j].eventId) && (DEM_FREEZE_FRAME_NON_OBD == freezeFrameBuffer[j].kind)) { if( TRUE == isValidRecordNumber(FreezeFrameRecNumClass, maxNofRecords, freezeFrameBuffer[j].recordNumber) ) { if( TRUE == removeOldFFRecords) { /* We should remove the old records. Don't increment nofStoredMemory * since no records will be stored in the buffer after all have been cleared */ memset(&freezeFrameBuffer[j], 0, sizeof(FreezeFrameRecType)); memoryChanged = TRUE; } else { nofStoredMemory++; } } else { /* Invalid ff record number */ memset(&freezeFrameBuffer[j], 0, sizeof(FreezeFrameRecType)); memoryChanged = TRUE; } } } /* Count the number of entries in the pre init memory for the event */ for( uint16 k = 0; k < DEM_MAX_NUMBER_FF_DATA_PRE_INIT; k++ ) { if( (eventId == preInitFreezeFrameBuffer[k].eventId) && (DEM_FREEZE_FRAME_NON_OBD == preInitFreezeFrameBuffer[k].kind)) { nofStoredPreInit++; } } /* Find out the number of FF to transfer from preInit buffer to memory */ /* We can assume that we should transfer at least on record from the preInitBuffer * since we found this event in the preInit buffer*/ if( 0u == maxNofRecords) { nofFFToMove = 0u; } else if( maxNofRecords == nofStoredMemory ) { /* All records already stored in primary memory. Just update the last record */ nofFFToMove = 1u; findRecordStartIndex = nofStoredPreInit - 1u; setRecordStartIndex = maxNofRecords - 1u; } else if( maxNofRecords > nofStoredMemory ) { nofFFToMove = (uint16)(MIN(nofStoredPreInit, (uint16)(maxNofRecords - nofStoredMemory))); findRecordStartIndex = nofStoredPreInit - nofFFToMove; setRecordStartIndex = nofStoredMemory; } else { /* To many records stored in primary memory. And they are all valid records * as we check this. * IMPROVEMENT: How do we handle this? * For now, throw all records in buffer and store the ones * in the preinit buffer. */ for( uint32 i = 0u; i < freezeFrameBufferSize; i++ ) { if( (eventId == freezeFrameBuffer[i].eventId) && (DEM_FREEZE_FRAME_NON_OBD == freezeFrameBuffer[i].kind)) { memset(&freezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); } } DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_MEMORY_CORRUPT); nofFFToMove = nofStoredPreInit; findRecordStartIndex = 0u; setRecordStartIndex = 0u; } if( 0u != nofFFToMove) { boolean ffStored = FALSE; for( uint16 offset = 0u; offset < nofFFToMove; offset++ ) { recordToFind = FreezeFrameRecNumClass->FreezeFrameRecordNumber[findRecordStartIndex + offset]; ffStored = FALSE; for( uint16 indx = 0u; (indx < DEM_MAX_NUMBER_FF_DATA_PRE_INIT) && (FALSE == ffStored); indx++ ) { if( (preInitFreezeFrameBuffer[indx].eventId == eventId) && (preInitFreezeFrameBuffer[indx].recordNumber == recordToFind) && (DEM_FREEZE_FRAME_NON_OBD == preInitFreezeFrameBuffer[indx].kind) && (FALSE == eventHandled[indx]) ) { /* Found the record to update */ preInitFreezeFrameBuffer[indx].recordNumber = FreezeFrameRecNumClass->FreezeFrameRecordNumber[setRecordStartIndex + offset]; /* Store the freeze frame */ if( TRUE == storeFreezeFrameDataMem(eventParam, &preInitFreezeFrameBuffer[indx], freezeFrameBuffer, freezeFrameBufferSize, origin) ) { dataUpdated = TRUE; } /* Clear the event id in the preInit buffer */ eventHandled[indx] = TRUE; ffStored = TRUE; } } } if( nofFFToMove < nofStoredPreInit ) { /* Did not move all freeze frames from the preInit buffer. * Need to clear the remaining */ for( uint16 indx = 0u; indx < DEM_MAX_NUMBER_FF_DATA_PRE_INIT; indx++ ) { if( (preInitFreezeFrameBuffer[indx].eventId == eventId) && (DEM_FREEZE_FRAME_NON_OBD == preInitFreezeFrameBuffer[indx].kind) ) { eventHandled[indx] = TRUE; } } } } if( TRUE == dataUpdated ) { /* Use errorStatusChanged in eventsStatusBuffer to signal that the event data was updated */ EventStatusRecType *eventStatusRecPtr; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( NULL != eventStatusRecPtr ) { eventStatusRecPtr->errorStatusChanged = TRUE; } } return memoryChanged; } #endif #if ( DEM_FF_DATA_IN_PRE_INIT ) static void transferOBDFreezeFramesEvtMem(const FreezeFrameRecType *freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin) { const Dem_EventParameterType *eventParam; lookupEventIdParameter(freezeFrame->eventId, &eventParam); if (origin != DEM_DTC_ORIGIN_PRIMARY_MEMORY) { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_OBD_NOT_ALLOWED_IN_SEC_MEM); } else if( NULL != eventParam ) { /* Assuming that this function will not store the OBD freeze frame * if there already is one stored. */ if( TRUE == storeOBDFreezeFrameDataMem(eventParam, freezeFrame, freezeFrameBuffer, freezeFrameBufferSize, origin) ) { /* Use errorStatusChanged in eventsStatusBuffer to signal that the event data was updated */ EventStatusRecType *eventStatusRecPtr; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( NULL != eventStatusRecPtr ) { eventStatusRecPtr->errorStatusChanged = TRUE; } } } else { /* Bad origin and no config available.. */ } } #endif #if ( DEM_FF_DATA_IN_PRE_INIT ) static boolean transferPreInitFreezeFramesEvtMem(FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, EventRecType* eventBuffer, uint32 eventBufferSize, Dem_DTCOriginType origin) { boolean priMemChanged = FALSE; boolean removeOldFFRecords; boolean skipFF; const Dem_EventParameterType *eventParam; EventStatusRecType* eventStatusRec; boolean eventHandled[DEM_MAX_NUMBER_FF_DATA_PRE_INIT] = {FALSE}; Dem_DTCOriginType eventOrigin; Dem_EventStatusExtendedType eventStatus; for( uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRE_INIT; i++ ) { if( (DEM_EVENT_ID_NULL != preInitFreezeFrameBuffer[i].eventId) && (TRUE == checkEntryValid(preInitFreezeFrameBuffer[i].eventId, origin, TRUE)) ) { /* Check if this is a freeze frame which should be processed. * Ignore freeze frames for event not stored in memory or OBD * freeze frames for event which are not confirmed */ eventStatusRec = NULL; eventParam = NULL; skipFF = TRUE; eventOrigin = DEM_DTC_ORIGIN_NOT_USED;; eventStatus = 0xFFu;/* This combination of bits is invalid */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(preInitFreezeFrameBuffer[i].eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(preInitFreezeFrameBuffer[i].eventId)]; eventOrigin = CombDTCCfg->MemoryDestination; if( DEM_STATUS_OK != GetDTCUDSStatus(CombDTCCfg->DTCClassRef, origin, &eventStatus) ) { eventStatus = 0xFFu; } } else { lookupEventStatusRec(preInitFreezeFrameBuffer[i].eventId, &eventStatusRec); lookupEventIdParameter(preInitFreezeFrameBuffer[i].eventId, &eventParam); if( (NULL != eventStatusRec) && (NULL != eventParam) ) { eventOrigin = eventParam->EventClass->EventDestination; eventStatus = eventStatusRec->eventStatusExtended; } } #else lookupEventStatusRec(preInitFreezeFrameBuffer[i].eventId, &eventStatusRec); lookupEventIdParameter(preInitFreezeFrameBuffer[i].eventId, &eventParam); if( (NULL != eventStatusRec) && (NULL != eventParam) ) { eventOrigin = eventParam->EventClass->EventDestination; eventStatus = eventStatusRec->eventStatusExtended; } #endif if( (DEM_DTC_ORIGIN_NOT_USED != eventOrigin) && (0xFFu != eventStatus) ) { skipFF = FALSE; if( origin == eventOrigin ) { if( (FALSE == eventIsStoredInMem(preInitFreezeFrameBuffer[i].eventId, eventBuffer, eventBufferSize)) || ((DEM_FREEZE_FRAME_OBD == preInitFreezeFrameBuffer[i].kind) && (0u == (eventStatus & DEM_CONFIRMED_DTC))) ) { /* Event is not stored or FF is OBD and event is not confirmed. Skip FF */ skipFF = TRUE; } } } if( FALSE == skipFF ) { removeOldFFRecords = FALSE; #if defined(USE_DEM_EXTENSION) Dem_Extension_PreTransferPreInitFreezeFrames(preInitFreezeFrameBuffer[i].eventId, &removeOldFFRecords, origin); #endif if( DEM_FREEZE_FRAME_NON_OBD == preInitFreezeFrameBuffer[i].kind ) { if (TRUE == transferNonOBDFreezeFramesEvtMem(preInitFreezeFrameBuffer[i].eventId, freezeFrameBuffer, freezeFrameBufferSize, eventHandled, origin, removeOldFFRecords)) { priMemChanged = TRUE; } } else { transferOBDFreezeFramesEvtMem(&preInitFreezeFrameBuffer[i], freezeFrameBuffer, freezeFrameBufferSize, origin); } } } } return priMemChanged; } #endif #endif /* DEM_USE_MEMORY_FUNCTIONS */ #if (DEM_USE_TIMESTAMPS == STD_ON) static void setExtDataTimeStamp(ExtDataRecType *extData) { if( DEM_INITIALIZED == demState ) { if(ExtData_TimeStamp >= DEM_MAX_TIMESTAMP_FOR_REARRANGEMENT){ rearrangeExtDataTimeStamp(&ExtData_TimeStamp); } extData->timeStamp = ExtData_TimeStamp; ExtData_TimeStamp++; } else { extData->timeStamp = ExtData_TimeStamp; if( ExtData_TimeStamp < DEM_MAX_TIMESTAMP_FOR_PRE_INIT ) { ExtData_TimeStamp++; } } } #endif #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && (DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) static Std_ReturnType lookupExtDataForDisplacement(const Dem_EventParameterType *eventParam, ExtDataRecType *extDataBufPtr, uint32 bufferSize, ExtDataRecType **extData ) { const Dem_EventParameterType *eventToRemoveParam = NULL; Std_ReturnType ret = E_NOT_OK; /* @req DEM400 */ Dem_EventIdType eventToRemove = DEM_EVENT_ID_NULL; #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) Dem_Extension_GetExtDataEventForDisplacement(eventParam, extDataBufPtr, bufferSize, &eventToRemove); #elif defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) if( E_OK != getExtDataEventForDisplacement(eventParam, extDataBufPtr, bufferSize, &eventToRemove) ) { eventToRemove = DEM_EVENT_ID_NULL; } #else #warning Unsupported displacement #endif if( DEM_EVENT_ID_NULL != eventToRemove ) { /* Extended data for a less significant event was found. * Find the entry in ext data buffer. */ for (uint32 indx = 0; (indx < bufferSize) && (E_OK != ret); indx++) { if( extDataBufPtr[indx].eventId == eventToRemove ) { memset(&extDataBufPtr[indx], 0, sizeof(ExtDataRecType)); *extData = &extDataBufPtr[indx]; ret = E_OK; #if defined(USE_DEM_EXTENSION) Dem_Extension_EventExtendedDataDisplaced(eventToRemove); #endif lookupEventIdParameter(eventToRemove, &eventToRemoveParam); /* @req DEM475 */ notifyEventDataChanged(eventToRemoveParam); } } } else { /* Buffer is full and the currently stored data is more significant *//* @req DEM407 */ } return ret; } #endif /* (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && (DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) */ #if ( DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM ) && defined(DEM_USE_MEMORY_FUNCTIONS) static boolean StoreExtDataInMem( const Dem_EventParameterType *eventParam, ExtDataRecType *extDataMem, uint16 bufferSize, Dem_DTCOriginType origin, boolean overrideOldData) { uint16 storeIndex = 0; uint16 recordSize; const Dem_ExtendedDataRecordClassType *extendedDataRecord; const Dem_ExtendedDataClassType *ExtendedDataClass; ExtDataRecType *extData = NULL; boolean eventIdFound = FALSE; boolean bStoredData = FALSE; Dem_EventIdType idToFind; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); ExtendedDataClass = configSet->CombinedDTCConfig[eventParam->CombinedDTCCID].ExtendedDataClassRef; } else { idToFind = eventParam->EventID; ExtendedDataClass = eventParam->ExtendedDataClassRef; } #else idToFind = eventParam->EventID; ExtendedDataClass = eventParam->ExtendedDataClassRef; #endif // Check if already stored for (uint16 i = 0; (i < bufferSize) && (FALSE == eventIdFound); i++){ eventIdFound = (extDataMem[i].eventId == idToFind)? TRUE: FALSE; extData = &extDataMem[i]; } if( FALSE == eventIdFound ) { extData = NULL; for (uint16 i = 0; (i < bufferSize) && (NULL == extData); i++){ if( extDataMem[i].eventId == DEM_EVENT_ID_NULL ) { extData = &extDataMem[i]; } } if( NULL == extData ) { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) /* @req DEM400 *//* @req DEM407 */ if( E_OK != lookupExtDataForDisplacement(eventParam, extDataMem, bufferSize, &extData) ) { setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); return FALSE; } #else /* @req DEM402*//* Displacement supported disabled */ setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_EXT_DATA_MEM_ID, DEM_E_MEM_EXT_DATA_BUFF_FULL); return FALSE; #endif /* DEM_EVENT_DISPLACEMENT_SUPPORT */ } } // Check if any pointer to extended data class if ( (NULL != extData) && (ExtendedDataClass != NULL) ) { // Request extended data and copy it to the buffer for (uint32 i = 0uL; (i < DEM_MAX_NR_OF_RECORDS_IN_EXTENDED_DATA) && (ExtendedDataClass->ExtendedDataRecordClassRef[i] != NULL); i++) { extendedDataRecord = ExtendedDataClass->ExtendedDataRecordClassRef[i]; if( DEM_UPDATE_RECORD_VOLATILE != extendedDataRecord->UpdateRule ) { recordSize = extendedDataRecord->DataSize; if ((storeIndex + recordSize) <= DEM_MAX_SIZE_EXT_DATA) { if( (DEM_UPDATE_RECORD_YES == extendedDataRecord->UpdateRule) || ((DEM_UPDATE_RECORD_NO == extendedDataRecord->UpdateRule) && (extData->eventId != eventParam->EventID)) || (TRUE == overrideOldData)) { /* Either update rule YES, or update rule is NO and extended data was not previously stored for this event */ if( NULL != extendedDataRecord->CallbackGetExtDataRecord ) { /** @req DEM282 */ if (E_OK != extendedDataRecord->CallbackGetExtDataRecord(&extData->data[storeIndex])) { // Callback data currently not available, clear space. memset(&extData->data[storeIndex], 0xFF, (size_t)recordSize); } bStoredData = TRUE; } else if( DEM_NO_ELEMENT != extendedDataRecord->InternalDataElement ) { getInternalElement( eventParam, extendedDataRecord->InternalDataElement, &extData->data[storeIndex], extendedDataRecord->DataSize ); bStoredData = TRUE; } else { /* No callback and not internal element.. * IMPROVMENT: Det error */ } } else { /* Should not update */ } storeIndex += recordSize; } else { // Error: Size of extended data record is bigger than reserved space. DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GET_EXTENDED_DATA_ID, DEM_E_EXT_DATA_TOO_BIG); break; // Break the loop } } } } // Check if any data has been stored if ( (NULL != extData) && (TRUE == bStoredData) ) { extData->eventId = idToFind; #if (DEM_USE_TIMESTAMPS == STD_ON) setExtDataTimeStamp(extData); #endif #ifdef DEM_USE_MEMORY_FUNCTIONS if( DEM_PREINITIALIZED != demState ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; EventStatusRecType *eventStatusRecPtr = NULL; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( (NULL != eventStatusRecPtr) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRecPtr->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } Dem_NvM_SetExtendedDataBlockChanged(origin, immediateStorage); #else Dem_NvM_SetExtendedDataBlockChanged(origin, FALSE); #endif } #endif } return bStoredData; } #endif /* DEM_EXT_DATA_IN_PRE_INIT || DEM_EXT_DATA_IN_PRI_MEM || DEM_EXT_DATA_IN_SEC_MEM */ /* * Procedure: getExtendedData * Description: Collects the extended data according to "eventParam" and return it in "extData", * if not found eventId is set to DEM_EVENT_ID_NULL. */ static boolean storeExtendedData(const Dem_EventParameterType *eventParam, boolean overrideOldData) { boolean ret = FALSE; if( DEM_PREINITIALIZED == demState ) { #if ( DEM_EXT_DATA_IN_PRE_INIT ) (void)StoreExtDataInMem(eventParam, preInitExtDataBuffer, DEM_MAX_NUMBER_EXT_DATA_PRE_INIT, DEM_DTC_ORIGIN_NOT_USED, overrideOldData);/* @req DEM468 */ #endif } else { switch (eventParam->EventClass->EventDestination) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_PRI_MEM) ret = StoreExtDataInMem(eventParam, priMemExtDataBuffer, DEM_MAX_NUMBER_EXT_DATA_PRI_MEM, DEM_DTC_ORIGIN_PRIMARY_MEMORY, overrideOldData);/* @req DEM468 */ #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_SEC_MEM) ret = StoreExtDataInMem(eventParam, secMemExtDataBuffer, DEM_MAX_NUMBER_EXT_DATA_SEC_MEM, DEM_DTC_ORIGIN_SECONDARY_MEMORY, overrideOldData);/* @req DEM468 */ #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: break; } } return ret; } #ifdef DEM_USE_MEMORY_FUNCTIONS #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) static Std_ReturnType findAndDisplaceEvent(const Dem_EventParameterType *eventParam, EventRecType *eventBuffer, uint32 bufferSize, EventRecType **memEventStatusRec, Dem_DTCOriginType origin) { Std_ReturnType ret = E_NOT_OK; for (uint32 i = 0; (i < bufferSize) && (E_OK != ret); i++) { if( eventBuffer[i].EventData.eventId == eventParam->EventID ) { memset(&eventBuffer[i].EventData, 0, sizeof(EventRecType)); *memEventStatusRec = &eventBuffer[i]; ret = E_OK; #if defined(USE_DEM_EXTENSION) Dem_Extension_EventDataDisplaced(eventParam->EventID); #endif } } /* Reset it */ EventStatusRecType *eventStatusRecPtr; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( NULL != eventStatusRecPtr ) { Dem_EventStatusExtendedType oldStatus = eventStatusRecPtr->eventStatusExtended; /* @req DEM409 *//* @req DEM538 */ eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)(~DEM_CONFIRMED_DTC); #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->failureCounter = 0; eventStatusRecPtr->failedDuringFailureCycle = FALSE; eventStatusRecPtr->passedDuringFailureCycle = FALSE; #endif #if defined(DEM_aging_PROCESSING_DEM_INTERNAL) eventStatusRecPtr->agingCounter = 0; eventStatusRecPtr->failedDuringAgingCycle = FALSE; eventStatusRecPtr->passedDuringAgingCycle = FALSE; #endif if( oldStatus != eventStatusRecPtr->eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventParam, oldStatus, eventStatusRecPtr->eventStatusExtended); } } /* Remove all event related data */ /* @req DEM408 */ /* @req DEM542 */ boolean combinedDTC = FALSE; const Dem_ExtendedDataClassType *ExtendedDataClass; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { ExtendedDataClass = configSet->CombinedDTCConfig[eventParam->CombinedDTCCID].ExtendedDataClassRef; combinedDTC = TRUE; } else { ExtendedDataClass = eventParam->ExtendedDataClassRef; } #else ExtendedDataClass = eventParam->ExtendedDataClassRef; #endif if( DEM_FF_NULLREF != getFFIdx(eventParam) ) { (void)deleteFreezeFrameDataMem(eventParam, origin, combinedDTC); } if( NULL_PTR != ExtendedDataClass ) { (void)deleteExtendedDataMem(eventParam, origin, combinedDTC); } #if defined(DEM_USE_INDICATORS) if( TRUE == resetIndicatorCounters(eventParam) ) { #ifdef DEM_USE_MEMORY_FUNCTIONS /* IPROVEMENT: Immediate storage when deleting events? */ Dem_NvM_SetIndicatorBlockChanged(FALSE); #endif } #endif /* @req DEM475 */ notifyEventDataChanged(eventParam); return ret; } Std_ReturnType lookupEventForDisplacement(const Dem_EventParameterType *eventParam, EventRecType *eventBuffer, uint32 bufferSize, EventRecType **memEventStatusRec, Dem_DTCOriginType origin) { Std_ReturnType ret = E_NOT_OK; Dem_EventIdType eventToRemove = DEM_EVENT_ID_NULL; /* No free position found. See if any of the stored events may be removed */ #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) Dem_Extension_GetEventForDisplacement(eventParam, eventBuffer, bufferSize, &eventToRemove); #elif defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) if( E_OK != getEventForDisplacement(eventParam, eventBuffer, bufferSize, &eventToRemove) ) { eventToRemove = DEM_EVENT_ID_NULL; } #else #warning Unsupported displacement #endif if( DEM_EVENT_ID_NULL != eventToRemove ) { const Dem_EventParameterType *removeEventParam = NULL; lookupEventIdParameter(eventToRemove, &removeEventParam); if( NULL != removeEventParam ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) const Dem_DTCClassType *DTCClass = removeEventParam->DTCClassRef; if( NULL_PTR != DTCClass ) { /* @req DEM443 */ for(uint16 evIdx = 0; evIdx < DTCClass->NofEvents; evIdx++) { removeEventParam = NULL; lookupEventIdParameter(DTCClass->Events[evIdx], &removeEventParam); if( NULL != removeEventParam ) { if( E_OK == findAndDisplaceEvent(removeEventParam, eventBuffer, bufferSize, memEventStatusRec, origin) ) { ret = E_OK; } } } } else { ret = findAndDisplaceEvent(removeEventParam, eventBuffer, bufferSize, memEventStatusRec, origin); } #else ret = findAndDisplaceEvent(removeEventParam, eventBuffer, bufferSize, memEventStatusRec, origin); #endif /* DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1 */ } } else { /* Buffer is full and the currently stored data is more significant */ } return ret; } #endif /* * Procedure: storeEventMem * Description: Store the event data of "eventStatus->eventId" in eventBuffer (i.e.primary or secondary memory), * if non existent a new entry is created. */ static Std_ReturnType storeEventMem(const Dem_EventParameterType *eventParam, const EventStatusRecType *eventStatus, EventRecType* buffer, uint32 bufferSize, Dem_DTCOriginType origin, boolean failedNow) { boolean positionFound = FALSE; EventRecType *eventStatusRec = NULL; Std_ReturnType ret = E_OK; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; #endif // Lookup event ID for (uint32 i = 0uL; (i < bufferSize) && (FALSE == positionFound); i++){ if( buffer[i].EventData.eventId == eventStatus->eventId ) { eventStatusRec = &buffer[i]; positionFound = TRUE; } } if( FALSE == positionFound ) { /* Event is not already stored, Search for free position */ for (uint32 i = 0uL; (i < bufferSize) && (FALSE == positionFound); i++){ if( buffer[i].EventData.eventId == DEM_EVENT_ID_NULL ) { eventStatusRec = &buffer[i]; positionFound = TRUE; } } if( FALSE == positionFound ) { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) /* @req DEM400 *//* @req DEM407 */ if( E_OK == lookupEventForDisplacement(eventParam, buffer, bufferSize, &eventStatusRec, origin) ) { positionFound = TRUE; } else { setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); } #else /* @req DEM402*/ /* No displacement should be done */ setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); #endif /* DEM_EVENT_DISPLACEMENT_SUPPORT */ } } if ((TRUE == positionFound) && (NULL != eventStatusRec)) { // Update event found eventStatusRec->EventData.eventId = eventStatus->eventId; eventStatusRec->EventData.occurrence = eventStatus->occurrence; eventStatusRec->EventData.eventStatusExtended = eventStatus->eventStatusExtended; #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) eventStatusRec->EventData.failureCounter = eventStatus->failureCounter; #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) eventStatusRec->EventData.agingCounter = eventStatus->agingCounter; #endif #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) eventStatusRec->EventData.timeStamp = eventStatus->timeStamp; #endif #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (TRUE == failedNow) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatus->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } Dem_NvM_SetEventBlockChanged(origin, immediateStorage); #else (void)failedNow;/* Only used for immediate storage */ Dem_NvM_SetEventBlockChanged(origin, FALSE); #endif } else { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) /* Error: mem event buffer full */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_EVENT_MEM_ID, DEM_E_MEM_EVENT_BUFF_FULL); #endif /* Buffer is full and all stored events are more significant */ ret = E_NOT_OK; } return ret; } /* * Procedure: deleteEventMem * Description: Delete the event data of "eventParam->eventId" from event buffer". */ static boolean deleteEventMem(const Dem_EventParameterType *eventParam, EventRecType* eventMemory, uint32 eventMemorySize, Dem_DTCOriginType origin) { boolean eventIdFound = FALSE; uint32 i; for (i = 0uL; (i < eventMemorySize) && (FALSE == eventIdFound); i++){ eventIdFound = (eventMemory[i].EventData.eventId == eventParam->EventID)? TRUE: FALSE; } if (TRUE == eventIdFound) { memset(&eventMemory[i-1], 0, sizeof(EventRecType)); /* IMPROVEMENT: Immediate storage when delecting event? */ Dem_NvM_SetEventBlockChanged(origin, FALSE); } return eventIdFound; } #endif /* DEM_USE_MEMORY_FUNCTIONS */ /** * Deletes DTC data i.e. event data, ff data and extended data for an event. * @param eventParam - the event which data shall be deleted for * @param dtcOriginFound - TRUE if origin found otherwise FALSE * @return TRUE if any data deleted otherwise FALSE */ static boolean DeleteDTCData(const Dem_EventParameterType *eventParam, boolean resetEventstatus, boolean *dtcOriginFound, boolean combinedDTC) { boolean dataDeleted = FALSE; switch (eventParam->EventClass->EventDestination) { #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) case DEM_DTC_ORIGIN_PRIMARY_MEMORY: /** @req DEM077 */ if( TRUE == deleteEventMem(eventParam, priMemEventBuffer, DEM_MAX_NUMBER_EVENT_PRI_MEM, DEM_DTC_ORIGIN_PRIMARY_MEMORY) ) { dataDeleted = TRUE; } if( TRUE == deleteFreezeFrameDataMem(eventParam, DEM_DTC_ORIGIN_PRIMARY_MEMORY, combinedDTC) ) { dataDeleted = TRUE; } if( TRUE == deleteExtendedDataMem(eventParam, DEM_DTC_ORIGIN_PRIMARY_MEMORY, combinedDTC) ) { dataDeleted = TRUE; } if( TRUE == resetEventstatus ) { resetEventStatusRec(eventParam); } *dtcOriginFound = TRUE; break; #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) case DEM_DTC_ORIGIN_SECONDARY_MEMORY: if( TRUE == deleteEventMem(eventParam, secMemEventBuffer, DEM_MAX_NUMBER_EVENT_SEC_MEM, DEM_DTC_ORIGIN_SECONDARY_MEMORY) ) { dataDeleted = TRUE; } if( TRUE == deleteFreezeFrameDataMem(eventParam, DEM_DTC_ORIGIN_SECONDARY_MEMORY, combinedDTC) ) { dataDeleted = TRUE; } if( TRUE == deleteExtendedDataMem(eventParam, DEM_DTC_ORIGIN_SECONDARY_MEMORY, combinedDTC) ) { dataDeleted = TRUE; } if( TRUE == resetEventstatus ) { resetEventStatusRec(eventParam); } *dtcOriginFound = TRUE; break; #endif default: *dtcOriginFound = FALSE; break; } return dataDeleted; } #if defined(DEM_USE_MEMORY_FUNCTIONS) /** * Checks if an event is stored in its event destination * @param eventParam * @return TRUE: Event is stored in event memory, FALSE: Event not stored in event memory */ static boolean isInEventMemory(const Dem_EventParameterType *eventParam) { boolean found = FALSE; uint16 memSize = 0; const EventRecType *mem = NULL; switch (eventParam->EventClass->EventDestination) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) mem = priMemEventBuffer; memSize = DEM_MAX_NUMBER_EVENT_ENTRY_PRI; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) mem = secMemEventBuffer; memSize = DEM_MAX_NUMBER_EVENT_ENTRY_SEC; #endif break; default: break; } if( NULL != mem ) { for(uint16 i = 0; (i < memSize) && (FALSE == found); i++) { if( eventParam->EventID == mem[i].EventData.eventId ) { found = TRUE; } } } return found; } #endif /* * Procedure: storeEventEvtMem * Description: Store the event data of "eventStatus->eventId" in event memory according to * "eventParam" destination option. */ static Std_ReturnType storeEventEvtMem(const Dem_EventParameterType *eventParam, const EventStatusRecType *eventStatus, boolean failedNow) { Std_ReturnType ret = E_NOT_OK; switch (eventParam->EventClass->EventDestination) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) ret = storeEventMem(eventParam, eventStatus, priMemEventBuffer, DEM_MAX_NUMBER_EVENT_ENTRY_PRI, DEM_DTC_ORIGIN_PRIMARY_MEMORY, failedNow); /** @req DEM010 */ #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) ret = storeEventMem(eventParam, eventStatus, secMemEventBuffer, DEM_MAX_NUMBER_EVENT_ENTRY_SEC, DEM_DTC_ORIGIN_SECONDARY_MEMORY, failedNow); /** @req DEM548 */ #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: break; } return ret; } /* * Procedure: getExtendedDataMem * Description: Get record from buffer if it exists, or pick next free if it doesn't */ #ifdef DEM_USE_MEMORY_FUNCTIONS #if (DEM_EXT_DATA_IN_PRE_INIT ) static void getExtendedDataMem(const Dem_EventParameterType *eventParam, ExtDataRecType ** const extendedData, ExtDataRecType* extendedDataBuffer, uint32 extendedDataBufferSize) /** @req DEM041 */ { boolean eventIdFound = FALSE; boolean eventIdFreePositionFound=FALSE; uint16 i; Dem_EventIdType idToFind; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else idToFind = eventParam->EventID; #endif // Check if already stored for (i = 0; (i < extendedDataBufferSize) && (FALSE == eventIdFound); i++){ if( extendedDataBuffer[i].eventId == idToFind ) { *extendedData = &extendedDataBuffer[i]; eventIdFound = TRUE; } } if ( FALSE == eventIdFound ) { // No, lookup first free position for (i = 0; (i < extendedDataBufferSize) && (FALSE == eventIdFreePositionFound); i++){ eventIdFreePositionFound = (extendedDataBuffer[i].eventId == DEM_EVENT_ID_NULL); } if ( TRUE == eventIdFreePositionFound ) { *extendedData = &extendedDataBuffer[i-1]; } else { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) if(E_OK != lookupExtDataForDisplacement(eventParam, extendedDataBuffer, extendedDataBufferSize, extendedData)) { *extendedData = NULL; } #else /* Displacement supported disabled */ /* Error: mem extended data buffer full */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_EXT_DATA_MEM_ID, DEM_E_MEM_EXT_DATA_BUFF_FULL); #endif /* DEM_EVENT_DISPLACEMENT_SUPPORT */ } } } #endif /* * Procedure: deleteExtendedDataMem * Description: Delete the extended data of "eventParam->eventId" from "priMemExtDataBuffer". */ static boolean deleteExtendedDataMem(const Dem_EventParameterType *eventParam, Dem_DTCOriginType origin, boolean combinedDTC) { boolean eventIdFound = FALSE; uint32 i; ExtDataRecType* extBuffer = NULL; uint32 bufferSize = 0; Dem_EventIdType idToFind; switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_PRI_MEM) extBuffer = priMemExtDataBuffer; bufferSize = DEM_MAX_NUMBER_EXT_DATA_PRI_MEM; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_SEC_MEM) extBuffer = secMemExtDataBuffer; bufferSize = DEM_MAX_NUMBER_EXT_DATA_SEC_MEM; #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: break; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (TRUE == combinedDTC) && (DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID) ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else (void)combinedDTC; idToFind = eventParam->EventID; #endif if( NULL != extBuffer ) { // Check if already stored for (i = 0uL; (i < bufferSize) && (FALSE == eventIdFound); i++){ eventIdFound = (extBuffer[i].eventId == idToFind)? TRUE: FALSE; } if (TRUE == eventIdFound) { // Yes, clear record memset(&extBuffer[i-1], 0, sizeof(ExtDataRecType)); /* IMPROVEMENT: Immediate storage when deleting data? */ Dem_NvM_SetExtendedDataBlockChanged(origin, FALSE); } } return eventIdFound; } /* * Procedure: storeExtendedDataEvtMem * Description: Store the extended data in event memory according to * "eventParam" destination option */ #if ( DEM_EXT_DATA_IN_PRE_INIT ) static boolean mergeExtendedDataEvtMem(const ExtDataRecType *extendedData, ExtDataRecType* extendedDataBuffer, uint32 extendedDataBufferSize, Dem_DTCOriginType origin, boolean updateAllExtData) { uint16 i; const Dem_ExtendedDataRecordClassType *extendedDataRecordClass; ExtDataRecType *memExtDataRec = NULL; uint16 storeIndex = 0; boolean bCopiedData = FALSE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; #endif const Dem_EventParameterType *eventParam = NULL_PTR; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(extendedData->eventId) ) { /* This is a combined event entry. */ /* Get DTC config */ const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(extendedData->eventId)]; /* Just grab the first event for this DTC. */ lookupEventIdParameter(CombDTCCfg->DTCClassRef->Events[0u], &eventParam); } else { lookupEventIdParameter(extendedData->eventId, &eventParam); } #else lookupEventIdParameter(extendedData->eventId, &eventParam); #endif if( (NULL_PTR != eventParam) && (eventParam->EventClass->EventDestination == origin) ) { /* Management is only relevant for events stored in destinatio mem (i.e. nvram) */ getExtendedDataMem(eventParam, &memExtDataRec, extendedDataBuffer, extendedDataBufferSize); if( NULL != memExtDataRec ) { /* We found an old record or could allocate a new slot */ /* Only copy extended data related to event set during pre-init */ for(i = 0; (i < DEM_MAX_NR_OF_RECORDS_IN_EXTENDED_DATA) && (eventParam->ExtendedDataClassRef->ExtendedDataRecordClassRef[i] != NULL); i++) { extendedDataRecordClass = eventParam->ExtendedDataClassRef->ExtendedDataRecordClassRef[i]; if( DEM_UPDATE_RECORD_VOLATILE != extendedDataRecordClass->UpdateRule ) { if( DEM_UPDATE_RECORD_YES == extendedDataRecordClass->UpdateRule ) { /* Copy records that failed during pre init */ memcpy(&memExtDataRec->data[storeIndex], &extendedData->data[storeIndex],extendedDataRecordClass->DataSize); bCopiedData = TRUE; } else if( DEM_UPDATE_RECORD_NO == extendedDataRecordClass->UpdateRule ) { if( (eventParam->EventID != memExtDataRec->eventId) || (TRUE == updateAllExtData) ) { /* Extended data was not previously stored for this event. */ memcpy(&memExtDataRec->data[storeIndex], &extendedData->data[storeIndex],extendedDataRecordClass->DataSize); bCopiedData = TRUE; } } else { /* DET FEL */ } storeIndex += extendedDataRecordClass->DataSize; } } if( TRUE == bCopiedData ) { memExtDataRec->eventId = extendedData->eventId; #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) && defined(DEM_DISPLACEMENT_PROCESSING_DEM_INTERNAL) memExtDataRec->timeStamp = extendedData->timeStamp; #endif #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) EventStatusRecType *eventStatusRecPtr = NULL; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( (NULL != eventStatusRecPtr) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRecPtr->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } Dem_NvM_SetExtendedDataBlockChanged(origin, immediateStorage); #else Dem_NvM_SetExtendedDataBlockChanged(origin, FALSE); #endif } } else { /* DET FEL */ } } return bCopiedData; } #endif #endif /* DEM_USE_MEMORY_FUNCTIONS */ /* * Procedure: lookupExtendedDataRecNumParam * Description: Returns TRUE if the requested extended data number was found among the configured records for the event. * "extDataRecClassPtr" returns a pointer to the record class, "posInExtData" returns the position in stored extended data. */ static boolean lookupExtendedDataRecNumParam(uint8 extendedDataNumber, const Dem_EventParameterType *eventParam, Dem_ExtendedDataRecordClassType const **extDataRecClassPtr, uint16 *posInExtData) { boolean recNumFound = FALSE; const Dem_ExtendedDataClassType *ExtendedDataClass; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { ExtendedDataClass = configSet->CombinedDTCConfig[eventParam->CombinedDTCCID].ExtendedDataClassRef; } else { ExtendedDataClass = eventParam->ExtendedDataClassRef; } #else ExtendedDataClass = eventParam->ExtendedDataClassRef; #endif if (ExtendedDataClass != NULL) { uint16 byteCnt = 0; uint32 i; // Request extended data and copy it to the buffer for (i = 0uL; (i < DEM_MAX_NR_OF_RECORDS_IN_EXTENDED_DATA) && (ExtendedDataClass->ExtendedDataRecordClassRef[i] != NULL) && (recNumFound == FALSE); i++) { if (ExtendedDataClass->ExtendedDataRecordClassRef[i]->RecordNumber == extendedDataNumber) { *extDataRecClassPtr = ExtendedDataClass->ExtendedDataRecordClassRef[i]; *posInExtData = byteCnt; recNumFound = TRUE; } if(DEM_UPDATE_RECORD_VOLATILE != ExtendedDataClass->ExtendedDataRecordClassRef[i]->UpdateRule) { byteCnt += ExtendedDataClass->ExtendedDataRecordClassRef[i]->DataSize; } } } return recNumFound; } /* * Procedure: lookupExtendedDataMem * Description: Returns TRUE if the requested event id is found, "extData" points to the found data. */ static boolean lookupExtendedDataMem(Dem_EventIdType eventId, ExtDataRecType **extData, Dem_DTCOriginType origin) { boolean eventIdFound = FALSE; uint32 i; ExtDataRecType* extBuffer = NULL; uint32 extBufferSize = 0; switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_PRI_MEM) extBuffer = priMemExtDataBuffer; extBufferSize = DEM_MAX_NUMBER_EXT_DATA_PRI_MEM; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_SEC_MEM) extBuffer = secMemExtDataBuffer; extBufferSize = DEM_MAX_NUMBER_EXT_DATA_SEC_MEM; #endif break; default: break; } if( NULL == extBuffer ) { return FALSE; } // Lookup corresponding extended data for (i = 0uL; (i < extBufferSize) && (FALSE == eventIdFound); i++) { eventIdFound = (extBuffer[i].eventId == eventId)? TRUE: FALSE; } if (TRUE == eventIdFound) { // Yes, return pointer *extData = &extBuffer[i-1]; } return eventIdFound; } #if (DEM_USE_TIMESTAMPS == STD_ON) && (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) /** * Searcher buffer for older (compared to timestamp provided) extended data entry. Timestamp check is done based on parameter checkTimeStamp. * @param eventId * @param extData * @param origin * @param timestamp * @param checkTimeStamp * @return */ static boolean lookupOlderExtendedDataMem(Dem_EventIdType eventId, ExtDataRecType **extData, Dem_DTCOriginType origin, uint32 *timestamp, boolean checkTimeStamp) { boolean eventIdFound = FALSE; uint32 i; ExtDataRecType* extBuffer = NULL; uint32 extBufferSize = 0; switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_PRI_MEM) extBuffer = priMemExtDataBuffer; extBufferSize = DEM_MAX_NUMBER_EXT_DATA_PRI_MEM; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_EXT_DATA_IN_SEC_MEM) extBuffer = secMemExtDataBuffer; extBufferSize = DEM_MAX_NUMBER_EXT_DATA_SEC_MEM; #endif break; default: break; } if( NULL == extBuffer ) { return FALSE; } // Lookup corresponding extended data for (i = 0uL; (i < extBufferSize) && (FALSE == eventIdFound); i++) { eventIdFound = (extBuffer[i].eventId == eventId)? TRUE: FALSE; } if ( TRUE == eventIdFound ) { if( (FALSE == checkTimeStamp) || (*timestamp > extBuffer[i-1u].timeStamp) ) { // Yes, return pointer *timestamp = extBuffer[i-1u].timeStamp; *extData = &extBuffer[i-1u]; } else { eventIdFound = FALSE; } } return eventIdFound; } #endif /* * Procedure: storeFreezeFrameDataMem * Description: store FreezeFrame data record in primary memory */ #ifdef DEM_USE_MEMORY_FUNCTIONS #if ( DEM_FF_DATA_IN_PRE_INIT || DEM_FF_DATA_IN_PRI_MEM || DEM_FF_DATA_IN_SEC_MEM ) static boolean storeFreezeFrameDataMem(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin) { boolean eventIdFound = FALSE; boolean eventIdFreePositionFound=FALSE; boolean ffUpdated = FALSE; uint32 i; /* Check if already stored */ for (i = 0uL; (i < freezeFrameBufferSize) && (FALSE == eventIdFound); i++){ eventIdFound = ((freezeFrameBuffer[i].eventId == freezeFrame->eventId) && (freezeFrameBuffer[i].recordNumber == freezeFrame->recordNumber))? TRUE: FALSE; } if ( TRUE == eventIdFound ) { memcpy(&freezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); ffUpdated = TRUE; } else { for (i = 0uL; (i < freezeFrameBufferSize) && (FALSE == eventIdFreePositionFound); i++){ eventIdFreePositionFound = (freezeFrameBuffer[i].eventId == DEM_EVENT_ID_NULL)? TRUE: FALSE; } if ( TRUE == eventIdFreePositionFound ) { memcpy(&freezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); ffUpdated = TRUE; } else { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) /* @req DEM400 *//* @req DEM407 */ FreezeFrameRecType *freezeFrameLocal; if( TRUE == lookupFreezeFrameForDisplacement(eventParam, &freezeFrameLocal, freezeFrameBuffer, freezeFrameBufferSize) ){ memcpy(freezeFrameLocal, freezeFrame, sizeof(FreezeFrameRecType)); ffUpdated = TRUE; } else { setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); } #else /* @req DEM402*/ /* Req is not the Det-error.. */ setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_FF_DATA_MEM_ID, DEM_E_MEM_FF_DATA_BUFF_FULL); #endif } } if( TRUE == ffUpdated ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; EventStatusRecType *eventStatusRecPtr = NULL; lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if( (NULL != eventStatusRecPtr) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRecPtr->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) if ( (TRUE == eventParam->EventClass->FFPrestorageSupported) && (origin == DEM_DTC_ORIGIN_NOT_USED) ) { Dem_NvM_SetPreStoreFreezeFrameBlockChanged(immediateStorage); } else { Dem_NvM_SetFreezeFrameBlockChanged(origin, immediateStorage); } #else Dem_NvM_SetFreezeFrameBlockChanged(origin, immediateStorage); #endif #else #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) if (eventParam->EventClass->FFPrestorageSupported && origin == DEM_DTC_ORIGIN_NOT_USED ) { Dem_NvM_SetPreStoreFreezeFrameBlockChanged(FALSE); } else { Dem_NvM_SetFreezeFrameBlockChanged(origin, FALSE); } #else Dem_NvM_SetFreezeFrameBlockChanged(origin, FALSE); #endif #endif } return ffUpdated; } #endif static boolean deleteFreezeFrameDataMem(const Dem_EventParameterType *eventParam, Dem_DTCOriginType origin, boolean combinedDTC) { uint32 i; boolean ffDeleted = FALSE; FreezeFrameRecType* freezeFrameBuffer = NULL_PTR; uint32 bufferSize = 0uL; Dem_EventIdType idToFind; switch (origin) { #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ( DEM_FF_DATA_IN_PRI_MEM ) freezeFrameBuffer = priMemFreezeFrameBuffer; bufferSize = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; #else freezeFrameBuffer = NULL_PTR; bufferSize = 0uL; #endif break; #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ( DEM_FF_DATA_IN_SEC_MEM ) freezeFrameBuffer = secMemFreezeFrameBuffer; bufferSize = DEM_MAX_NUMBER_FF_DATA_SEC_MEM; #endif break; #endif case DEM_DTC_ORIGIN_NOT_USED: #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) /* It could be a pre-stored freeze frame */ if (TRUE == eventParam->EventClass->FFPrestorageSupported ) { freezeFrameBuffer = memPreStoreFreezeFrameBuffer; bufferSize = DEM_MAX_NUMBER_PRESTORED_FF; } #endif break; default: break; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (TRUE == combinedDTC) && (DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID) ) { idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else (void)combinedDTC; idToFind = eventParam->EventID; #endif if( NULL != freezeFrameBuffer ) { for (i = 0uL; i < bufferSize; i++){ if (freezeFrameBuffer[i].eventId == idToFind){ memset(&freezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); ffDeleted = TRUE; } } if( TRUE == ffDeleted ) { /* IMPROVEMENT: Immediate storage when deleting data? */ #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) if ((TRUE == eventParam->EventClass->FFPrestorageSupported) && (origin == DEM_DTC_ORIGIN_NOT_USED) ) { Dem_NvM_SetPreStoreFreezeFrameBlockChanged(FALSE); } else { Dem_NvM_SetFreezeFrameBlockChanged(origin, FALSE); } #else Dem_NvM_SetFreezeFrameBlockChanged(origin, FALSE); #endif } } return ffDeleted; } #endif /* DEM_USE_MEMORY_FUNCTIONS */ /* * Procedure: storeFreezeFrameDataEvtMem * Description: Store the freeze frame data in event memory according to * "eventParam" destination option */ static boolean storeFreezeFrameDataEvtMem(const Dem_EventParameterType *eventParam, FreezeFrameRecType *freezeFrame, Dem_FreezeFrameKindType ffKind) { boolean ret = FALSE; switch (eventParam->EventClass->EventDestination) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) getFreezeFrameData(eventParam, freezeFrame, ffKind, DEM_DTC_ORIGIN_PRIMARY_MEMORY, TRUE); if (freezeFrame->eventId != DEM_EVENT_ID_NULL) { if(freezeFrame->kind == DEM_FREEZE_FRAME_OBD){ ret = storeOBDFreezeFrameDataMem(eventParam, freezeFrame,priMemFreezeFrameBuffer, DEM_MAX_NUMBER_FF_DATA_PRI_MEM, DEM_DTC_ORIGIN_PRIMARY_MEMORY); } else { ret = storeFreezeFrameDataMem(eventParam, freezeFrame, priMemFreezeFrameBuffer, DEM_MAX_NUMBER_FF_DATA_PRI_MEM, DEM_DTC_ORIGIN_PRIMARY_MEMORY); /** @req DEM190 */ } } #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) getFreezeFrameData(eventParam, freezeFrame, ffKind, DEM_DTC_ORIGIN_SECONDARY_MEMORY, TRUE); if (freezeFrame->eventId != DEM_EVENT_ID_NULL) { if(freezeFrame->kind == DEM_FREEZE_FRAME_OBD){ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_OBD_NOT_ALLOWED_IN_SEC_MEM); } else { ret = storeFreezeFrameDataMem(eventParam, freezeFrame, secMemFreezeFrameBuffer, DEM_MAX_NUMBER_FF_DATA_SEC_MEM, DEM_DTC_ORIGIN_SECONDARY_MEMORY); /** @req DEM190 */ } } #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: (void)freezeFrame; /*lint !e920 Avoid compiler warning (variable not used) */ (void)ffKind; break; } return ret; } /* * Procedure: lookupFreezeFrameDataRecNumParam * Description: Returns TRUE if the requested freezeFrame data number was found among the configured records for the event. * "freezeFrameClassPtr" returns a pointer to the record class. */ static boolean lookupFreezeFrameDataRecNumParam(uint8 recordNumber, const Dem_EventParameterType *eventParam, Dem_FreezeFrameClassType const **freezeFrameClassPtr) { boolean recNumFound = FALSE; uint8 maxNofRecords; const Dem_FreezeFrameRecNumClass *FreezeFrameRecNumClass; Dem_FreezeFrameClassTypeRefIndex ffIdx = DEM_FF_NULLREF; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; maxNofRecords = CombDTCCfg->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = CombDTCCfg->FreezeFrameRecNumClassRef; ffIdx = CombDTCCfg->Calib->FreezeFrameClassIdx; } else { maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; ffIdx = *(eventParam->FreezeFrameClassRefIdx); } #else maxNofRecords = eventParam->MaxNumberFreezeFrameRecords; FreezeFrameRecNumClass = eventParam->FreezeFrameRecNumClassRef; ffIdx = *(eventParam->FreezeFrameClassRefIdx); #endif if ( (ffIdx != DEM_FF_NULLREF) && (NULL != FreezeFrameRecNumClass)) { for( uint8 i = 0; (i < maxNofRecords) && (FALSE == recNumFound); i++ ) { if( FreezeFrameRecNumClass->FreezeFrameRecordNumber[i] == recordNumber ) { recNumFound = TRUE; getFFClassReference(eventParam, (Dem_FreezeFrameClassType **) freezeFrameClassPtr); } } } return recNumFound; } /* * Procedure: lookupFreezeFrameDataSize * Description: Returns TRUE if the requested freezeFrame data size was obtained successfully from the configuration. * "dataSize" returns a pointer to the data size. */ static boolean lookupFreezeFrameDataSize(uint8 recordNumber, const Dem_FreezeFrameClassType const * const *freezeFrameClassPtr, uint16 *dataSize) { boolean dataSizeFound = FALSE; uint16 i; (void)recordNumber; /* Avoid compiler warning - can this be removed */ *dataSize = 0; if (*freezeFrameClassPtr != NULL) { dataSizeFound = TRUE; for (i = 0u; (i < DEM_MAX_NR_OF_DIDS_IN_FREEZEFRAME_DATA) && ((*freezeFrameClassPtr)->FFIdClassRef[i]->Arc_EOL != TRUE); i++) { *dataSize += (uint16)(*freezeFrameClassPtr)->FFIdClassRef[i]->PidOrDidSize + DEM_DID_IDENTIFIER_SIZE_OF_BYTES; } } return dataSizeFound; } /** * Looks for a stored freeze frame with correct record number has been stored for an event * @param eventId * @param recordNumber * @param dtcOrigin * @param freezeFrame * @return TRUE: if a freeze frame with the correct record number was stored for this event, FALSE: Otherwise */ static boolean getStoredFreezeFrame(Dem_EventIdType eventId, uint8 recordNumber, Dem_DTCOriginType dtcOrigin, FreezeFrameRecType **freezeFrame) { boolean ffFound = FALSE; FreezeFrameRecType* freezeFrameBuffer = NULL; uint32 freezeFrameBufferSize = 0; switch (dtcOrigin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) freezeFrameBuffer = priMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) freezeFrameBuffer = secMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_SEC_MEM; #endif break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; } if (freezeFrameBuffer != NULL) { for (uint32 i = 0uL; (i < freezeFrameBufferSize) && (FALSE == ffFound); i++) { ffFound = ((freezeFrameBuffer[i].eventId == eventId) && (freezeFrameBuffer[i].recordNumber == recordNumber))? TRUE: FALSE; if(TRUE == ffFound) { *freezeFrame = &freezeFrameBuffer[i]; } } } return ffFound; } #if (DEM_USE_TIMESTAMPS == STD_ON) && (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) /** * Gets and updates freeze frame data if older than provided timestamp * @param eventId * @param recordNumber * @param dtcOrigin * @param destBuffer * @param bufSize * @param FFDataSize * @param timestamp * @param checkTimeStamp * @return */ static boolean getOlderFreezeFrameRecord(Dem_EventIdType eventId, uint8 recordNumber, Dem_DTCOriginType dtcOrigin, uint8* destBuffer, uint16* bufSize, const uint16 FFDataSize, uint32 *timestamp, boolean checkTimeStamp) { boolean ffFound = FALSE; FreezeFrameRecType* freezeFrame = NULL; if( TRUE == getStoredFreezeFrame(eventId, recordNumber, dtcOrigin, &freezeFrame) ) { if( (FALSE == checkTimeStamp) || (*timestamp > freezeFrame->timeStamp) ) { memcpy(destBuffer, freezeFrame->data, FFDataSize); /** @req DEM071 */ *bufSize = FFDataSize; *timestamp = freezeFrame->timeStamp; ffFound = TRUE; } } return ffFound; } #else /* * Procedure: getFreezeFrameRecord * Description: Returns TRUE if the requested event id is found, "freezeFrame" points to the found data. */ static boolean getFreezeFrameRecord(Dem_EventIdType eventId, uint8 recordNumber, Dem_DTCOriginType dtcOrigin, uint8* destBuffer, uint16* bufSize, const uint16 FFDataSize) { boolean ffFound = FALSE; FreezeFrameRecType* freezeFrame = NULL; if(TRUE == getStoredFreezeFrame(eventId, recordNumber, dtcOrigin, &freezeFrame)) { memcpy(destBuffer, freezeFrame->data, FFDataSize); /** @req DEM071 */ *bufSize = FFDataSize; ffFound = TRUE; } return ffFound; } #endif /** * Gets conditions for data storage * @param eventFailedNow * @param eventDataUppdated * @param extensionStorageBitfield * @param storeFFData * @param storeExtData * @param overrideOldExtdata */ static void getStorageConditions(boolean eventFailedNow, boolean eventDataUpdated, uint8 extensionStorageBitfield, boolean *storeFFData, boolean *storeExtData, boolean *overrideOldExtData) { #if defined(DEM_EXTENDED_DATA_CAPTURE_EVENT_MEMORY_STORAGE) *storeExtData = eventDataUpdated; *overrideOldExtData = FALSE; #elif defined(DEM_EXTENDED_DATA_CAPTURE_TESTFAILED) *storeExtData = eventFailedNow; *overrideOldExtData = FALSE; #elif defined(DEM_EXTENDED_DATA_CAPTURE_EXTENSION) /* @req OEM_DEM_10169 DEM_TRIGGER_EXTENSION */ *overrideOldExtData = (0 != (extensionStorageBitfield & DEM_EXT_CLEAR_BEFORE_STORE_EXT_DATA_BIT)); *storeExtData = (0 != (extensionStorageBitfield & DEM_EXT_STORE_EXT_DATA_BIT)); #else *storeExtData = FALSE; *overrideOldExtData = FALSE; #endif #if defined(DEM_FREEZE_FRAME_CAPTURE_EVENT_MEMORY_STORAGE) *storeFFData = eventDataUpdated; #elif defined(DEM_FREEZE_FRAME_CAPTURE_TESTFAILED) *storeFFData = eventFailedNow; #elif defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) /* @req OEM_DEM_10170 DEM_TRIGGER_EXTENSION */ *storeFFData = (0 != (extensionStorageBitfield & DEM_EXT_STORE_FF_BIT)); #else *storeFFData = FALSE; (void)eventFailedNow; /* Avoid compiler warning */ (void)eventDataUpdated; /* Avoid compiler warning */ (void)extensionStorageBitfield; /* Avoid compiler warning */ #endif } /* * Procedure: handlePreInitEvent * Description: Handle the updating of event status and storing of * event related data in preInit buffers. */ static void handlePreInitEvent(Dem_EventIdType eventId, Dem_EventStatusType eventStatus) { const Dem_EventParameterType *eventParam; EventStatusRecType *eventStatusRec = NULL; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) Dem_EventStatusExtendedType newDTCStatus = DEM_DEFAULT_EVENT_STATUS; Dem_EventStatusExtendedType oldDTCStatus = DEM_DEFAULT_EVENT_STATUS; #endif lookupEventIdParameter(eventId, &eventParam); if (eventParam != NULL) { if ( TRUE == operationCycleIsStarted(eventParam->EventClass->OperationCycleRef) ) { lookupEventStatusRec(eventId, &eventStatusRec); if( NULL != eventStatusRec ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { if( DEM_STATUS_OK != GetDTCUDSStatus(eventParam->DTCClassRef, eventParam->EventClass->EventDestination, &oldDTCStatus) ) { oldDTCStatus = eventStatusRec->eventStatusExtended; } } else { oldDTCStatus = eventStatusRec->eventStatusExtended; } #endif updateEventStatusRec(eventParam, eventStatus, eventStatusRec); #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { if( DEM_STATUS_OK != GetDTCUDSStatus(eventParam->DTCClassRef, eventParam->EventClass->EventDestination, &newDTCStatus) ) { newDTCStatus = eventStatusRec->eventStatusExtended; } } else { newDTCStatus = eventStatusRec->eventStatusExtended; } #endif if ( (0 != eventStatusRec->errorStatusChanged) || (0 != eventStatusRec->extensionDataChanged) ) { boolean storeExtData; boolean overrideOldExtData; boolean storeFFData; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) boolean dtcFailedNow = (((0u == (oldDTCStatus & DEM_TEST_FAILED))) && ((0 != (newDTCStatus & DEM_TEST_FAILED)))) ? TRUE: FALSE; #else boolean eventFailedNow = ((TRUE == eventStatusRec->errorStatusChanged) && (0 != (eventStatusRec->eventStatusExtended & DEM_TEST_FAILED)))? TRUE: FALSE; #endif /* Get conditions for data storage */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* @req DEM163 */ getStorageConditions(dtcFailedNow, TRUE, eventStatusRec->extensionDataStoreBitfield, &storeFFData, &storeExtData, &overrideOldExtData); #else /* @req DEM539 */ getStorageConditions(eventFailedNow, TRUE, eventStatusRec->extensionDataStoreBitfield, &storeFFData, &storeExtData, &overrideOldExtData); #endif if( (TRUE == storeExtData) && (NULL != eventParam->ExtendedDataClassRef) ) { (void)storeExtendedData(eventParam, overrideOldExtData); } #if( DEM_FF_DATA_IN_PRE_INIT ) if( TRUE == storeFFData) { FreezeFrameRecType freezeFrameLocal; if( DEM_FF_NULLREF != getFFIdx(eventParam) ) { #if defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) /* Allow extension to decide if ffs should be deleted before storing */ if( 0 != (eventStatusRec->extensionDataStoreBitfield & DEM_EXT_CLEAR_BEFORE_STORE_FF_BIT) ) { deleteFreezeFrameDataPreInit(eventParam); } #endif getFreezeFrameData(eventParam, &freezeFrameLocal, DEM_FREEZE_FRAME_NON_OBD, DEM_DTC_ORIGIN_NOT_USED, TRUE); if (freezeFrameLocal.eventId != DEM_EVENT_ID_NULL) { storeFreezeFrameDataPreInit(eventParam, &freezeFrameLocal); } } if( (NULL != eventParam->DTCClassRef) && (DEM_NON_EMISSION_RELATED != (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind) ) { getFreezeFrameData(eventParam, &freezeFrameLocal, DEM_FREEZE_FRAME_OBD, DEM_DTC_ORIGIN_NOT_USED, TRUE); if (freezeFrameLocal.eventId != DEM_EVENT_ID_NULL) { storeFreezeFrameDataPreInit(eventParam, &freezeFrameLocal); } } } #endif /* DEM_FF_DATA_IN_PRE_INIT */ } } } else { // Operation cycle not set or not started // IMPROVEMENT: Report error? } } else { // Event ID not configured // IMPROVEMENT: Report error? } } #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) static boolean enableConditionsSet(const Dem_EventClassType *eventClass) { /* @req DEM449 */ /* @req DEM450 */ boolean conditionsSet = TRUE; if( NULL != eventClass->EnableConditionGroupRef ) { /* Each group must reference at least one enable condition. Or this won't work.. */ const Dem_EnableConditionGroupType *enableConditionGroupPtr = eventClass->EnableConditionGroupRef; for( uint8 i = 0; i < enableConditionGroupPtr->nofEnableConditions; i++ ) { if( FALSE == DemEnableConditions[enableConditionGroupPtr->EnableCondition[i]->EnableConditionID] ) { conditionsSet = FALSE; } } } return conditionsSet; } #endif /** * Checks whether DTC setting for event is disabled. If the event does not have a DTC (or its DTC is suppressed) * setting is NOT disabled. * @param eventParam * @return TRUE: Disabled, FALSE: NOT disabled */ static boolean DTCSettingDisabled(const Dem_EventParameterType *eventParam) { /* @req DEM587 */ boolean eventDTCSettingDisabled = FALSE; if( (disableDtcSetting.settingDisabled == TRUE) && (NULL != eventParam->DTCClassRef) && (DTCIsAvailable(eventParam->DTCClassRef) == TRUE) ) { /* DTC setting is disabled and the event has a DTC (which is not suppressed) */ if( (checkDtcGroup(disableDtcSetting.dtcGroup, eventParam, DEM_DTC_FORMAT_UDS) == TRUE) && (checkDtcKind(disableDtcSetting.dtcKind, eventParam) == TRUE) ) { /* Setting of DTC for this event is disabled. */ eventDTCSettingDisabled = TRUE; } } return eventDTCSettingDisabled; } /** * Checks whether event processing is allowed * @param eventParam * @return TRUE: Processing allowed, FALSE: Processing not allowed */ static boolean eventProcessingAllowed(const Dem_EventParameterType *eventParam) { /* Event processing is not allowed if event has DTC and DTC setting has been disabled, * or if event has enable conditions and these are not set. */ if ( ( FALSE == DTCSettingDisabled(eventParam) ) /* @req DEM626 */ #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) && (TRUE == enableConditionsSet(eventParam->EventClass))/* @req DEM447 */ #endif ) { return TRUE; } else { return FALSE; } } /** * Checks if condition for storing OBD freeze frame is fulfilled * @param eventParam * @param oldStatus * @param status * @return */ static boolean checkOBDFFStorageCondition(Dem_EventStatusExtendedType oldStatus, Dem_EventStatusExtendedType status) { if( (0u == (oldStatus & DEM_CONFIRMED_DTC)) && (0u != (status & DEM_CONFIRMED_DTC)) ) { return TRUE; } else { return FALSE; } } /** * Get index for event FF * @param eventParam * @return DEM_FF_NULLREF: no FF configured */ static Dem_FreezeFrameClassTypeRefIndex getFFIdx(const Dem_EventParameterType *eventParam) { Dem_FreezeFrameClassTypeRefIndex ffIdx = DEM_FF_NULLREF; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; ffIdx = CombDTCCfg->Calib->FreezeFrameClassIdx; } else { if( NULL_PTR != eventParam->FreezeFrameClassRefIdx ) { ffIdx = *(eventParam->FreezeFrameClassRefIdx); } } #else if( NULL_PTR != eventParam->FreezeFrameClassRefIdx ) { ffIdx = *(eventParam->FreezeFrameClassRefIdx); } #endif return ffIdx; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /** * Gets the status of DTC referenced bu event * @param eventParam * @param eventStatus * @return Status of DTC */ static Dem_EventStatusExtendedType getEventDTCStatus(const Dem_EventParameterType *eventParam, Dem_EventStatusExtendedType eventStatus) { Dem_EventStatusExtendedType DTCStatus = DEM_DEFAULT_EVENT_STATUS; if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { if( DEM_STATUS_OK != GetDTCUDSStatus(eventParam->DTCClassRef, eventParam->EventClass->EventDestination, &DTCStatus) ) { DTCStatus = eventStatus; } } else { DTCStatus = eventStatus; } return DTCStatus; } #endif /* * Procedure: handleEvent * Description: Handle the updating of event status and storing of * event related data in event memory. */ Std_ReturnType handleEvent(Dem_EventIdType eventId, Dem_EventStatusType eventStatus) { Std_ReturnType returnCode = E_OK; const Dem_EventParameterType *eventParam; EventStatusRecType *eventStatusRec; FreezeFrameRecType freezeFrameLocal; Dem_EventStatusExtendedType oldEventStatus = DEM_DEFAULT_EVENT_STATUS; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) Dem_EventStatusExtendedType newDTCStatus = DEM_DEFAULT_EVENT_STATUS; Dem_EventStatusExtendedType oldDTCStatus = DEM_DEFAULT_EVENT_STATUS; #endif Std_ReturnType eventStoreStatus = E_OK; lookupEventIdParameter(eventId, &eventParam); lookupEventStatusRec(eventId, &eventStatusRec); if ( (eventParam != NULL) && (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable) ) { if ( TRUE == operationCycleIsStarted(eventParam->EventClass->OperationCycleRef) ) {/* @req DEM481 */ /* Check if event processing is allowed (DTC setting, enable condition) */ if ( TRUE == eventProcessingAllowed(eventParam)) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) oldDTCStatus = getEventDTCStatus(eventParam, eventStatusRec->eventStatusExtended); #endif oldEventStatus = eventStatusRec->eventStatusExtended; updateEventStatusRec(eventParam, eventStatus, eventStatusRec); #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) newDTCStatus = getEventDTCStatus(eventParam, eventStatusRec->eventStatusExtended); #endif if ( (0 != eventStatusRec->errorStatusChanged) || (0 != eventStatusRec->extensionDataChanged) ) { boolean eventFailedNow = ((TRUE == eventStatusRec->errorStatusChanged) && (0 != (eventStatusRec->eventStatusExtended & DEM_TEST_FAILED)))? TRUE: FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) boolean dtcFailedNow = (((0u == (oldDTCStatus & DEM_TEST_FAILED))) && ((0 != (newDTCStatus & DEM_TEST_FAILED)))) ? TRUE: FALSE; #endif eventStoreStatus = storeEventEvtMem(eventParam, eventStatusRec, eventFailedNow); /** @req DEM184 *//** @req DEM396 */ boolean storeExtData; boolean storeFFData; boolean overrideOldExtData; boolean eventDataUpdated = (E_OK == eventStoreStatus)? TRUE: FALSE; /* Get conditions for data storage */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* @req DEM163 */ getStorageConditions(dtcFailedNow, eventDataUpdated, eventStatusRec->extensionDataStoreBitfield, &storeFFData, &storeExtData, &overrideOldExtData); #else /* @req DEM539 */ getStorageConditions(eventFailedNow, eventDataUpdated, eventStatusRec->extensionDataStoreBitfield, &storeFFData, &storeExtData, &overrideOldExtData); #endif if( FALSE == eventDTCRecordDataUpdateDisabled(eventParam) ) { if ( (TRUE == storeExtData) && (NULL != eventParam->ExtendedDataClassRef) ) { if( TRUE == storeExtendedData(eventParam, overrideOldExtData) ) { eventDataUpdated = TRUE; } } if ( TRUE == storeFFData ) { if( DEM_FF_NULLREF != getFFIdx(eventParam) ) { #if defined(DEM_USE_MEMORY_FUNCTIONS) && defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) /* Allow extension to decide if ffs should be deleted before storing */ if( 0 != (eventStatusRec->extensionDataStoreBitfield & DEM_EXT_CLEAR_BEFORE_STORE_FF_BIT) ) { if( TRUE == deleteFreezeFrameDataMem(eventParam, eventParam->EventClass->EventDestination, FALSE) ) { eventDataUpdated = TRUE; } } #endif if( TRUE == storeFreezeFrameDataEvtMem(eventParam, &freezeFrameLocal, DEM_FREEZE_FRAME_NON_OBD) ) { /** @req DEM190 */ eventDataUpdated = TRUE; } } if( (DEM_NON_EMISSION_RELATED != (Dem_Arc_EventDTCKindType) *(eventParam->EventDTCKind)) && (TRUE == eventDataUpdated) && #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) (TRUE == checkOBDFFStorageCondition(oldDTCStatus, newDTCStatus)) #else (TRUE == checkOBDFFStorageCondition(oldEventStatus, eventStatusRec->eventStatusExtended)) #endif ) { if( TRUE == storeFreezeFrameDataEvtMem(eventParam, &freezeFrameLocal, DEM_FREEZE_FRAME_OBD) ) { /** @req DEM190 */ eventDataUpdated = TRUE; } } } } if( TRUE == eventDataUpdated ) { /* @req DEM475 */ notifyEventDataChanged(eventParam); } } if( E_NOT_OK == eventStoreStatus ) { /* Tried to store event but did not succeed (eventStoreStatus initialized to E_OK). * Make sure confirmed bit is not set. */ eventStatusRec->eventStatusExtended &= ~DEM_CONFIRMED_DTC; } if( oldEventStatus != eventStatusRec->eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventStatusRec->eventParamRef, oldEventStatus, eventStatusRec->eventStatusExtended); } #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) if((TRUE == eventStatusRec->indicatorDataChanged) && (TRUE == isInEventMemory(eventParam))) { storeEventIndicators(eventParam); #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; if( (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRec->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } Dem_NvM_SetIndicatorBlockChanged(immediateStorage); #else Dem_NvM_SetIndicatorBlockChanged(FALSE); #endif } #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) if(TRUE == handlePermanentDTCStorage(eventParam, eventStatusRec->eventStatusExtended)) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; if( (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRec->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } Dem_NvM_SetPermanentBlockChanged(immediateStorage); #else Dem_NvM_SetPermanentBlockChanged(FALSE); #endif } #endif } else { /* Enable conditions not set or DTC disabled */ returnCode = E_NOT_OK; } } else { returnCode = E_NOT_OK; // Operation cycle not valid or not started /* @req DEM482 */ } } else { returnCode = E_NOT_OK; // Event ID not configured or set to not available } return returnCode; } /* * Procedure: resetEventStatus * Description: Resets the events status of eventId. */ static Std_ReturnType resetEventStatus(Dem_EventIdType eventId) { EventStatusRecType *eventStatusRecPtr; Std_ReturnType ret = E_OK; lookupEventStatusRec(eventId, &eventStatusRecPtr); if (eventStatusRecPtr != NULL) { if( (TRUE == eventStatusRecPtr->isAvailable) && (0 != (eventStatusRecPtr->eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE)) ) { Dem_EventStatusExtendedType oldStatus = eventStatusRecPtr->eventStatusExtended; eventStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)~DEM_TEST_FAILED; /** @req DEM187 */ resetDebounceCounter(eventStatusRecPtr); if( oldStatus != eventStatusRecPtr->eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventStatusRecPtr->eventParamRef, oldStatus, eventStatusRecPtr->eventStatusExtended); } /* NOTE: Should we store in "event destination" if DEM_TEST_FAILED_STORAGE == STD_ON) */ #if 0 #if DEM_TEST_FAILED_STORAGE == STD_ON if((0 != (oldStatus & DEM_TEST_FAILED)) && (E_OK == storeEventEvtMem(eventStatusRecPtr->eventParamRef, eventStatusRecPtr))) { notifyEventDataChanged(eventStatusRecPtr->eventParamRef); } #endif #endif } else { /* @req DEM638 */ ret = E_NOT_OK; } } return ret; } /* * Procedure: getEventStatus * Description: Returns the extended event status bitmask of eventId in "eventStatusExtended". */ static Std_ReturnType getEventStatus(Dem_EventIdType eventId, Dem_EventStatusExtendedType *eventStatusExtended) { Std_ReturnType ret = E_OK; EventStatusRecType eventStatusLocal; // Get recorded status getEventStatusRec(eventId, &eventStatusLocal); if ( (eventStatusLocal.eventId == eventId) && (TRUE == eventStatusLocal.isAvailable) ) { *eventStatusExtended = eventStatusLocal.eventStatusExtended; /** @req DEM051 */ } else { // Event Id not found, no report received. *eventStatusExtended = DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE | DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR; ret = E_NOT_OK; } return ret; } /* * Procedure: getEventFailed * Description: Returns the TRUE or FALSE of "eventId" in "eventFailed" depending on current status. */ static Std_ReturnType getEventFailed(Dem_EventIdType eventId, boolean *eventFailed) { Std_ReturnType ret = E_OK; EventStatusRecType eventStatusLocal; // Get recorded status getEventStatusRec(eventId, &eventStatusLocal); if ( (eventStatusLocal.eventId == eventId) && (TRUE == eventStatusLocal.isAvailable) ) { if ( 0 != (eventStatusLocal.eventStatusExtended & DEM_TEST_FAILED)) { /** @req DEM052 */ *eventFailed = TRUE; } else { *eventFailed = FALSE; } } else { // Event Id not found or not available. *eventFailed = FALSE; ret = E_NOT_OK; } return ret; } /* * Procedure: getEventTested * Description: Returns the TRUE or FALSE of "eventId" in "eventTested" depending on * current status the "test not completed this operation cycle" bit. */ static Std_ReturnType getEventTested(Dem_EventIdType eventId, boolean *eventTested) { Std_ReturnType ret = E_OK; EventStatusRecType eventStatusLocal; // Get recorded status getEventStatusRec(eventId, &eventStatusLocal); if ( (eventStatusLocal.eventId == eventId) && (TRUE == eventStatusLocal.isAvailable) ) { if ( 0 == (eventStatusLocal.eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE)) { /** @req DEM053 */ *eventTested = TRUE; } else { *eventTested = FALSE; } } else { // Event Id not found, not tested. *eventTested = FALSE; ret = E_NOT_OK; } return ret; } #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) && defined(DEM_USE_MEMORY_FUNCTIONS) #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_COMBINED_DTC_STATUS_AGING) /** * Gets the combined status (passed/failed) during aging cycle * @param eventParam * @param passed * @param failed * @return */ static Std_ReturnType getCombTypeStatusDuringAgingCycle(const Dem_EventParameterType *eventParam, boolean *passed, boolean *failed) { Std_ReturnType ret = E_NOT_OK; const Dem_CombinedDTCCfgType *CombDTCCfg; const Dem_DTCClassType *DTCClass; EventStatusRecType* eventStatusRecPtr; *failed = FALSE; *passed = TRUE; if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { ret = E_OK; CombDTCCfg = &configSet->CombinedDTCConfig[eventParam->CombinedDTCCID]; DTCClass = CombDTCCfg->DTCClassRef; for(uint16 i = 0; (i < DTCClass->NofEvents) && (E_OK == ret); i++) { if( eventParam->EventID != DTCClass->Events[i] ) { eventStatusRecPtr = NULL_PTR; lookupEventStatusRec(DTCClass->Events[i], &eventStatusRecPtr); if( NULL_PTR != eventStatusRecPtr ) { if( FALSE == eventStatusRecPtr->passedDuringAgingCycle ) { *passed = FALSE; } if( TRUE == eventStatusRecPtr->failedDuringAgingCycle ) { *failed = FALSE; } } else { /* This is unexpected */ ret = E_NOT_OK; } } } } return ret; } #endif #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /** * Deletes all DTC data if a combined DTC is aged * @param eventParam * @return TRUE: data was deleted, FALSE: No data deleted */ static boolean deletDTCDataIfAged(const Dem_EventParameterType *eventParam) { boolean dataDeleted = FALSE; boolean dummy; if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { Dem_EventStatusExtendedType DTCStatus; if( DEM_STATUS_OK == GetDTCUDSStatus(eventParam->DTCClassRef, eventParam->EventClass->EventDestination, &DTCStatus) ) { if( 0u == (DTCStatus & DEM_CONFIRMED_DTC) ) { /* Confirmed bit was cleared for combined event *//* @req DEM442 */ if( TRUE == DeleteDTCData(eventParam, FALSE, &dummy, TRUE) ) { dataDeleted = TRUE; } } } } return dataDeleted; } #endif static boolean ageEvent(EventStatusRecType* evtStatusRecPtr) { /* @req DEM643 */ boolean updatedMemory = FALSE; boolean dummy; boolean eventDeleted = FALSE; Dem_EventStatusExtendedType oldStatus = evtStatusRecPtr->eventStatusExtended; boolean passedDuringAgingCycle; boolean failedDuringAgingCycle; /* @req DEM489 *//* If it is confirmed it should be stored in event memory */ if( 0u != (evtStatusRecPtr->eventStatusExtended & DEM_CONFIRMED_DTC)) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) && defined(DEM_COMBINED_DTC_STATUS_AGING) if( DEM_COMBINED_EVENT_NO_DTC_ID != evtStatusRecPtr->eventParamRef->CombinedDTCCID ) { passedDuringAgingCycle = evtStatusRecPtr->passedDuringAgingCycle; failedDuringAgingCycle = evtStatusRecPtr->failedDuringAgingCycle; if( E_OK != getCombTypeStatusDuringAgingCycle(evtStatusRecPtr->eventParamRef, &passedDuringAgingCycle, &failedDuringAgingCycle) ) { passedDuringAgingCycle = FALSE; failedDuringAgingCycle = FALSE; } } else { passedDuringAgingCycle = evtStatusRecPtr->passedDuringAgingCycle; failedDuringAgingCycle = evtStatusRecPtr->failedDuringAgingCycle; } #else passedDuringAgingCycle = evtStatusRecPtr->passedDuringAgingCycle; failedDuringAgingCycle = evtStatusRecPtr->failedDuringAgingCycle; #endif if( (TRUE == passedDuringAgingCycle) && (FALSE == evtStatusRecPtr->failedDuringAgingCycle) ) { /* Event was PASSED but NOT FAILED during aging cycle. * Increment aging counter */ if( evtStatusRecPtr->agingCounter < DEM_AGING_CNTR_MAX ) { evtStatusRecPtr->agingCounter++; /* Set the flag,start up the storage of NVRam in main function. */ updatedMemory = TRUE; } if((NULL != evtStatusRecPtr->eventParamRef->EventClass->AgingCycleCounterThresholdPtr) && (evtStatusRecPtr->agingCounter >= *evtStatusRecPtr->eventParamRef->EventClass->AgingCycleCounterThresholdPtr) ) { /* @req DEM493 */ /* @req DEM497 *//* Delete ff and ext data */ /* @req DEM161 */ /* @req DEM541 */ evtStatusRecPtr->agingCounter = 0; /* !req DEM498 *//* IMPROVEMNT: Only reset confirmed bit */ evtStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)(~DEM_CONFIRMED_DTC); evtStatusRecPtr->eventStatusExtended &= (Dem_EventStatusExtendedType)(~DEM_PENDING_DTC); if(TRUE == DeleteDTCData(evtStatusRecPtr->eventParamRef, FALSE, &dummy, FALSE)) { /* Set the flag,start up the storage of NVRam in main function. */ updatedMemory = TRUE; eventDeleted = TRUE; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( TRUE == deletDTCDataIfAged(evtStatusRecPtr->eventParamRef ) ) { /* Set the flag,start up the storage of NVRam in main function. */ updatedMemory = TRUE; } #endif #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) evtStatusRecPtr->failureCounter = 0; #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_HealedEvent(evtStatusRecPtr->eventId); #endif } } else if( (TRUE == failedDuringAgingCycle) && (0u != evtStatusRecPtr->agingCounter)) { /* Event failed during the aging cycle. Reset aging counter */ evtStatusRecPtr->agingCounter = 0; updatedMemory = TRUE; } else { /* Do nothing.. */ } } if( oldStatus != evtStatusRecPtr->eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(evtStatusRecPtr->eventParamRef, oldStatus, evtStatusRecPtr->eventStatusExtended); } if( TRUE == updatedMemory ) { if( FALSE == eventDeleted ) { if(E_OK == storeEventEvtMem(evtStatusRecPtr->eventParamRef, evtStatusRecPtr, FALSE) ) { /* @req DEM475 */ notifyEventDataChanged(evtStatusRecPtr->eventParamRef); } } else { /* Event was deleted. So don't store again but notify event data changed */ notifyEventDataChanged(evtStatusRecPtr->eventParamRef); #if defined(DEM_USE_MEMORY_FUNCTIONS) /* IMPROVEMENT: Immediate storage when deleting data? */ Dem_NvM_SetEventBlockChanged(evtStatusRecPtr->eventParamRef->EventClass->EventDestination, FALSE); #endif } } return updatedMemory; } /* * Procedure: handleAging * Description: according to the operation state of "operationCycleId" to "cycleState" , handle the aging relatived data * Returns E_OK if operation was successful else E_NOT_OK. */ static Std_ReturnType handleAging(Dem_OperationCycleIdType operationCycleId) { uint16 i; Std_ReturnType returnCode = E_OK; boolean agingUpdatedSecondaryMemory = FALSE; boolean agingUpdatedPrimaryMemory = FALSE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStoragePrimary = FALSE; boolean immediateStorageSecondary = FALSE; #endif if (operationCycleId < DEM_OPERATION_CYCLE_ID_ENDMARK) { /** @req Dem490 */ for (i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if(eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL){ if(eventStatusBuffer[i].eventParamRef != NULL){ if(eventStatusBuffer[i].eventParamRef->EventClass != NULL){ if((eventStatusBuffer[i].eventParamRef->EventClass->AgingAllowed == TRUE) && (eventStatusBuffer[i].eventParamRef->EventClass->AgingCycleRef == operationCycleId)) { /* Loop all destination memories e.g. primary and secondary */ Dem_DTCOriginType origin = eventStatusBuffer[i].eventParamRef->EventClass->EventDestination; if (origin == DEM_DTC_ORIGIN_SECONDARY_MEMORY) { agingUpdatedSecondaryMemory = ageEvent(&eventStatusBuffer[i]); #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventStatusBuffer[i].eventParamRef->DTCClassRef) && (TRUE == eventStatusBuffer[i].eventParamRef->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusBuffer[i].occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorageSecondary = TRUE; } #endif } else if (origin == DEM_DTC_ORIGIN_PRIMARY_MEMORY) { agingUpdatedPrimaryMemory = ageEvent(&eventStatusBuffer[i]); #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventStatusBuffer[i].eventParamRef->DTCClassRef) && (TRUE == eventStatusBuffer[i].eventParamRef->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusBuffer[i].occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStoragePrimary = TRUE; } #endif } } } } } } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_SETOPERATIONCYCLESTATE_ID, DEM_E_PARAM_DATA); returnCode = E_NOT_OK; } #if defined(DEM_USE_MEMORY_FUNCTIONS) if( TRUE == agingUpdatedPrimaryMemory ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) Dem_NvM_SetEventBlockChanged(DEM_DTC_ORIGIN_PRIMARY_MEMORY, immediateStoragePrimary); #else Dem_NvM_SetEventBlockChanged(DEM_DTC_ORIGIN_PRIMARY_MEMORY, FALSE); #endif } if( TRUE == agingUpdatedSecondaryMemory ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) Dem_NvM_SetEventBlockChanged(DEM_DTC_ORIGIN_SECONDARY_MEMORY, immediateStorageSecondary); #else Dem_NvM_SetEventBlockChanged(DEM_DTC_ORIGIN_SECONDARY_MEMORY, FALSE); #endif } #endif return returnCode; } #endif /** * Handles starting an operation cycle * @param operationCycleId */ static void operationCycleStart(Dem_OperationCycleIdType operationCycleId) { Dem_EventStatusExtendedType oldStatus; operationCycleStateList[operationCycleId] = DEM_CYCLE_STATE_START; // Lookup event ID for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if( (eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) && (TRUE == eventStatusBuffer[i].isAvailable) ) { if( eventStatusBuffer[i].eventParamRef->EventClass->OperationCycleRef == operationCycleId ) { oldStatus = eventStatusBuffer[i].eventStatusExtended; eventStatusBuffer[i].eventStatusExtended &= (Dem_EventStatusExtendedType)~DEM_TEST_FAILED_THIS_OPERATION_CYCLE; eventStatusBuffer[i].eventStatusExtended |= DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE; resetDebounceCounter(&eventStatusBuffer[i]); eventStatusBuffer[i].isDisabled = FALSE; if( oldStatus != eventStatusBuffer[i].eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventStatusBuffer[i].eventParamRef, oldStatus, eventStatusBuffer[i].eventStatusExtended); } if( NULL != eventStatusBuffer[i].eventParamRef->CallbackInitMforE ) { /* @req DEM376 */ (void)eventStatusBuffer[i].eventParamRef->CallbackInitMforE(DEM_INIT_MONITOR_RESTART); } } #if defined(USE_DEM_EXTENSION) Dem_Extension_OperationCycleStart(operationCycleId, &eventStatusBuffer[i]); #endif } #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) if( (eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) && ((Dem_OperationCycleIdType)*eventStatusBuffer[i].eventParamRef->EventClass->FailureCycleRef == operationCycleId) ) { eventStatusBuffer[i].failedDuringFailureCycle = FALSE; eventStatusBuffer[i].passedDuringFailureCycle = FALSE; } #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) if( (eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) && (eventStatusBuffer[i].eventParamRef->EventClass->AgingCycleRef == operationCycleId) ) { eventStatusBuffer[i].passedDuringAgingCycle = FALSE; eventStatusBuffer[i].failedDuringAgingCycle = FALSE; } #endif } #if defined(DEM_USE_INDICATORS) indicatorOpCycleStart(operationCycleId); #endif #if defined(DEM_USE_IUMPR) resetIumprFlags(operationCycleId); incrementUnlockedIumprDenominators(operationCycleId); incrementIgnitionCycleCounter(operationCycleId); #endif } #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /** * Check if an event is stored in permanent memory * @param eventParam * @return */ static boolean isStoredInPermanentMemory(const Dem_EventParameterType *eventParam) { boolean isStored = FALSE; for( uint32 i = 0; (i < DEM_MAX_NUMBER_EVENT_PERM_MEM) && (FALSE == isStored); i++) { if( (NULL != eventParam->DTCClassRef) && (eventParam->DTCClassRef->DTCRef->OBDDTC == permMemEventBuffer[i].OBDDTC)) { /* DTC is stored */ isStored = TRUE; } } return isStored; } /** * Transfers a number of events to permanent memory * @param nofEntries */ static boolean transferEventToPermanent(uint16 nofEntries) { uint32 oldestTimestamp; uint16 storeIndex = 0; boolean candidateFound = TRUE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateStorage = FALSE; #endif /* Find the oldest */ for( uint16 cnt = 0; (cnt < nofEntries) && (TRUE == candidateFound); cnt++ ) { candidateFound = FALSE; oldestTimestamp = 0xFFFFFFFF; for (uint16 i = 0; (i < DEM_MAX_NUMBER_EVENT) ; i++) { if( (eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) && (TRUE == eventStatusBuffer[i].isAvailable) ) { if( (TRUE == permanentDTCStorageConditionFulfilled(eventStatusBuffer[i].eventParamRef, eventStatusBuffer[i].eventStatusExtended)) && (FALSE == isStoredInPermanentMemory(eventStatusBuffer[i].eventParamRef)) && (eventStatusBuffer[i].timeStamp < oldestTimestamp)) { storeIndex = i; oldestTimestamp = eventStatusBuffer[i].timeStamp; candidateFound = TRUE; } } } if( TRUE == candidateFound ) { if( TRUE == handlePermanentDTCStorage(eventStatusBuffer[storeIndex].eventParamRef, eventStatusBuffer[storeIndex].eventStatusExtended) ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventStatusBuffer[storeIndex].eventParamRef->DTCClassRef) && (TRUE == eventStatusBuffer[storeIndex].eventParamRef->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusBuffer[storeIndex].occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateStorage = TRUE; } #endif } } } #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) return immediateStorage; #else return FALSE; #endif } #endif /** * Handles ending an operation cycle * @param operationCycleId */ static void operationCycleEnd(Dem_OperationCycleIdType operationCycleId) { Dem_EventStatusExtendedType oldStatus; #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) boolean permanentMemoryUpdated = FALSE; uint16 nofErasedPermanentDTCs = 0; #endif #if defined(DEM_USE_INDICATORS) boolean indicatorsUpdated = FALSE; #endif operationCycleStateList[operationCycleId] = DEM_CYCLE_STATE_END; // Lookup event ID for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { boolean storeEvtMem = FALSE; if ((eventStatusBuffer[i].eventId != DEM_EVENT_ID_NULL) && (TRUE == eventStatusBuffer[i].isAvailable)) { oldStatus = eventStatusBuffer[i].eventStatusExtended; #if defined(DEM_USE_INDICATORS) if(TRUE == indicatorOpCycleEnd(operationCycleId, &eventStatusBuffer[i])) { indicatorsUpdated = TRUE; } #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) /* Handle the permanent DTC */ if(TRUE == handlePermanentDTCErase(&eventStatusBuffer[i], operationCycleId) ) { nofErasedPermanentDTCs++; permanentMemoryUpdated = TRUE; } #endif if ((0 == (eventStatusBuffer[i].eventStatusExtended & DEM_TEST_FAILED_THIS_OPERATION_CYCLE)) && (0 == (eventStatusBuffer[i].eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE))) { if( eventStatusBuffer[i].eventParamRef->EventClass->OperationCycleRef == operationCycleId ) { eventStatusBuffer[i].eventStatusExtended &= (Dem_EventStatusExtendedType)~DEM_PENDING_DTC; // Clear pendingDTC bit /** @req DEM379.PendingClear if( oldStatus != eventStatusBuffer[i].eventStatusExtended ) { storeEvtMem = TRUE; } } } #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) if( ((Dem_OperationCycleIdType)*(eventStatusBuffer[i].eventParamRef->EventClass->FailureCycleRef) == operationCycleId) && (TRUE == eventStatusBuffer[i].passedDuringFailureCycle) && (FALSE == eventStatusBuffer[i].failedDuringFailureCycle) ) { /* @dev DEM: Spec. does not say when this counter should be cleared */ if( 0 != eventStatusBuffer[i].failureCounter ) { eventStatusBuffer[i].failureCounter = 0; storeEvtMem = TRUE; } } #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_OperationCycleEnd(operationCycleId, &eventStatusBuffer[i]); #endif if( oldStatus != eventStatusBuffer[i].eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventStatusBuffer[i].eventParamRef, oldStatus, eventStatusBuffer[i].eventStatusExtended); } if( TRUE == storeEvtMem ) { /* Transfer to event memory. */ if( E_OK == storeEventEvtMem(eventStatusBuffer[i].eventParamRef, &eventStatusBuffer[i], FALSE) ) { notifyEventDataChanged(eventStatusBuffer[i].eventParamRef); } } } } #if defined(DEM_USE_INDICATORS) if( TRUE == indicatorsUpdated ) { #ifdef DEM_USE_MEMORY_FUNCTIONS /* IMPROVEMENT: Immediate storage? */ Dem_NvM_SetIndicatorBlockChanged(FALSE); #endif } #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) if( TRUE == permanentMemoryUpdated ) { /* DTC was deleted from permanent memory. Check if we should store some other DTC */ boolean immediateStorage = transferEventToPermanent(nofErasedPermanentDTCs); Dem_NvM_SetPermanentBlockChanged(immediateStorage); } #endif } /* * Procedure: setOperationCycleState * Description: Change the operation state of "operationCycleId" to "cycleState" and updates stored * event connected to this cycle id. * Returns E_OK if operation was successful else E_NOT_OK. */ static Std_ReturnType setOperationCycleState(Dem_OperationCycleIdType operationCycleId, Dem_OperationCycleStateType cycleState) /** @req DEM338 */ { Std_ReturnType returnCode = E_OK; /* @req DEM338 */ if (operationCycleId < DEM_OPERATION_CYCLE_ID_ENDMARK) { switch (cycleState) { case DEM_CYCLE_STATE_START: /* @req DEM483 */ operationCycleStart(operationCycleId); break; case DEM_CYCLE_STATE_END: if(operationCycleStateList[operationCycleId] != DEM_CYCLE_STATE_END) { /* @req DEM484 */ operationCycleEnd(operationCycleId); #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) && defined(DEM_USE_MEMORY_FUNCTIONS) (void)handleAging(operationCycleId); #endif } break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_SETOPERATIONCYCLESTATE_ID, DEM_E_PARAM_DATA); returnCode = E_NOT_OK; break; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_SETOPERATIONCYCLESTATE_ID, DEM_E_PARAM_DATA); returnCode = E_NOT_OK; } return returnCode; } static inline void initEventStatusBuffer(const Dem_EventParameterType *eventIdParamList) { // Insert all supported events into event status buffer const Dem_EventParameterType *eventParam = eventIdParamList; EventStatusRecType *eventStatusRecPtr; while( FALSE == eventParam->Arc_EOL ) { // Find next free position in event status buffer lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); if(NULL != eventStatusRecPtr) { eventStatusRecPtr->eventId = eventParam->EventID; eventStatusRecPtr->eventParamRef = eventParam; sint8 startUdsFdc = getDefaultUDSFdc(eventParam->EventID); eventStatusRecPtr->UDSFdc = startUdsFdc;/* @req DEM438 */ eventStatusRecPtr->maxUDSFdc = startUdsFdc; eventStatusRecPtr->fdcInternal = 0; eventStatusRecPtr->isAvailable = *eventParam->EventClass->EventAvailableByCalibration; if(FALSE == eventStatusRecPtr->isAvailable) { eventStatusRecPtr->eventStatusExtended = 0x0u; } #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) /* Check if suppression of DTC is affected */ boolean suppressed = TRUE; const Dem_EventParameterType *dtcEventParam; if( (NULL != eventParam->DTCClassRef) && (NULL != eventParam->DTCClassRef->Events) ) { for( uint16 i = 0; (i < eventParam->DTCClassRef->NofEvents) && (TRUE == suppressed); i++ ) { dtcEventParam = NULL; lookupEventIdParameter(eventParam->DTCClassRef->Events[i], &dtcEventParam); if( (NULL != dtcEventParam) && (TRUE == *dtcEventParam->EventClass->EventAvailableByCalibration) ) { /* Event is available -> DTC NOT suppressed */ suppressed = FALSE; } } if( 0 != eventParam->DTCClassRef->NofEvents ) { DemDTCSuppressed[eventParam->DTCClassRef->DTCIndex].SuppressedByEvent = suppressed; } } #endif } eventParam++; } } #if ( DEM_FF_DATA_IN_PRE_INIT ) static inline void initPreInitFreezeFrameBuffer(void) { for (uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRE_INIT; i++) { preInitFreezeFrameBuffer[i].eventId = DEM_EVENT_ID_NULL; preInitFreezeFrameBuffer[i].dataSize = 0; #if (DEM_USE_TIMESTAMPS == STD_ON) preInitFreezeFrameBuffer[i].timeStamp = 0; #endif for (uint16 j = 0; j < DEM_MAX_SIZE_FF_DATA;j++){ preInitFreezeFrameBuffer[i].data[j] = 0; } } } #endif static inline void initPreInitExtDataBuffer(void) { #if ( DEM_EXT_DATA_IN_PRE_INIT ) for (uint16 i = 0; i < DEM_MAX_NUMBER_EXT_DATA_PRE_INIT; i++) { #if (DEM_USE_TIMESTAMPS == STD_ON) preInitExtDataBuffer[i].timeStamp = 0; #endif preInitExtDataBuffer[i].eventId = DEM_EVENT_ID_NULL; for (uint16 j = 0; j < DEM_MAX_SIZE_EXT_DATA;j++){ preInitExtDataBuffer[i].data[j] = 0; } } #endif } #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) static inline void initEnableConditions(void) { /* Initialize the enable conditions */ const Dem_EnableConditionType *enableCondition = configSet->EnableCondition; while( enableCondition->EnableConditionID != DEM_ENABLE_CONDITION_EOL) { DemEnableConditions[enableCondition->EnableConditionID] = enableCondition->EnableConditionStatus; enableCondition++; } } #endif #ifdef DEM_USE_MEMORY_FUNCTIONS static boolean validateFreezeFrames(FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin) { /* IMPROVEMENT: Delete OBD freeze frames if the event is not emission related */ boolean freezeFrameBlockChanged = FALSE; // Validate freeze frame records stored in primary memory for (uint32 i = 0u; i < freezeFrameBufferSize; i++) { if ((freezeFrameBuffer[i].eventId == DEM_EVENT_ID_NULL) || (FALSE == checkEntryValid(freezeFrameBuffer[i].eventId, origin, TRUE))) { // Unlegal record, clear the record memset(&freezeFrameBuffer[i], 0, sizeof(FreezeFrameRecType)); freezeFrameBlockChanged = TRUE; } } return freezeFrameBlockChanged; } static boolean validateExtendedData(ExtDataRecType* extendedDataBuffer, uint32 extendedDataBufferSize, Dem_DTCOriginType origin) { boolean extendedDataBlockChanged = FALSE; for (uint32 i = 0uL; i < extendedDataBufferSize; i++) { if ((extendedDataBuffer[i].eventId == DEM_EVENT_ID_NULL) || (FALSE == checkEntryValid(extendedDataBuffer[i].eventId, origin, TRUE))) { // Unlegal record, clear the record memset(&extendedDataBuffer[i], 0, sizeof(ExtDataRecType)); extendedDataBlockChanged = TRUE; } } return extendedDataBlockChanged; } #endif /* DEM_USE_MEMORY_FUNCTIONS */ /** * Looks for freeze frame data for a specific record number (a specific record or the most recent). Returns pointer to data, * the record number found and the type of freeze frame data (OBD or NON-OBD) * @param eventParam * @param recNum * @param freezeFrameData * @param ffRecNumFound * @param ffKind * @return TRUE: freeze frame data found, FALSE: freeze frame data not found */ static boolean getFFRecData(const Dem_EventParameterType *eventParam, uint8 recNum, uint8 **freezeFrameData, uint8 *ffRecNumFound, Dem_FreezeFrameKindType *ffKind) { boolean isStored = FALSE; uint8 nofStoredRecord = 0; uint8 recordToFind = recNum; boolean failed = FALSE; if( (NULL != eventParam->FreezeFrameClassRefIdx) && (*(eventParam->FreezeFrameClassRefIdx) != DEM_FF_NULLREF) && (NULL != eventParam->FreezeFrameRecNumClassRef) ) { if( MOST_RECENT_FF_RECORD == recNum ) { /* Should find the most recent record */ if(E_OK == getNofStoredNonOBDFreezeFrames(eventParam, eventParam->EventClass->EventDestination, &nofStoredRecord)){ if( 0 == nofStoredRecord ) { failed = TRUE; } else { recordToFind = eventParam->FreezeFrameRecNumClassRef->FreezeFrameRecordNumber[nofStoredRecord - 1]; } } } if( FALSE == failed ) { /* Have a record number to look for */ FreezeFrameRecType *freezeFrame = NULL; if((TRUE == getStoredFreezeFrame(eventParam->EventID, recordToFind, eventParam->EventClass->EventDestination, &freezeFrame)) && (NULL != freezeFrame)) { *freezeFrameData = freezeFrame->data; *ffKind = DEM_FREEZE_FRAME_NON_OBD; isStored = TRUE; } } } else { #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) /* Could be OBD... */ recordToFind = 0; /* Always 0 for OBD freeze frame */ if( (NULL != configSet->GlobalOBDFreezeFrameClassRef) && (NULL != eventParam->DTCClassRef) && (DEM_NON_EMISSION_RELATED != (Dem_Arc_EventDTCKindType) *(eventParam->EventDTCKind))) { /* Event is event related */ if( (0 == recNum) || (MOST_RECENT_FF_RECORD == recNum) ) { /*find the corresponding FF in FF buffer*/ for(uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM; i++){ if((DEM_FREEZE_FRAME_OBD == priMemFreezeFrameBuffer[i].kind) && (priMemFreezeFrameBuffer[i].eventId == eventParam->EventID)){ *freezeFrameData = priMemFreezeFrameBuffer[i].data; *ffKind = DEM_FREEZE_FRAME_OBD; isStored = TRUE; break; } } } } #endif } *ffRecNumFound = recordToFind; return isStored; } /** * Checks if an event may be cleared * @param eventParam * @return TRUE: Event may be cleared, FALSE: Event may NOT be cleared */ static boolean clearEventAllowed(const Dem_EventParameterType *eventParam) { boolean clearAllowed = TRUE; /* @req DEM514 */ if(NULL != eventParam->CallbackClearEventAllowed) { /* @req DEM515 */ if( E_OK != eventParam->CallbackClearEventAllowed(&clearAllowed)) { /* @req DEM516 */ clearAllowed = TRUE; } } return clearAllowed; } //==============================================================================// // // // E X T E R N A L F U N C T I O N S // // // //==============================================================================// /********************************************* * Interface for upper layer modules (8.3.1) * *********************************************/ /* * Procedure: Dem_GetVersionInfo * Reentrant: Yes */ // Defined in Dem.h /*********************************************** * Interface ECU State Manager <-> DEM (8.3.2) * ***********************************************/ #if defined(DEM_USE_INDICATORS) static void initIndicatorStatusBuffer(const Dem_EventParameterType *eventIdParamList) { uint16 indx = 0; while( FALSE == eventIdParamList[indx].Arc_EOL ) { if( NULL != eventIdParamList[indx].EventClass->IndicatorAttribute ) { const Dem_IndicatorAttributeType *indAttrPtr = eventIdParamList[indx].EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL) { indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].EventID = eventIdParamList[indx].EventID; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].InternalIndicatorId = indAttrPtr->IndicatorBufferIndex; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].FailureCounter = 0; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].HealingCounter = 0; indicatorStatusBuffer[indAttrPtr->IndicatorBufferIndex].OpCycleStatus = 0; indAttrPtr++; } } indx++; } } #endif #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) /** * Validates configured NvM block sizes */ /*lint --e{522} CONFIGURATION */ static void validateNvMBlockSizes(void) { /* Check sizes of used NvM blocks */ #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) DEM_ASSERT( (0 == DEM_EVENT_PRIMARY_NVM_BLOCK_HANDLE) || (DEM_EVENT_PRIMARY_NVM_BLOCK_SIZE == sizeof(priMemEventBuffer)));/*lint !e506 CONFIGURATION */ #if ( DEM_FF_DATA_IN_PRI_MEM ) DEM_ASSERT( (0 == DEM_FREEZE_FRAME_PRIMARY_NVM_BLOCK_HANDLE) || (DEM_FREEZE_FRAME_PRIMARY_NVM_BLOCK_SIZE == sizeof(priMemFreezeFrameBuffer)));/*lint !e506 CONFIGURATION */ #endif #if ( DEM_EXT_DATA_IN_PRI_MEM ) DEM_ASSERT( (0 == DEM_EXTENDED_DATA_PRIMARY_NVM_BLOCK_HANDLE) || (DEM_EXTENDED_DATA_PRIMARY_NVM_BLOCK_SIZE == sizeof(priMemExtDataBuffer)));/*lint !e506 CONFIGURATION */ #endif #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) DEM_ASSERT( (0 == DEM_EVENT_SECONDARY_NVM_BLOCK_HANDLE) || (DEM_EVENT_SECONDARY_NVM_BLOCK_SIZE == sizeof(secMemEventBuffer)));/*lint !e506 CONFIGURATION */ #if ( DEM_FF_DATA_IN_SEC_MEM ) DEM_ASSERT( (0 == DEM_FREEZE_FRAME_SECONDARY_NVM_BLOCK_HANDLE) || (DEM_FREEZE_FRAME_SECONDARY_NVM_BLOCK_SIZE == sizeof(secMemFreezeFrameBuffer)));/*lint !e506 CONFIGURATION */ #endif #if ( DEM_EXT_DATA_IN_SEC_MEM ) DEM_ASSERT( (0 == DEM_EXTENDED_DATA_SECONDARY_NVM_BLOCK_HANDLE ) || (DEM_EXTENDED_DATA_SECONDARY_NVM_BLOCK_SIZE == sizeof(secMemExtDataBuffer)));/*lint !e506 CONFIGURATION */ #endif #endif #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) DEM_ASSERT( (0 == DEM_INDICATOR_NVM_BLOCK_HANDLE ) || (DEM_INDICATOR_NVM_BLOCK_SIZE == sizeof(indicatorBuffer)));/*lint !e506 CONFIGURATION */ #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) DEM_ASSERT( (0 == DEM_PERMANENT_NVM_BLOCK_HANDLE ) || (DEM_PERMANENT_NVM_BLOCK_SIZE == sizeof(permMemEventBuffer)));/*lint !e506 CONFIGURATION */ #endif #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) DEM_ASSERT( (0 == DEM_PRESTORE_FF_NVM_BLOCK_HANDLE ) || (DEM_PRESTORE_FF_NVM_BLOCK_SIZE == sizeof(memPreStoreFreezeFrameBuffer)));/*lint !e506 CONFIGURATION */ #endif } #endif /* * Procedure: Dem_PreInit * Reentrant: No */ void Dem_PreInit(const Dem_ConfigType *ConfigPtr) { /** @req DEM180 */ uint16 i; VALIDATE_NO_RV(ConfigPtr != NULL, DEM_PREINIT_ID, DEM_E_CONFIG_PTR_INVALID); VALIDATE_NO_RV(ConfigPtr->ConfigSet != NULL, DEM_PREINIT_ID, DEM_E_CONFIG_PTR_INVALID); #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) validateNvMBlockSizes(); #endif configSet = ConfigPtr->ConfigSet; #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) const Dem_DTCClassType *DTCClass = configSet->DTCClass; while(FALSE == DTCClass->Arc_EOL) { DemDTCSuppressed[DTCClass->DTCIndex].SuppressedByDTC = FALSE; DemDTCSuppressed[DTCClass->DTCIndex].SuppressedByEvent = FALSE; DTCClass++; } #endif // Initializion of operation cycle states. for (i = 0; i < DEM_OPERATION_CYCLE_ID_ENDMARK; i++) { operationCycleStateList[i] = DEM_CYCLE_STATE_END; } // Initialize the event status buffer for (i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { setDefaultEventStatus(&eventStatusBuffer[i]); } #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) InitTimeBasedDebounce(); #endif #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) && defined(DEM_USE_MEMORY_FUNCTIONS) SetDefaultUDSStatusBitSubset(); #endif // Initialize the eventstatus buffer (Insert all supported events into event status buffer) initEventStatusBuffer(configSet->EventParameter); /* Initialize the preInit freeze frame buffer */ #if( DEM_FF_DATA_IN_PRE_INIT ) initPreInitFreezeFrameBuffer(); #endif /* Initialize the preInit extended data buffer */ initPreInitExtDataBuffer(); #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) /* Initialize the enable conditions */ initEnableConditions(); #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_PreInit(ConfigPtr); #endif #if (DEM_USE_TIMESTAMPS == STD_ON) /* Reset freze frame time stamp */ FF_TimeStamp = 0; /* Reset event time stamp */ Event_TimeStamp = 0; /* Reset extended data timestamp */ ExtData_TimeStamp = 0; #endif #if defined(DEM_USE_INDICATORS) initIndicatorStatusBuffer(configSet->EventParameter); #endif disableDtcSetting.settingDisabled = FALSE; (void)setOperationCycleState(DEM_ACTIVE, DEM_CYCLE_STATE_START); /* Init the DTC record update disable */ DTCRecordDisabled.DTC = NO_DTC_DISABLED; #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) priMemOverflow = FALSE; #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) secMemOverflow = FALSE; #endif Dem_NvM_Init(); #if defined(USE_FIM) DemFiMInit = FALSE; #endif demState = DEM_PREINITIALIZED; } #ifdef DEM_USE_MEMORY_FUNCTIONS static boolean ValidateAndMergeEventRecords(EventRecType* eventBuffer, uint32 eventBufferSize, boolean* eventEntryChanged, uint32* Evt_TimeStamp, Dem_DTCOriginType origin ) { boolean eventBlockChanged = FALSE; uint32 i; // Validate event records stored in memory for (i = 0; i < eventBufferSize; i++) { eventEntryChanged[i] = FALSE; if ((eventBuffer[i].EventData.eventId == DEM_EVENT_ID_NULL) || (checkEntryValid(eventBuffer[i].EventData.eventId, origin, FALSE) == FALSE )) { // Unlegal record, clear the record memset(&eventBuffer[i], 0, sizeof(EventRecType)); eventBlockChanged = TRUE; } } #if (DEM_USE_TIMESTAMPS == STD_ON) /* initialize the current timestamp and update the timestamp in pre init */ initCurrentEventTimeStamp(Evt_TimeStamp); #else (void)Evt_TimeStamp;/*lint !e920 *//* Avoid compiler warning */ #endif /* Merge events read from NvRam */ for (i = 0; i < eventBufferSize; i++) { eventEntryChanged[i] = FALSE; if( DEM_EVENT_ID_NULL != eventBuffer[i].EventData.eventId ) { eventEntryChanged[i] = mergeEventStatusRec(&eventBuffer[i]); } } return eventBlockChanged; } static void MergeBuffer(Dem_DTCOriginType origin) { uint32 i; boolean eventBlockChanged; boolean extendedDataBlockChanged; boolean freezeFrameBlockChanged; boolean eventEntryChanged[DEM_MAX_NUMBER_EVENT_ENTRY] = {FALSE};/*lint !e506 */ const Dem_EventParameterType *eventParam; EventRecType* eventBuffer = NULL; uint32 eventBufferSize = 0; FreezeFrameRecType* freezeFrameBuffer = NULL; uint32 freezeFrameBufferSize = 0; ExtDataRecType* extendedDataBuffer = NULL; uint32 extendedDataBufferSize = 0; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) boolean immediateEventStorage = FALSE; boolean immediateFFStorage = FALSE; boolean immediateExtDataStorage = FALSE; #endif /* Setup variables for merging */ switch (origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) eventBuffer = priMemEventBuffer; eventBufferSize = DEM_MAX_NUMBER_EVENT_PRI_MEM; #if ( DEM_FF_DATA_IN_PRI_MEM ) freezeFrameBuffer = priMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; #endif #if ( DEM_EXT_DATA_IN_PRI_MEM ) extendedDataBuffer = priMemExtDataBuffer; extendedDataBufferSize = DEM_MAX_NUMBER_EXT_DATA_PRI_MEM; #endif #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) eventBuffer = secMemEventBuffer; eventBufferSize = DEM_MAX_NUMBER_EVENT_SEC_MEM; #if ( DEM_FF_DATA_IN_SEC_MEM ) freezeFrameBuffer = secMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_SEC_MEM; #endif #if ( DEM_EXT_DATA_IN_SEC_MEM ) extendedDataBuffer = secMemExtDataBuffer; extendedDataBufferSize = DEM_MAX_NUMBER_EXT_DATA_SEC_MEM; #endif #endif break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; } #if (DEM_USE_TIMESTAMPS != STD_ON) /* The timestamp isn't actually used. This just to make it compile.. */ uint32 Event_TimeStamp = 0; #endif eventBlockChanged = ValidateAndMergeEventRecords(eventBuffer, eventBufferSize, eventEntryChanged, &Event_TimeStamp, origin); #if defined(USE_DEM_EXTENSION) Dem_Extension_Init_PostEventMerge(origin); #endif #if (DEM_USE_TIMESTAMPS == STD_ON) //initialize the current timestamp and update the timestamp in pre init initCurrentFreezeFrameTimeStamp(&FF_TimeStamp); #endif /* Validate freeze frames stored in memory */ freezeFrameBlockChanged = validateFreezeFrames(freezeFrameBuffer, freezeFrameBufferSize, origin); /* Transfer updated event data to event memory */ for (i = 0u; (i < eventBufferSize) && (NULL != eventBuffer); i++) { if ( (eventBuffer[i].EventData.eventId != DEM_EVENT_ID_NULL) && (TRUE == eventEntryChanged[i]) ) { EventStatusRecType *eventStatusRecPtr = NULL; eventParam = NULL; lookupEventIdParameter(eventBuffer[i].EventData.eventId, &eventParam); /* Transfer to event memory. */ lookupEventStatusRec(eventBuffer[i].EventData.eventId, &eventStatusRecPtr); if( (NULL != eventStatusRecPtr) && (NULL != eventParam) ) { if( E_OK == storeEventEvtMem(eventParam, eventStatusRecPtr, FALSE) ) { /* Use errorStatusChanged in eventsStatusBuffer to signal that the event data was updated */ eventStatusRecPtr->errorStatusChanged = TRUE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRecPtr->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateEventStorage = TRUE; } #endif } } } } /* Now we need to store events that was reported during preInit. * That is, events not already stored in eventBuffer. */ for (i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if( (DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) && (0 == (eventStatusBuffer[i].eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE)) && (FALSE == eventIsStoredInMem(eventStatusBuffer[i].eventId, eventBuffer, eventBufferSize)) ) { lookupEventIdParameter(eventStatusBuffer[i].eventId, &eventParam); if( (NULL != eventParam) && (eventParam->EventClass->EventDestination == origin)) { /* Destination check is needed two avoid notifying status change twice */ notifyEventStatusChange(eventParam, DEM_DEFAULT_EVENT_STATUS, eventStatusBuffer[i].eventStatusExtended); } if( 0 != (eventStatusBuffer[i].eventStatusExtended & DEM_TEST_FAILED_THIS_OPERATION_CYCLE) ) { if( E_OK == storeEventEvtMem(eventParam, &eventStatusBuffer[i], FALSE) ) { /* Use errorStatusChanged in eventsStatusBuffer to signal that the event data was updated */ eventStatusBuffer[i].errorStatusChanged = TRUE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL != eventParam) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusBuffer[i].occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateEventStorage = TRUE; } #endif } } } } // Validate extended data records stored in primary memory extendedDataBlockChanged = validateExtendedData(extendedDataBuffer, extendedDataBufferSize, origin); #if (DEM_USE_TIMESTAMPS == STD_ON) //initialize the current timestamp and update the timestamp in pre init initCurrentExtDataTimeStamp(&ExtData_TimeStamp); #endif #if ( DEM_EXT_DATA_IN_PRE_INIT ) /* Transfer extended data to event memory if necessary */ for (i = 0; i < DEM_MAX_NUMBER_EXT_DATA_PRE_INIT; i++) { if ( preInitExtDataBuffer[i].eventId != DEM_EVENT_ID_NULL ) { boolean updateAllExtData = FALSE; #if defined(USE_DEM_EXTENSION) Dem_Extension_PreMergeExtendedData(preInitExtDataBuffer[i].eventId, &updateAllExtData); #endif if( TRUE == mergeExtendedDataEvtMem(&preInitExtDataBuffer[i], extendedDataBuffer, extendedDataBufferSize, origin, updateAllExtData) ) { /* Use errorStatusChanged in eventsStatusBuffer to signal that the event data was updated */ EventStatusRecType *eventStatusRecPtr = NULL_PTR; eventParam = NULL_PTR; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) /* Event id may be a combined id. */ if( IS_COMBINED_EVENT_ID(preInitExtDataBuffer[i].eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(preInitExtDataBuffer[i].eventId)]; CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(preInitExtDataBuffer[i].eventId)]; /* Just grab the first event for this DTC. */ lookupEventIdParameter(CombDTCCfg->DTCClassRef->Events[0u], &eventParam); } else { lookupEventIdParameter(preInitExtDataBuffer[i].eventId, &eventParam); } #else lookupEventIdParameter(preInitExtDataBuffer[i].eventId, &eventParam); #endif if( NULL_PTR != eventParam ) { lookupEventStatusRec(eventParam->EventID, &eventStatusRecPtr); } if( NULL_PTR != eventStatusRecPtr ) { eventStatusRecPtr->errorStatusChanged = TRUE; #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) if( (NULL_PTR != eventParam) && (NULL != eventParam->DTCClassRef) && (TRUE == eventParam->DTCClassRef->DTCRef->ImmediateNvStorage) && (eventStatusRecPtr->occurrence <= DEM_IMMEDIATE_NV_STORAGE_LIMIT)) { immediateExtDataStorage = TRUE; } #endif } } } } #endif /* Transfer freeze frames stored during preInit to event memory */ #if ( DEM_FF_DATA_IN_PRE_INIT ) if( TRUE == transferPreInitFreezeFramesEvtMem(freezeFrameBuffer, freezeFrameBufferSize, eventBuffer, eventBufferSize, origin) ){ freezeFrameBlockChanged = TRUE; } #endif if( TRUE == eventBlockChanged ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) Dem_NvM_SetEventBlockChanged(origin, immediateEventStorage); #else Dem_NvM_SetEventBlockChanged(origin, FALSE); #endif } if( TRUE == extendedDataBlockChanged ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) Dem_NvM_SetExtendedDataBlockChanged(origin, immediateExtDataStorage); #else Dem_NvM_SetExtendedDataBlockChanged(origin, FALSE); #endif } if( TRUE == freezeFrameBlockChanged ) { #if defined(DEM_USE_IMMEDIATE_NV_STORAGE) /* IMPROVEMENT: Immediate storage */ Dem_NvM_SetFreezeFrameBlockChanged(origin, immediateFFStorage); #else Dem_NvM_SetFreezeFrameBlockChanged(origin, FALSE); #endif } } #if (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) /** * Set the default value for UDS status bit subset if buffer is considered * invalid. */ static void SetDefaultUDSStatusBitSubset(void) { if( UDS_STATUS_BIT_MAGIC != statusBitSubsetBuffer[UDS_STATUS_BIT_MAGIC_INDEX] ) { memset(statusBitSubsetBuffer, 0u, sizeof(statusBitSubsetBuffer)); for(Dem_EventIdType i = (Dem_EventIdType)0u; i < DEM_MAX_NUMBER_EVENT; i++) { statusBitSubsetBuffer[GET_UDSBIT_BYTE_INDEX(i+1u)] |= 1u<<(GET_UDS_STARTBIT(i+1u) + UDS_TNCSLC_BIT); } } } /** * Merges UDS status bit subset to event buffer */ static void MergeUDSStatusBitSubset(void) { EventStatusRecType *eventStatusRec; if( UDS_STATUS_BIT_MAGIC == statusBitSubsetBuffer[UDS_STATUS_BIT_MAGIC_INDEX] ) { for(Dem_EventIdType i = (Dem_EventIdType)0; i < DEM_MAX_NUMBER_EVENT; i++) { eventStatusRec = NULL; lookupEventStatusRec(i + 1u, &eventStatusRec); if( (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable) ) { if( 0 == (statusBitSubsetBuffer[GET_UDSBIT_BYTE_INDEX(i+1u)] & (1u<<(GET_UDS_STARTBIT(i+1u) + UDS_TNCSLC_BIT))) ) { eventStatusRec->eventStatusExtended &= ~(DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR); } if( 0 != (statusBitSubsetBuffer[GET_UDSBIT_BYTE_INDEX(i+1u)] & (1u<<(GET_UDS_STARTBIT(i+1u) + UDS_TFSLC_BIT))) ) { eventStatusRec->eventStatusExtended |= DEM_TEST_FAILED_SINCE_LAST_CLEAR; } } } } } /** * Transfers subset of UDS status bits from event buffer to buffer for NvM storage */ static void StoreUDSStatusBitSubset(void) { Dem_EventStatusExtendedType eventStatus; const Dem_EventParameterType *eventParam; memset(statusBitSubsetBuffer, 0u, sizeof(statusBitSubsetBuffer)); for(Dem_EventIdType i = (Dem_EventIdType)0; i < DEM_MAX_NUMBER_EVENT; i++) { if(E_OK == getEventStatus(i + 1u, &eventStatus)) { eventParam = NULL; lookupEventIdParameter(i + 1u, &eventParam); if( (NULL != eventParam) && (DEM_DTC_ORIGIN_NOT_USED != eventParam->EventClass->EventDestination)) { if( 0 != (eventStatus & DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR) ) { statusBitSubsetBuffer[GET_UDSBIT_BYTE_INDEX(i+1u)] |= 1u<<(GET_UDS_STARTBIT(i+1u) + UDS_TNCSLC_BIT); } if( 0 != (eventStatus & DEM_TEST_FAILED_SINCE_LAST_CLEAR) ) { statusBitSubsetBuffer[GET_UDSBIT_BYTE_INDEX(i+1u)] |= 1u<<(GET_UDS_STARTBIT(i+1u) + UDS_TFSLC_BIT); } } } } statusBitSubsetBuffer[UDS_STATUS_BIT_MAGIC_INDEX] = UDS_STATUS_BIT_MAGIC; /* IPROVEMENT: Immediate storage? */ Dem_NvM_SetStatusBitSubsetBlockChanged(FALSE); } #endif #endif /* DEM_USE_MEMORY_FUNCTIONS */ #if defined(DEM_USE_IUMPR) static void mergeIumprBuffer(void) { for (Dem_RatioIdType i = 0; i < DEM_IUMPR_REGISTERED_COUNT; i++) { iumprBufferLocal[i].denominator.value = iumprBuffer.ratios[i].denominator; iumprBufferLocal[i].numerator.value = iumprBuffer.ratios[i].numerator; } generalDenominatorBuffer.value = iumprBuffer.generalDenominatorCount; ignitionCycleCountBuffer = iumprBuffer.ignitionCycleCount; } static void storeIumprBuffer(void) { for (Dem_RatioIdType i = 0; i < DEM_IUMPR_REGISTERED_COUNT; i++) { iumprBuffer.ratios[i].denominator = iumprBufferLocal[i].denominator.value; iumprBuffer.ratios[i].numerator = iumprBufferLocal[i].numerator.value; } iumprBuffer.generalDenominatorCount = generalDenominatorBuffer.value; iumprBuffer.ignitionCycleCount = ignitionCycleCountBuffer; Dem_Nvm_SetIumprBlockChanged(TRUE); } #endif /* * Procedure: Dem_Init * Reentrant: No */ void Dem_Init(void) { /* @req DEM340 */ //// SchM_Enter_Dem_EA_0(); for(uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { eventStatusBuffer[i].errorStatusChanged = FALSE; } if(DEM_PREINITIALIZED != demState) { /* * Dem_PreInit was has not been called since last time Dem_Shutdown was called. * This suggests that we are resuming from sleep. According to section 5.7 in * EcuM specification, RAM content is assumed to be still valid from the previous cycle. * Do not read from saved error log since buffers already contains this data. */ (void)setOperationCycleState(DEM_ACTIVE, DEM_CYCLE_STATE_START); } else { #if defined(DEM_USE_MEMORY_FUNCTIONS) && (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) MergeUDSStatusBitSubset(); #endif #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) mergeIndicatorBuffers(); #endif #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) MergeBuffer(DEM_DTC_ORIGIN_PRIMARY_MEMORY); #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) MergeBuffer(DEM_DTC_ORIGIN_SECONDARY_MEMORY); #endif #if (DEM_USE_PERMANENT_MEMORY_SUPPORT == STD_ON) ValidateAndUpdatePermanentBuffer(); #endif #if (DEM_PRESTORAGE_FF_DATA_IN_MEM) ValidateAndUpdatePreStoredFreezeFramesBuffer(); #endif } #if defined(USE_FIM) /* @req 4.3.0/SWS_Dem_01189 */ if( FALSE == DemFiMInit ) { FiM_DemInit(); DemFiMInit = TRUE; } #endif /* Notify application if event data was updated */ for(uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { /* @req DEM475 */ if( 0 != eventStatusBuffer[i].errorStatusChanged ) { notifyEventDataChanged(eventStatusBuffer[i].eventParamRef); eventStatusBuffer[i].errorStatusChanged = FALSE; } } #if defined(USE_DEM_EXTENSION) Dem_Extension_Init_Complete(); #endif #if (DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) if(ADMIN_MAGIC == priMemEventBuffer[PRI_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.magic) { priMemOverflow = priMemEventBuffer[PRI_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow; } #endif #if (DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) if(ADMIN_MAGIC == secMemEventBuffer[SEC_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.magic) { secMemOverflow = secMemEventBuffer[SEC_MEM_EVENT_BUFFER_ADMIN_INDEX].AdminData.overflow; } #endif // Init the dtc filter dtcFilter.dtcStatusMask = DEM_DTC_STATUS_MASK_ALL; // All allowed dtcFilter.dtcKind = DEM_DTC_KIND_ALL_DTCS; // All kinds of DTCs dtcFilter.dtcOrigin = DEM_DTC_ORIGIN_PRIMARY_MEMORY; // Primary memory dtcFilter.filterWithSeverity = DEM_FILTER_WITH_SEVERITY_NO; // No Severity filtering dtcFilter.dtcSeverityMask = DEM_SEVERITY_NO_SEVERITY; // Not used when filterWithSeverity is FALSE dtcFilter.filterForFaultDetectionCounter = DEM_FILTER_FOR_FDC_NO; // No fault detection counter filtering dtcFilter.DTCIndex = 0u; disableDtcSetting.settingDisabled = FALSE; ffRecordFilter.ffIndex = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; ffRecordFilter.dtcFormat = 0xff; #if defined(DEM_USE_IUMPR) mergeIumprBuffer(); initIumprAddiDenomCondBuffer(); #endif demState = DEM_INITIALIZED; //// SchM_Exit_Dem_EA_0(); } /* * Procedure: Dem_shutdown * Reentrant: No */ void Dem_Shutdown(void) { VALIDATE_NO_RV(DEM_INITIALIZED == demState, DEM_SHUTDOWN_ID, DEM_E_UNINIT); /* @req DEM102 */ SchM_Enter_Dem_EA_0(); (void)setOperationCycleState(DEM_ACTIVE, DEM_CYCLE_STATE_END); #if defined(DEM_USE_MEMORY_FUNCTIONS) && (DEM_STORE_UDS_STATUS_BIT_SUBSET_FOR_ALL_EVENTS == STD_ON) StoreUDSStatusBitSubset(); #endif #if defined(DEM_USE_IUMPR) storeIumprBuffer(); #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_Shutdown(); #endif demState = DEM_SHUTDOWN; /** @req DEM368 */ SchM_Exit_Dem_EA_0(); } /* * Interface for basic software scheduler */ void Dem_MainFunction(void)/** @req DEM125 */ { VALIDATE_NO_RV(DEM_UNINITIALIZED != demState, DEM_MAINFUNCTION_ID, DEM_E_UNINIT); #ifdef DEM_USE_MEMORY_FUNCTIONS Dem_NvM_MainFunction(); #endif /* DEM_USE_MEMORY_FUNCTIONS */ #if defined(USE_DEM_EXTENSION) Dem_Extension_MainFunction(); #endif #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) /* Handle time based predebounce */ TimeBasedDebounceMainFunction(); #endif } /** * Gets the indicator status derived from the event status * @param IndicatorId * @param IndicatorStatus * @return E_OK: Operation was successful, E_NOT_OK: Operation failed or is not supported */ /*lint -efunc(818,Dem_GetIndicatorStatus) Dem_IndicatorStatusType cannot be declared as pointing to const as API defined by AUTOSAR */ Std_ReturnType Dem_GetIndicatorStatus( uint8 IndicatorId, Dem_IndicatorStatusType* IndicatorStatus ) { /* @req DEM046 */ /* @req DEM508 */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETINDICATORSTATUS_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(NULL != IndicatorStatus, DEM_GETINDICATORSTATUS_ID, DEM_E_PARAM_POINTER, E_NOT_OK); #if defined(DEM_USE_INDICATORS) VALIDATE_RV(DEM_NOF_INDICATORS > IndicatorId, DEM_GETINDICATORSTATUS_ID, DEM_E_PARAM_CONFIG, E_NOT_OK); Std_ReturnType ret = E_NOT_OK; const Dem_IndicatorType *indConfig; const Dem_EventParameterType *eventParam; uint8 currPrio = 0xff; if( IndicatorId < DEM_NOF_INDICATORS ) { indConfig = &configSet->Indicators[IndicatorId]; *IndicatorStatus = DEM_INDICATOR_OFF; for( uint8 indx = 0; indx < indConfig->EventListSize; indx++ ) { eventParam = NULL; lookupEventIdParameter(indConfig->EventList[indx], &eventParam); if( (NULL != eventParam) && (NULL != eventParam->EventClass->IndicatorAttribute) && (TRUE == (boolean)(*eventParam->EventClass->IndicatorAttribute->IndicatorValid)) ) { const Dem_IndicatorAttributeType *indAttrPtr = eventParam->EventClass->IndicatorAttribute; while( FALSE == indAttrPtr->Arc_EOL ) { if( indAttrPtr->IndicatorId == IndicatorId ) { /* Found a match */ ret = E_OK; if( TRUE == indicatorFailFulfilled(eventParam, indAttrPtr) ) { if( eventParam->EventClass->EventPriority < currPrio ) { *IndicatorStatus = indAttrPtr->IndicatorBehaviour; currPrio = eventParam->EventClass->EventPriority; } } } indAttrPtr++; } } } } return ret; #else (void)IndicatorId; DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETINDICATORSTATUS_ID, DEM_E_PARAM_CONFIG); return E_NOT_OK; #endif } /*************************************************** * Interface SW-Components via RTE <-> DEM (8.3.3) * ***************************************************/ /* * Procedure: Dem_SetEventStatus * Reentrant: Yes */ /* @req DEM183 */ Std_ReturnType Dem_SetEventStatus(Dem_EventIdType eventId, Dem_EventStatusType eventStatus) /** @req DEM330 */ { /* @req DEM330 */ Std_ReturnType returnCode = E_NOT_OK; VALIDATE_RV(((DEM_INITIALIZED == demState) || (DEM_SHUTDOWN == demState)), DEM_SETEVENTSTATUS_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(IS_VALID_EVENT_STATUS(eventStatus), DEM_SETEVENTSTATUS_ID, DEM_E_PARAM_DATA, E_NOT_OK); // Ignore this API call after Dem_Shutdown() if (DEM_SHUTDOWN != demState) { SchM_Enter_Dem_EA_0(); returnCode = handleEvent(eventId, eventStatus); SchM_Exit_Dem_EA_0(); } return returnCode; } /* * Procedure: Dem_ResetEventStatus * Reentrant: Yes */ /* @req DEM185 */ Std_ReturnType Dem_ResetEventStatus(Dem_EventIdType eventId) /** @req DEM331 */ { /* @req DEM331 */ Std_ReturnType returnCode; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_RESETEVENTSTATUS_ID, DEM_E_UNINIT, E_NOT_OK); SchM_Enter_Dem_EA_0(); /* Function resetEventStatus will notify application if there is a change in the status bits */ returnCode = resetEventStatus(eventId); SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetEventStatus * Reentrant: Yes */ Std_ReturnType Dem_GetEventStatus(Dem_EventIdType eventId, Dem_EventStatusExtendedType *eventStatusExtended) { Std_ReturnType returnCode; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTSTATUS_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(NULL != eventStatusExtended, DEM_GETEVENTSTATUS_ID, DEM_E_PARAM_POINTER, E_NOT_OK); SchM_Enter_Dem_EA_0(); returnCode = getEventStatus(eventId, eventStatusExtended); SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetEventFailed * Reentrant: Yes */ Std_ReturnType Dem_GetEventFailed(Dem_EventIdType eventId, boolean *eventFailed) /** @req DEM333 */ { /* @req DEM333 */ Std_ReturnType returnCode; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTFAILED_ID, DEM_E_UNINIT, E_NOT_OK); SchM_Enter_Dem_EA_0(); returnCode = getEventFailed(eventId, eventFailed); SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetEventTested * Reentrant: Yes */ Std_ReturnType Dem_GetEventTested(Dem_EventIdType eventId, boolean *eventTested) { /* @req DEM333 */ Std_ReturnType returnCode; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTTESTED_ID, DEM_E_UNINIT, E_NOT_OK); SchM_Enter_Dem_EA_0(); returnCode = getEventTested(eventId, eventTested); SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetFaultDetectionCounter * Reentrant: No */ Std_ReturnType Dem_GetFaultDetectionCounter(Dem_EventIdType eventId, sint8 *counter) { /* @req DEM204 */ Std_ReturnType returnCode; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETFAULTDETECTIONCOUNTER_ID, DEM_E_UNINIT, E_NOT_OK); SchM_Enter_Dem_EA_0(); returnCode = getFaultDetectionCounter(eventId, counter); SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_SetOperationCycleState * Reentrant: No */ Std_ReturnType Dem_SetOperationCycleState(Dem_OperationCycleIdType operationCycleId, Dem_OperationCycleStateType cycleState) { Std_ReturnType returnCode = E_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETOPERATIONCYCLESTATE_ID, DEM_E_UNINIT, E_NOT_OK); SchM_Enter_Dem_EA_0(); if( DEM_ACTIVE == operationCycleId ) { /* Handled internally */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_SETOPERATIONCYCLESTATE_ID, DEM_E_UNEXPECTED_EXECUTION); returnCode = E_NOT_OK; } else { returnCode = setOperationCycleState(operationCycleId, cycleState); } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetDTCOfEvent * Reentrant: Yes */ Std_ReturnType Dem_GetDTCOfEvent(Dem_EventIdType eventId, Dem_DTCFormatType dtcFormat, uint32* dtcOfEvent) { Std_ReturnType returnCode = E_NO_DTC_AVAILABLE; const Dem_EventParameterType *eventParam; EventStatusRecType * eventStatusRec; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETDTCOFEVENT_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(IS_VALID_DTC_FORMAT(dtcFormat), DEM_GETDTCOFEVENT_ID, DEM_E_PARAM_DATA, E_NOT_OK); SchM_Enter_Dem_EA_0(); lookupEventIdParameter(eventId, &eventParam); lookupEventStatusRec(eventId, &eventStatusRec); if ( (eventParam != NULL) && (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable)) { if ((eventParam->DTCClassRef != NULL) && (TRUE == eventParam->DTCClassRef->DTCRef->DTCUsed)) { if( TRUE == eventHasDTCOnFormat(eventParam, dtcFormat) ) { *dtcOfEvent = (DEM_DTC_FORMAT_UDS == dtcFormat) ? eventParam->DTCClassRef->DTCRef->UDSDTC : TO_OBD_FORMAT(eventParam->DTCClassRef->DTCRef->OBDDTC);/** @req DEM269 */ returnCode = E_OK; } } } else { // Event Id not found returnCode = E_NOT_OK; } SchM_Exit_Dem_EA_0(); return returnCode; } /******************************************** * Interface BSW-Components <-> DEM (8.3.4) * ********************************************/ /* * Procedure: Dem_ReportErrorStatus * Reentrant: Yes */ void Dem_ReportErrorStatus( Dem_EventIdType eventId, Dem_EventStatusType eventStatus ) /** @req DEM206 */ { /* @req DEM330 */ /* @req DEM107 */ VALIDATE_NO_RV((DEM_UNINITIALIZED != demState), DEM_REPORTERRORSTATUS_ID, DEM_E_UNINIT); VALIDATE_NO_RV(IS_VALID_EVENT_STATUS(eventStatus), DEM_REPORTERRORSTATUS_ID, DEM_E_PARAM_DATA); SchM_Enter_Dem_EA_0(); switch (demState) { case DEM_PREINITIALIZED: // Update status and check if is to be stored if ((eventStatus == DEM_EVENT_STATUS_PASSED) || (eventStatus == DEM_EVENT_STATUS_FAILED)) { handlePreInitEvent(eventId, eventStatus); /** @req DEM167 */ } break; case DEM_INITIALIZED: (void)handleEvent(eventId, eventStatus); break; case DEM_SHUTDOWN: default: // Ignore api call break; } // switch (demState) SchM_Exit_Dem_EA_0(); } /********************************* * Interface DCM <-> DEM (8.3.5) * *********************************/ /* * Procedure: Dem_GetDTCStatusAvailabilityMask * Reentrant: No */ /*lint -esym(793, Dem_GetDTCStatusAvailabilityMask) Function name defined by AUTOSAR. */ Std_ReturnType Dem_GetDTCStatusAvailabilityMask(uint8 *dtcStatusMask) /** @req DEM014 */ { /** @req DEM060 */ *dtcStatusMask = DEM_DTC_STATUS_AVAILABILITY_MASK; // User configuration mask return E_OK; } /* * Procedure: Dem_SetDTCFilter * Reentrant: No */ Dem_ReturnSetFilterType Dem_SetDTCFilter(uint8 dtcStatusMask, Dem_DTCKindType dtcKind, Dem_DTCFormatType dtcFormat, Dem_DTCOriginType dtcOrigin, Dem_FilterWithSeverityType filterWithSeverity, Dem_DTCSeverityType dtcSeverityMask, Dem_FilterForFDCType filterForFaultDetectionCounter) { Dem_ReturnSetFilterType returnCode = DEM_FILTER_ACCEPTED; uint8 dtcStatusAvailabilityMask; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETDTCFILTER_ID, DEM_E_UNINIT, E_NOT_OK); // Check dtcKind parameter VALIDATE_RV((dtcKind == DEM_DTC_KIND_ALL_DTCS) || (dtcKind == DEM_DTC_KIND_EMISSION_REL_DTCS), DEM_SETDTCFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); // Check dtcOrigin parameter VALIDATE_RV((dtcOrigin == DEM_DTC_ORIGIN_SECONDARY_MEMORY) || (dtcOrigin == DEM_DTC_ORIGIN_PRIMARY_MEMORY)|| (dtcOrigin == DEM_DTC_ORIGIN_PERMANENT_MEMORY), DEM_SETDTCFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); // Check filterWithSeverity and dtcSeverityMask parameter VALIDATE_RV(((filterWithSeverity == DEM_FILTER_WITH_SEVERITY_NO) || ((filterWithSeverity == DEM_FILTER_WITH_SEVERITY_YES) && (0 == (dtcSeverityMask & (Dem_DTCSeverityType)~(DEM_SEVERITY_MAINTENANCE_ONLY | DEM_SEVERITY_CHECK_AT_NEXT_HALT | DEM_SEVERITY_CHECK_IMMEDIATELY))))), DEM_SETDTCFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); // Check filterForFaultDetectionCounter parameter VALIDATE_RV((filterForFaultDetectionCounter == DEM_FILTER_FOR_FDC_YES) || (filterForFaultDetectionCounter == DEM_FILTER_FOR_FDC_NO), DEM_SETDTCFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); VALIDATE_RV( IS_VALID_DTC_FORMAT(dtcFormat), DEM_SETDTCFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); (void)Dem_GetDTCStatusAvailabilityMask(&dtcStatusAvailabilityMask); if( (0u == (dtcStatusMask & dtcStatusAvailabilityMask)) && (DEM_DTC_STATUS_MASK_ALL != dtcStatusMask) ) { /* No bit in the filter mask supported. */ returnCode = DEM_WRONG_FILTER; } else { // Yes all parameters correct, set the new filters. /** @req DEM057 */ dtcFilter.dtcStatusMask = dtcStatusMask & dtcStatusAvailabilityMask; dtcFilter.dtcKind = dtcKind; dtcFilter.dtcOrigin = dtcOrigin; dtcFilter.filterWithSeverity = filterWithSeverity; dtcFilter.dtcSeverityMask = dtcSeverityMask; dtcFilter.filterForFaultDetectionCounter = filterForFaultDetectionCounter; dtcFilter.DTCIndex = 0u; dtcFilter.dtcFormat = dtcFormat; } return returnCode; } /* * Procedure: Dem_GetStatusOfDTC * Reentrant: No */ Dem_ReturnGetStatusOfDTCType Dem_GetStatusOfDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, Dem_EventStatusExtendedType* status) { /* NOTE: dtc is in UDS format according to DEM212 */ Dem_ReturnGetStatusOfDTCType returnCode = DEM_STATUS_FAILED; EventStatusRecType *eventRec; const Dem_DTCClassType *DTCClass; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETSTATUSOFDTC_ID, DEM_E_UNINIT, DEM_STATUS_FAILED); VALIDATE_RV(IS_SUPPORTED_ORIGIN(dtcOrigin), DEM_GETSTATUSOFDTC_ID, DEM_E_PARAM_DATA, DEM_STATUS_WRONG_DTCORIGIN);/** @req DEM171 */ SchM_Enter_Dem_EA_0(); Dem_EventStatusExtendedType temp = 0u; if ( TRUE == LookupUdsDTC(dtc, &DTCClass)) { returnCode = DEM_STATUS_OK; for(uint16 i = 0; (i < DTCClass->NofEvents) && (DEM_STATUS_OK == returnCode); i++) { returnCode = DEM_STATUS_OK; eventRec = NULL_PTR; lookupEventStatusRec(DTCClass->Events[i], &eventRec); if( NULL_PTR != eventRec ) { /* Event found for this DTC */ if (checkDtcOrigin(dtcOrigin,eventRec->eventParamRef, FALSE) == TRUE) { /* NOTE: Should the availability mask be used here? */ /* @req DEM059 */ /* @req DEM441 */ if( TRUE == eventRec->isAvailable ) { temp |= eventRec->eventStatusExtended; } } else { /* Here we know that dtcOrigin is a supported one */ returnCode = DEM_STATUS_WRONG_DTC; /** @req DEM172 */ } } else { returnCode = DEM_STATUS_FAILED; } } uint8 mask = 0xFFU; if( (DEM_STATUS_OK == returnCode) && (DTCClass->NofEvents > 1u) ) { /* This is a combined DTC. Bits have already been OR-ed above. Now we should and bits. */ /* @req DEM441 */ mask = ((temp & (1u << 5u)) >> 1u) | ((temp & (1u << 1u)) << 5u); mask = (uint8)((~mask) & 0xFFu); } *status = (temp & mask); } else { /* Event has no DTC or DTC is suppressed */ /* @req 4.2.2/SWS_Dem_01100 *//* @req DEM587 */ returnCode = DEM_STATUS_WRONG_DTC; } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetNumberOfFilteredDtc * Reentrant: No */ Dem_ReturnGetNumberOfFilteredDTCType Dem_GetNumberOfFilteredDtc(uint16 *numberOfFilteredDTC) { uint16 numberOfFaults = 0; Dem_ReturnGetNumberOfFilteredDTCType returnCode = DEM_NUMBER_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETNUMBEROFFILTEREDDTC_ID, DEM_E_UNINIT, DEM_NUMBER_FAILED); VALIDATE_RV(NULL != numberOfFilteredDTC, DEM_GETNUMBEROFFILTEREDDTC_ID, DEM_E_PARAM_POINTER, DEM_NUMBER_FAILED); SchM_Enter_Dem_EA_0(); const Dem_DTCClassType *DTCClass = configSet->DTCClass; Dem_EventStatusExtendedType DTCStatus; /* Find all DTCs matching filter. Ignore suppressed DTCs *//* @req DEM587 *//* @req 4.2.2/SWS_Dem_01101 */ while( FALSE == DTCClass->Arc_EOL ) { if( TRUE == matchDTCWithDtcFilter(DTCClass, &DTCStatus) ) { numberOfFaults++; } DTCClass++; } *numberOfFilteredDTC = numberOfFaults; /** @req DEM061 */ SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetNextFilteredDTC * Reentrant: No */ Dem_ReturnGetNextFilteredDTCType Dem_GetNextFilteredDTC(uint32 *dtc, Dem_EventStatusExtendedType *dtcStatus) { Dem_ReturnGetNextFilteredDTCType returnCode = DEM_FILTERED_OK; boolean dtcFound = FALSE; Dem_EventStatusExtendedType DTCStatus; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETNEXTFILTEREDDTC_ID, DEM_E_UNINIT, DEM_FILTERED_NO_MATCHING_DTC); VALIDATE_RV(NULL != dtc, DEM_GETNEXTFILTEREDDTC_ID, DEM_E_PARAM_POINTER, DEM_FILTERED_NO_MATCHING_DTC); VALIDATE_RV(NULL != dtcStatus, DEM_GETNEXTFILTEREDDTC_ID, DEM_E_PARAM_POINTER, DEM_FILTERED_NO_MATCHING_DTC); SchM_Enter_Dem_EA_0(); /* Find the next DTC matching filter. Ignore suppressed DTCs *//* @req DEM587 *//* @req 4.2.2/SWS_Dem_01101 */ /* @req DEM217 */ const Dem_DTCClassType *DTCClass = &configSet->DTCClass[dtcFilter.DTCIndex]; while( (dtcFound == FALSE) && (FALSE == DTCClass->Arc_EOL) ) { if( TRUE == matchDTCWithDtcFilter(DTCClass, &DTCStatus) ) { if( DEM_DTC_FORMAT_UDS == dtcFilter.dtcFormat ) { *dtc = DTCClass->DTCRef->UDSDTC; /** @req DEM216 */ } else { *dtc = TO_OBD_FORMAT(DTCClass->DTCRef->OBDDTC); } *dtcStatus = DTCStatus; dtcFound = TRUE; } dtcFilter.DTCIndex++; DTCClass++; } if( FALSE == dtcFound ) { dtcFilter.DTCIndex = 0u; returnCode = DEM_FILTERED_NO_MATCHING_DTC; } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetTranslationType * Reentrant: No */ Dem_DTCTranslationFormatType Dem_GetTranslationType(void) { return DEM_TYPE_OF_DTC_SUPPORTED; /** @req DEM231 */ } /* * Procedure: Dem_ClearDTC * Comment: Stating the dtcOrigin makes no since when reading the reqiurements in the specification. * Reentrant: No */ Dem_ReturnClearDTCType Dem_ClearDTC(uint32 dtc, Dem_DTCFormatType dtcFormat, Dem_DTCOriginType dtcOrigin) /** @req DEM009 *//** @req DEM241 */ { Dem_ReturnClearDTCType returnCode = DEM_CLEAR_WRONG_DTCORIGIN; const Dem_EventParameterType *eventParam; Dem_EventStatusExtendedType oldStatus; boolean dataDeleted; #ifdef DEM_USE_MEMORY_FUNCTIONS boolean allClearOK = TRUE; #endif (void)dtcOrigin; #if defined(DEM_USE_INDICATORS) && defined(DEM_USE_MEMORY_FUNCTIONS) boolean indicatorsChanged = FALSE; #endif VALIDATE_RV(DEM_INITIALIZED == demState, DEM_CLEARDTC_ID, DEM_E_UNINIT, DEM_CLEAR_FAILED); VALIDATE_RV(IS_VALID_DTC_FORMAT(dtcFormat), DEM_CLEARDTC_ID, DEM_E_PARAM_DATA, DEM_CLEAR_FAILED); for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { SchM_Enter_Dem_EA_0(); dataDeleted = FALSE; if ((DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) && (NULL != eventStatusBuffer[i].eventParamRef)) { eventParam = eventStatusBuffer[i].eventParamRef; if ((DEM_CLEAR_ALL_EVENTS == STD_ON) || (eventParam->DTCClassRef != NULL)) {/*lint !e506 !e774*/ if (checkDtcGroup(dtc, eventParam, dtcFormat) == TRUE) { if( eventParam->EventClass->EventDestination == dtcOrigin ) { if(FALSE == eventDTCRecordDataUpdateDisabled(eventParam)) { if( clearEventAllowed(eventParam) == TRUE) { boolean dtcOriginFound = FALSE; oldStatus = eventStatusBuffer[i].eventStatusExtended; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) dataDeleted = DeleteDTCData(eventParam, TRUE, &dtcOriginFound, (DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID));/* @req DEM343 */ #else dataDeleted = DeleteDTCData(eventParam, TRUE, &dtcOriginFound, FALSE);/* @req DEM343 */ #endif if (dtcOriginFound == FALSE) { returnCode = DEM_CLEAR_WRONG_DTCORIGIN; DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_CLEARDTC_ID, DEM_E_NOT_IMPLEMENTED_YET); } else { #if defined(DEM_USE_INDICATORS) if( TRUE == resetIndicatorCounters(eventParam) ) { #ifdef DEM_USE_MEMORY_FUNCTIONS indicatorsChanged = TRUE; #endif } #endif #if defined(USE_DEM_EXTENSION) Dem_Extension_ClearEvent(eventParam); #endif if( dataDeleted == TRUE) { /* @req DEM475 */ notifyEventDataChanged(eventParam); } if( oldStatus != eventStatusBuffer[i].eventStatusExtended ) { /* @req DEM016 */ notifyEventStatusChange(eventParam, oldStatus, eventStatusBuffer[i].eventStatusExtended); } if( NULL != eventParam->CallbackInitMforE ) { /* @req DEM376 */ (void)eventParam->CallbackInitMforE(DEM_INIT_MONITOR_CLEAR); } /* Have cleared at least one, OK */ returnCode = DEM_CLEAR_OK; } } else { returnCode = DEM_CLEAR_FAILED; /* CallbackClearEventAllowed returned not allowed to clear */ #ifdef DEM_USE_MEMORY_FUNCTIONS /* Clear was not allowed */ allClearOK = FALSE; #endif } } } } else { if( (((DEM_DTC_FORMAT_UDS == dtcFormat) && (dtc == eventParam->DTCClassRef->DTCRef->UDSDTC)) || ((DEM_DTC_FORMAT_OBD == dtcFormat) && (dtc == TO_OBD_FORMAT(eventParam->DTCClassRef->DTCRef->OBDDTC)))) && (DTCIsAvailable(eventParam->DTCClassRef) == FALSE) ) { /* This DTC is suppressed *//* @req 4.2.2/SWS_Dem_01101 */ returnCode = DEM_CLEAR_WRONG_DTC; } } } } else { // Fatal error, no event parameters found for the event! DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_CLEARDTC_ID, DEM_E_UNEXPECTED_EXECUTION); } SchM_Exit_Dem_EA_0(); } SchM_Enter_Dem_EA_0(); #ifdef DEM_USE_MEMORY_FUNCTIONS #if defined(DEM_USE_INDICATORS) if( indicatorsChanged == TRUE ) { /* IMPROVEMENT: Immediate storage when deleting? */ Dem_NvM_SetIndicatorBlockChanged(FALSE); } #endif if( (DEM_DTC_GROUP_ALL_DTCS == dtc) && (allClearOK == TRUE)) { /* @req DEM399 */ setOverflowIndication(dtcOrigin, FALSE); } #endif SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_DisableDTCStorage * Reentrant: No */ Dem_ReturnControlDTCStorageType Dem_DisableDTCSetting(Dem_DTCGroupType dtcGroup, Dem_DTCKindType dtcKind) /** @req DEM035 */ { Dem_ReturnControlDTCStorageType returnCode = DEM_CONTROL_DTC_STORAGE_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_DISABLEDTCSETTING_ID, DEM_E_UNINIT, DEM_CONTROL_DTC_STORAGE_N_OK); // Check dtcGroup parameter uint32 DTCGroupLower; uint32 DTCGroupUpper; if ( (dtcGroup == DEM_DTC_GROUP_ALL_DTCS) || (DEM_DTC_GROUP_EMISSION_REL_DTCS == dtcGroup) || (TRUE == dtcIsGroup(dtcGroup, DEM_DTC_FORMAT_UDS, &DTCGroupLower, &DTCGroupUpper))) { // Check dtcKind parameter if ((dtcKind == DEM_DTC_KIND_ALL_DTCS) || (dtcKind == DEM_DTC_KIND_EMISSION_REL_DTCS)) { /** @req DEM079 */ disableDtcSetting.dtcGroup = dtcGroup; disableDtcSetting.dtcKind = dtcKind; disableDtcSetting.settingDisabled = TRUE; } else { returnCode = DEM_CONTROL_DTC_STORAGE_N_OK; } } else { returnCode = DEM_CONTROL_DTC_WRONG_DTCGROUP; } return returnCode; } /* * Procedure: Dem_EnableDTCStorage * Reentrant: No */ Dem_ReturnControlDTCStorageType Dem_EnableDTCSetting(Dem_DTCGroupType dtcGroup, Dem_DTCKindType dtcKind) { Dem_ReturnControlDTCStorageType returnCode = DEM_CONTROL_DTC_STORAGE_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_ENABLEDTCSETTING_ID, DEM_E_UNINIT, DEM_CONTROL_DTC_STORAGE_N_OK); // NOTE: Behavior is not defined if group or kind do not match active settings, therefore the filter is just switched off. (void)dtcGroup; (void)dtcKind; // Just to make get rid of PC-Lint warnings disableDtcSetting.settingDisabled = FALSE; /** @req DEM080 */ return returnCode; } /* * Procedure: Dem_GetExtendedDataRecordByDTC * Reentrant: No */ Dem_ReturnGetExtendedDataRecordByDTCType Dem_GetExtendedDataRecordByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 extendedDataNumber, uint8 *destBuffer, uint16 *bufSize) { /* IMPROVEMENT: Handle record numbers 0xFE and 0xFF */ /* NOTE: dtc is in UDS format according to DEM239 */ /* @req DEM540 */ Dem_ReturnGetExtendedDataRecordByDTCType returnCode = DEM_RECORD_WRONG_DTC; const Dem_EventParameterType *eventParam; Dem_ExtendedDataRecordClassType const *extendedDataRecordClass = NULL; ExtDataRecType *extData; uint16 posInExtData = 0; uint16 nofBytesCopied = 0; uint16 bufSizeLeft ; boolean oneRecordOK = FALSE; #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) uint32 timestamp = 0; boolean dataCopied = FALSE; #endif VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEXTENDEDDATARECORDBYDTC_ID, DEM_E_UNINIT, DEM_RECORD_WRONG_DTC); VALIDATE_RV((NULL != destBuffer), DEM_GETEXTENDEDDATARECORDBYDTC_ID, DEM_E_PARAM_POINTER, DEM_RECORD_WRONG_DTC); VALIDATE_RV((NULL != bufSize), DEM_GETEXTENDEDDATARECORDBYDTC_ID, DEM_E_PARAM_POINTER, DEM_RECORD_WRONG_DTC); SchM_Enter_Dem_EA_0(); bufSizeLeft = *bufSize; if( extendedDataNumber <= DEM_HIGHEST_EXT_DATA_REC_NUM ) { /* Get the DTC config */ const Dem_DTCClassType *DTCClass; if ( TRUE == LookupUdsDTC(dtc, &DTCClass) ) { for(uint16 i = 0; i < DTCClass->NofEvents; i++) { eventParam = NULL_PTR; lookupEventIdParameter(DTCClass->Events[i], &eventParam); if( NULL_PTR != eventParam ) { if (checkDtcOrigin(dtcOrigin, eventParam, FALSE)==TRUE) { if (lookupExtendedDataRecNumParam(extendedDataNumber, eventParam, &extendedDataRecordClass, &posInExtData)==TRUE) { if (bufSizeLeft >= extendedDataRecordClass->DataSize) { oneRecordOK = TRUE; #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_OFF) Dem_EventIdType idToFind; #endif if( extendedDataRecordClass->UpdateRule != DEM_UPDATE_RECORD_VOLATILE ) { switch (dtcOrigin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) if (lookupOlderExtendedDataMem(eventParam->EventID, &extData, dtcOrigin, &timestamp, dataCopied) == TRUE) { // Yes all conditions met, copy the extended data record to destination buffer. memcpy(destBuffer, &extData->data[posInExtData], extendedDataRecordClass->DataSize); /** @req DEM075 */ nofBytesCopied = extendedDataRecordClass->DataSize;/* @req DEM076 */ dataCopied = TRUE; returnCode = DEM_RECORD_OK; } #else #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { /* @req DEM537 */ idToFind = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { idToFind = eventParam->EventID; } #else idToFind = eventParam->EventID; #endif if (lookupExtendedDataMem(idToFind, &extData, dtcOrigin) == TRUE) { // Yes all conditions met, copy the extended data record to destination buffer. memcpy(&destBuffer[nofBytesCopied], &extData->data[posInExtData], extendedDataRecordClass->DataSize); /** @req DEM075 */ #if !defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) bufSizeLeft -= extendedDataRecordClass->DataSize;/* @req DEM076 */ #endif nofBytesCopied += extendedDataRecordClass->DataSize; returnCode = DEM_RECORD_OK; } else { /* The record number is legal but no record was found for the DTC *//* @req DEM631 */ returnCode = DEM_RECORD_OK; } #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported returnCode = DEM_RECORD_WRONG_DTCORIGIN; DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETEXTENDEDDATARECORDBYDTC_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: returnCode = DEM_RECORD_WRONG_DTCORIGIN; break; } } else { #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) if( FALSE == dataCopied ) { /* No data copied*/ if( NULL != extendedDataRecordClass->CallbackGetExtDataRecord ) { /* IMPROVEMENT: Handle return value? */ (void)extendedDataRecordClass->CallbackGetExtDataRecord(&destBuffer[nofBytesCopied]); bufSizeLeft -= extendedDataRecordClass->DataSize;/* @req DEM076 */ nofBytesCopied += extendedDataRecordClass->DataSize; returnCode = DEM_RECORD_OK; } else if (DEM_NO_ELEMENT != extendedDataRecordClass->InternalDataElement ) { getInternalElement( eventParam, extendedDataRecordClass->InternalDataElement, &destBuffer[nofBytesCopied], extendedDataRecordClass->DataSize ); bufSizeLeft -= extendedDataRecordClass->DataSize;/* @req DEM076 */ nofBytesCopied += extendedDataRecordClass->DataSize; returnCode = DEM_RECORD_OK; } else { returnCode = DEM_RECORD_WRONG_DTC; } } else { /* Data has already been copied. This means that a stored record was found. Assume this to be older than "live" data. */ } #else if( NULL != extendedDataRecordClass->CallbackGetExtDataRecord ) { /* IMPROVEMENT: Handle return value? */ (void)extendedDataRecordClass->CallbackGetExtDataRecord(destBuffer); #if !defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) bufSizeLeft -= extendedDataRecordClass->DataSize;/* @req DEM076 */ #endif nofBytesCopied += extendedDataRecordClass->DataSize; returnCode = DEM_RECORD_OK; } else if (DEM_NO_ELEMENT != extendedDataRecordClass->InternalDataElement ) { getInternalElement( eventParam, extendedDataRecordClass->InternalDataElement, destBuffer, extendedDataRecordClass->DataSize ); #if !defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) bufSizeLeft -= extendedDataRecordClass->DataSize;/* @req DEM076 */ #endif nofBytesCopied += extendedDataRecordClass->DataSize; returnCode = DEM_RECORD_OK; } else { returnCode = DEM_RECORD_WRONG_DTC; } #endif } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETEXTENDEDDATARECORDBYDTC_ID, DEM_E_PARAM_LENGTH); returnCode = DEM_RECORD_BUFFERSIZE; } } else { returnCode = DEM_RECORD_NUMBER; } } else { returnCode = DEM_RECORD_WRONG_DTCORIGIN; } } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) break; #endif } if( TRUE == oneRecordOK ) { returnCode = DEM_RECORD_OK; *bufSize = nofBytesCopied; } } else { /* Event has no DTC or DTC is suppressed */ /* @req 4.2.2/SWS_Dem_01100 */ /* @req 4.2.2/SWS_Dem_01101 */ /* @req DEM587 */ returnCode = DEM_RECORD_WRONG_DTC; } } else { returnCode = DEM_RECORD_NUMBER; } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetSizeOfExtendedDataRecordByDTC * Reentrant: No */ /*lint -esym(793, Dem_GetSizeOfExtendedDataRecordByDTC) Function name defined by AUTOSAR. */ Dem_ReturnGetSizeOfExtendedDataRecordByDTCType Dem_GetSizeOfExtendedDataRecordByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 extendedDataNumber, uint16 *sizeOfExtendedDataRecord) { /* NOTE: dtc is in UDS format according to DEM240 */ Dem_ReturnGetExtendedDataRecordByDTCType returnCode = DEM_GET_SIZEOFEDRBYDTC_W_DTC; Dem_ExtendedDataRecordClassType const *extendedDataRecordClass = NULL_PTR; const Dem_EventParameterType *eventParam; uint16 posInExtData; boolean oneRecordOK = FALSE; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETSIZEOFEXTENDEDDATARECORDBYDTC_ID, DEM_E_UNINIT, DEM_GET_SIZEOFEDRBYDTC_W_DTC); VALIDATE_RV(NULL != sizeOfExtendedDataRecord, DEM_GETSIZEOFEXTENDEDDATARECORDBYDTC_ID, DEM_E_PARAM_POINTER, DEM_GET_SIZEOFEDRBYDTC_W_DTC); SchM_Enter_Dem_EA_0(); /* Check if event has DTC and that the DTC is not suppressed *//* @req DEM587 */ /* @req 4.2.2/SWS_Dem_01100 */ /* @req 4.2.2/SWS_Dem_01101 */ /* Get the DTC config */ const Dem_DTCClassType *DTCClass; if ( TRUE == LookupUdsDTC(dtc, &DTCClass) ) { *sizeOfExtendedDataRecord = 0u; for(uint16 i = 0; i < DTCClass->NofEvents; i++) { eventParam = NULL_PTR; lookupEventIdParameter(DTCClass->Events[i], &eventParam); if( NULL_PTR != eventParam ) { if (checkDtcOrigin(dtcOrigin, eventParam, FALSE) == TRUE) { if (lookupExtendedDataRecNumParam(extendedDataNumber, eventParam, &extendedDataRecordClass, &posInExtData) == TRUE) { #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) if( extendedDataRecordClass->DataSize > *sizeOfExtendedDataRecord) { *sizeOfExtendedDataRecord = extendedDataRecordClass->DataSize; /** @req DEM076 */ } #else *sizeOfExtendedDataRecord += extendedDataRecordClass->DataSize; #endif oneRecordOK = TRUE; } else { returnCode = DEM_GET_SIZEOFEDRBYDTC_W_RNUM; } } else { returnCode = DEM_GET_SIZEOFEDRBYDTC_W_DTCOR; } } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) break; #endif } if( TRUE == oneRecordOK ) { returnCode = DEM_GET_SIZEOFEDRBYDTC_OK; } } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetFreezeFrameDataByDTC * Reentrant: No */ /** @req DEM236 */ Dem_ReturnGetFreezeFrameDataByDTCType Dem_GetFreezeFrameDataByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 recordNumber, uint8* destBuffer, uint16* bufSize) { /* !req DEM576 */ /* @req DEM540 */ /* NOTE: dtc is in UDS format according to DEM236 */ Dem_ReturnGetFreezeFrameDataByDTCType returnCode = DEM_GET_FFDATABYDTC_WRONG_DTC; const Dem_EventParameterType *eventParam; Dem_FreezeFrameClassType const *FFDataRecordClass = NULL; uint16 FFDataSize = 0; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_UNINIT, DEM_GET_ID_PENDING); VALIDATE_RV((NULL != destBuffer), DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_PARAM_POINTER, DEM_GET_FFDATABYDTC_WRONG_DTC); VALIDATE_RV((NULL != bufSize), DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_PARAM_POINTER, DEM_GET_FFDATABYDTC_WRONG_DTC); SchM_Enter_Dem_EA_0(); uint16 bufSizeLeft = *bufSize; uint16 bufferSize; uint16 nofBytesCopied = 0u; boolean oneRecordOK = FALSE; #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) uint32 timestamp = 0; boolean useTimestamp = FALSE; #endif if( *bufSize >= DEM_REC_NUM_AND_NUM_DIDS_SIZE ) { bufSizeLeft -= DEM_REC_NUM_AND_NUM_DIDS_SIZE; if( recordNumber <= DEM_HIGHEST_FF_REC_NUM ) { /* Get the DTC config */ const Dem_DTCClassType *DTCClass; if ( TRUE == LookupUdsDTC(dtc, &DTCClass) ) { destBuffer[0] = recordNumber; destBuffer[1] = 0u; for(uint16 i = 0; i < DTCClass->NofEvents; i++) { eventParam = NULL_PTR; lookupEventIdParameter(DTCClass->Events[i], &eventParam); if( NULL_PTR != eventParam ) { if (checkDtcOrigin(dtcOrigin, eventParam, FALSE) == TRUE) { if (lookupFreezeFrameDataRecNumParam(recordNumber, eventParam, &FFDataRecordClass) == TRUE) { /* NOTE: Handle return value? */ (void)lookupFreezeFrameDataSize(recordNumber, &FFDataRecordClass, &FFDataSize); if (bufSizeLeft >= FFDataSize) { oneRecordOK = TRUE; switch (dtcOrigin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: case DEM_DTC_ORIGIN_SECONDARY_MEMORY: returnCode = DEM_GET_FFDATABYDTC_OK; bufferSize = bufSizeLeft; #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) if( TRUE == getOlderFreezeFrameRecord(eventParam->EventID, recordNumber, dtcOrigin, &destBuffer[2u], &bufferSize, FFDataSize, &timestamp, useTimestamp)) { destBuffer[1] = FFDataRecordClass->NofXids; useTimestamp = TRUE; nofBytesCopied = bufferSize; } #else #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) Dem_EventIdType eventId; if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { /* @req DEM537 */ eventId = TO_COMBINED_EVENT_ID(eventParam->CombinedDTCCID); } else { eventId = eventParam->EventID; } if (getFreezeFrameRecord(eventId, recordNumber, dtcOrigin, &destBuffer[nofBytesCopied + 2u], &bufferSize, FFDataSize) == TRUE) { #else if (getFreezeFrameRecord(eventParam->EventID, recordNumber, dtcOrigin, &destBuffer[nofBytesCopied + 2u], &bufferSize, FFDataSize) == TRUE) { #endif destBuffer[1] += FFDataRecordClass->NofXids; #if !defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) bufSizeLeft -= bufferSize; #endif nofBytesCopied += bufferSize; } else { /* @req DEM630 */ } #endif break; case DEM_DTC_ORIGIN_PERMANENT_MEMORY: case DEM_DTC_ORIGIN_MIRROR_MEMORY: // Not yet supported returnCode = DEM_GET_FFDATABYDTC_WRONG_DTCORIGIN; DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_NOT_IMPLEMENTED_YET); break; default: returnCode = DEM_GET_FFDATABYDTC_WRONG_DTCORIGIN; break; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_PARAM_LENGTH); returnCode = DEM_GET_FFDATABYDTC_BUFFERSIZE; } } else { returnCode = DEM_GET_FFDATABYDTC_RECORDNUMBER; } } else { returnCode = DEM_GET_FFDATABYDTC_WRONG_DTCORIGIN; } } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) break; #endif } if( (DEM_GET_FFDATABYDTC_OK == returnCode) || (TRUE == oneRecordOK) ) { *bufSize = nofBytesCopied; if( 0u != nofBytesCopied ) { /* Data was found. Add size of RecordNumber and NumOfDIDs */ *bufSize += DEM_REC_NUM_AND_NUM_DIDS_SIZE; } returnCode = DEM_GET_FFDATABYDTC_OK; } } else { /* Event has no DTC or DTC is suppressed */ /* @req 4.2.2/SWS_Dem_01100 */ /* @req 4.2.2/SWS_Dem_01101 */ /* @req DEM587 */ returnCode = DEM_GET_FFDATABYDTC_WRONG_DTC; } } else { returnCode = DEM_GET_FFDATABYDTC_RECORDNUMBER; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETFREEZEFRAMEDATABYDTC_ID, DEM_E_PARAM_LENGTH); returnCode = DEM_GET_FFDATABYDTC_BUFFERSIZE; } SchM_Exit_Dem_EA_0(); return returnCode; } /* * Procedure: Dem_GetSizeOfFreezeFrame * Reentrant: No */ /** @req DEM238 */ Dem_ReturnGetSizeOfFreezeFrameType Dem_GetSizeOfFreezeFrameByDTC(uint32 dtc, Dem_DTCOriginType dtcOrigin, uint8 recordNumber, uint16* sizeOfFreezeFrame) { /* NOTE: dtc is in UDS format according to DEM238 */ Dem_ReturnGetSizeOfFreezeFrameType returnCode = DEM_GET_SIZEOFFF_PENDING; Dem_FreezeFrameClassType const *FFDataRecordClass = NULL; const Dem_EventParameterType *eventParam; #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) uint16 tempSize; #endif VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETSIZEOFFREEZEFRAMEBYDTC_ID, DEM_E_UNINIT, DEM_GET_SIZEOFFF_PENDING); VALIDATE_RV((NULL != sizeOfFreezeFrame), DEM_GETSIZEOFFREEZEFRAMEBYDTC_ID, DEM_E_PARAM_POINTER, DEM_GET_SIZEOFFF_WRONG_DTC); SchM_Enter_Dem_EA_0(); const Dem_DTCClassType *DTCClass; if ( TRUE == LookupUdsDTC(dtc, &DTCClass) ) { *sizeOfFreezeFrame = 0u; for(uint16 i = 0; i < DTCClass->NofEvents; i++) { eventParam = NULL_PTR; lookupEventIdParameter(DTCClass->Events[i], &eventParam); if( NULL_PTR != eventParam ) { if (checkDtcOrigin(dtcOrigin, eventParam, FALSE) == TRUE) { if (lookupFreezeFrameDataRecNumParam(recordNumber, eventParam, &FFDataRecordClass) == TRUE) { if(FFDataRecordClass->FFIdClassRef != NULL){ /* Note - there is a function called lookupFreezeFrameDataSize that can be used here */ for(uint16 j = 0; (j < DEM_MAX_NR_OF_DIDS_IN_FREEZEFRAME_DATA) && ((FFDataRecordClass->FFIdClassRef[j]->Arc_EOL == FALSE)); j++){ /* read out the did size */ #if (DEM_EVENT_COMB_TYPE2_REPORT_OLDEST_DATA == STD_ON) /* Report the biggest */ tempSize = (uint16)(FFDataRecordClass->FFIdClassRef[j]->PidOrDidSize + DEM_DID_IDENTIFIER_SIZE_OF_BYTES); if( tempSize > *sizeOfFreezeFrame ) { *sizeOfFreezeFrame = tempSize; } #else /* Report the total size */ *sizeOfFreezeFrame += (uint16)(FFDataRecordClass->FFIdClassRef[j]->PidOrDidSize + DEM_DID_IDENTIFIER_SIZE_OF_BYTES);/** @req DEM074 */ #endif returnCode = DEM_GET_SIZEOFFF_OK; } } else { returnCode = DEM_GET_SIZEOFFF_WRONG_RNUM; } } else { returnCode = DEM_GET_SIZEOFFF_WRONG_RNUM; } } else { returnCode = DEM_GET_SIZEOFFF_WRONG_DTCOR; } } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) break; #endif } } else { /* Event has no DTC or DTC is suppressed */ /* @req 4.2.2/SWS_Dem_01100 */ /* @req 4.2.2/SWS_Dem_01101 */ /* @req DEM587 */ returnCode = DEM_GET_SIZEOFFF_WRONG_DTC; } SchM_Exit_Dem_EA_0(); return returnCode; } /** * * @param DTCFormat * @param NumberOfFilteredRecords * @return */ Dem_ReturnSetFilterType Dem_SetFreezeFrameRecordFilter(Dem_DTCFormatType DTCFormat, uint16 *NumberOfFilteredRecords) { Dem_ReturnSetFilterType ret = DEM_WRONG_FILTER; uint16 nofRecords = 0; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETFREEZEFRAMERECORDFILTER_ID, DEM_E_UNINIT, DEM_WRONG_FILTER); VALIDATE_RV((NULL != NumberOfFilteredRecords), DEM_SETFREEZEFRAMERECORDFILTER_ID, DEM_E_PARAM_POINTER, DEM_WRONG_FILTER); VALIDATE_RV(IS_VALID_DTC_FORMAT(DTCFormat), DEM_SETFREEZEFRAMERECORDFILTER_ID, DEM_E_PARAM_DATA, DEM_WRONG_FILTER); SchM_Enter_Dem_EA_0(); /* @req DEM210 Only applies to primary memory */ #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) for( uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM; i++ ) { if( DEM_EVENT_ID_NULL != priMemFreezeFrameBuffer[i].eventId ) { EventStatusRecType *eventStatusRecPtr = NULL_PTR; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( !IS_COMBINED_EVENT_ID(priMemFreezeFrameBuffer[i].eventId) ) { /* Only do this if the entry is NOT a combined event entry. This to avoid Det error. */ lookupEventStatusRec(priMemFreezeFrameBuffer[i].eventId, &eventStatusRecPtr); } #else lookupEventStatusRec(priMemFreezeFrameBuffer[i].eventId, &eventStatusRecPtr); #endif #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) /* Check if this record has already been counted. */ boolean alreadyCounted = FALSE; for( uint16 j = 0; j < i; j++ ) { if( DEM_EVENT_ID_NULL != priMemFreezeFrameBuffer[j].eventId ) { EventStatusRecType *eventStatusRecPtr2 = NULL_PTR; lookupEventStatusRec(priMemFreezeFrameBuffer[j].eventId, &eventStatusRecPtr2); if( NULL_PTR != eventStatusRecPtr2) { if( (eventStatusRecPtr->eventParamRef->DTCClassRef == eventStatusRecPtr2->eventParamRef->DTCClassRef) && (priMemFreezeFrameBuffer[j].recordNumber == priMemFreezeFrameBuffer[i].recordNumber)) { /* Same DTC and record found earlier in buffer -> already counted. */ alreadyCounted = TRUE; } } } } #endif if( (NULL_PTR != eventStatusRecPtr) && (TRUE == eventHasDTCOnFormat(eventStatusRecPtr->eventParamRef, DTCFormat)) && (TRUE == DTCIsAvailable(eventStatusRecPtr->eventParamRef->DTCClassRef)) #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && (FALSE == alreadyCounted) #endif ) { nofRecords++; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (NULL_PTR == eventStatusRecPtr) && IS_COMBINED_EVENT_ID(priMemFreezeFrameBuffer[i].eventId) ) { /* This is a combined event entry. */ /* Get DTC config */ const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(priMemFreezeFrameBuffer[i].eventId)]; if( (TRUE == DTCISAvailableOnFormat(CombDTCCfg->DTCClassRef, DTCFormat)) && (TRUE == DTCIsAvailable(CombDTCCfg->DTCClassRef)) ) { nofRecords++; } } #endif } } #endif *NumberOfFilteredRecords = nofRecords; /* @req DEM595 */ ffRecordFilter.dtcFormat = DTCFormat; ffRecordFilter.ffIndex = 0; ret = DEM_FILTER_ACCEPTED; SchM_Exit_Dem_EA_0(); return ret; } Dem_ReturnGetNextFilteredDTCType Dem_GetNextFilteredRecord(uint32 *DTC, uint8 *RecordNumber) { /* No requirement on checking the pointers but do it anyway. */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETNEXTFILTEREDRECORD_ID, DEM_E_UNINIT, DEM_FILTERED_NO_MATCHING_DTC); VALIDATE_RV(NULL != DTC, DEM_GETNEXTFILTEREDRECORD_ID, DEM_E_PARAM_POINTER, DEM_FILTERED_NO_MATCHING_DTC); VALIDATE_RV(NULL != RecordNumber, DEM_GETNEXTFILTEREDRECORD_ID, DEM_E_PARAM_POINTER, DEM_FILTERED_NO_MATCHING_DTC); Dem_ReturnGetNextFilteredDTCType ret = DEM_FILTERED_NO_MATCHING_DTC; SchM_Enter_Dem_EA_0(); #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) /* Find the next record which has a DTC */ EventStatusRecType *eventStatusRecPtr; boolean found = FALSE; for( uint16 i = ffRecordFilter.ffIndex; (i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM) && (FALSE == found); i++ ) { if( DEM_EVENT_ID_NULL != priMemFreezeFrameBuffer[i].eventId ) { eventStatusRecPtr = NULL_PTR; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( !IS_COMBINED_EVENT_ID(priMemFreezeFrameBuffer[i].eventId) ) { /* Only do this if the entry is NOT a combined event entry. This to avoid Det error. */ lookupEventStatusRec(priMemFreezeFrameBuffer[i].eventId, &eventStatusRecPtr); } #else lookupEventStatusRec(priMemFreezeFrameBuffer[i].eventId, &eventStatusRecPtr); #endif #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) /* Check if this record has already been counted. */ boolean alreadyCounted = FALSE; for( uint16 j = 0; j < i; j++ ) { if( DEM_EVENT_ID_NULL != priMemFreezeFrameBuffer[j].eventId ) { EventStatusRecType *eventStatusRecPtr2 = NULL_PTR; lookupEventStatusRec(priMemFreezeFrameBuffer[j].eventId, &eventStatusRecPtr2); if( NULL_PTR != eventStatusRecPtr2) { if( (eventStatusRecPtr->eventParamRef->DTCClassRef == eventStatusRecPtr2->eventParamRef->DTCClassRef) && (priMemFreezeFrameBuffer[j].recordNumber == priMemFreezeFrameBuffer[i].recordNumber)) { /* Same DTC and record found earlier in buffer -> already counted. */ alreadyCounted = TRUE; } } } } #endif /* @req 4.2.2/SWS_Dem_01101 *//* @req DEM587 */ if( (NULL != eventStatusRecPtr) && (TRUE == eventHasDTCOnFormat(eventStatusRecPtr->eventParamRef, ffRecordFilter.dtcFormat)) && (TRUE == DTCIsAvailable(eventStatusRecPtr->eventParamRef->DTCClassRef)) #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && (FALSE == alreadyCounted) #endif ) { /* Found one not already reported! */ /* @req DEM225 */ *RecordNumber = priMemFreezeFrameBuffer[i].recordNumber; *DTC = (DEM_DTC_FORMAT_UDS == ffRecordFilter.dtcFormat) ? eventStatusRecPtr->eventParamRef->DTCClassRef->DTCRef->UDSDTC : TO_OBD_FORMAT(eventStatusRecPtr->eventParamRef->DTCClassRef->DTCRef->OBDDTC); /* @req DEM226 */ ffRecordFilter.ffIndex = i + 1; found = TRUE; ret = DEM_FILTERED_OK; } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( (NULL_PTR == eventStatusRecPtr) && IS_COMBINED_EVENT_ID(priMemFreezeFrameBuffer[i].eventId) ) { /* This is a combined event entry. */ /* Get DTC config */ const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(priMemFreezeFrameBuffer[i].eventId)]; if( (TRUE == DTCISAvailableOnFormat(CombDTCCfg->DTCClassRef, ffRecordFilter.dtcFormat)) && (TRUE == DTCIsAvailable(CombDTCCfg->DTCClassRef)) ) { *RecordNumber = priMemFreezeFrameBuffer[i].recordNumber; *DTC = (DEM_DTC_FORMAT_UDS == ffRecordFilter.dtcFormat) ? CombDTCCfg->DTCClassRef->DTCRef->UDSDTC : TO_OBD_FORMAT(CombDTCCfg->DTCClassRef->DTCRef->OBDDTC); ffRecordFilter.ffIndex = i + 1; found = TRUE; ret = DEM_FILTERED_OK; } } #endif } } #endif SchM_Exit_Dem_EA_0(); return ret; /*lint -e{818} *RecordNumber and *DTC these pointers are updated under DEM_USE_PRIMARY_MEMORY_SUPPORT condition */ } #if (DEM_ENABLE_CONDITION_SUPPORT == STD_ON) /* @req DEM202 */ Std_ReturnType Dem_SetEnableCondition(uint8 EnableConditionID, boolean ConditionFulfilled) { VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETENABLECONDITION_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV((EnableConditionID < DEM_NUM_ENABLECONDITIONS), DEM_SETENABLECONDITION_ID, DEM_E_PARAM_DATA, E_NOT_OK); DemEnableConditions[EnableConditionID] = ConditionFulfilled; return E_OK; } #endif /* Function: Dem_GetSeverityOfDTC * Description: Gets the severity of a DTC */ Dem_ReturnGetSeverityOfDTCType Dem_GetSeverityOfDTC(uint32 DTC, Dem_DTCSeverityType* DTCSeverity) { /* NOTE: DTC is on UDS format according to DEM232 */ Dem_ReturnGetSeverityOfDTCType ret = DEM_GET_SEVERITYOFDTC_WRONG_DTC; boolean isDone = FALSE; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETSEVERITYOFDTC_ID, DEM_E_UNINIT, DEM_GET_SEVERITYOFDTC_PENDING); VALIDATE_RV((NULL != DTCSeverity), DEM_GETSEVERITYOFDTC_ID, DEM_E_PARAM_POINTER, DEM_GET_SEVERITYOFDTC_PENDING); const Dem_DTCClassType *DTCPtr = configSet->DTCClass; while( (DTCPtr->Arc_EOL == FALSE) && (isDone == FALSE) ) { if( (DEM_NO_DTC != DTCPtr->DTCRef->UDSDTC) && (DTC == DTCPtr->DTCRef->UDSDTC) ) { /* Dtc found */ isDone = TRUE; if( DTCIsAvailable(DTCPtr) == TRUE ) { *DTCSeverity = DTCPtr->DTCSeverity; if( DEM_SEVERITY_NO_SEVERITY == DTCPtr->DTCSeverity ) { ret = DEM_GET_SEVERITYOFDTC_NOSEVERITY; } else { ret = DEM_GET_SEVERITYOFDTC_OK; } } else { /* @req 4.2.2/SWS_Dem_01100 */ /* Ignore suppressed DTCs *//* @req DEM587 */ ret = DEM_GET_SEVERITYOFDTC_WRONG_DTC; } } DTCPtr++; } return ret; } /* Function: Dem_DisableDTCRecordUpdate * Description: Disables the event memory update of a specific DTC (only one at one time) */ Dem_ReturnDisableDTCRecordUpdateType Dem_DisableDTCRecordUpdate(uint32 DTC, Dem_DTCOriginType DTCOrigin) { /* NOTE: DTC in in UDS format according to DEM233 */ Dem_ReturnDisableDTCRecordUpdateType ret = DEM_DISABLE_DTCRECUP_WRONG_DTC; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_DISABLEDTCRECORDUPDATE_ID, DEM_E_UNINIT, DEM_DISABLE_DTCRECUP_PENDING); if(NO_DTC_DISABLED == DTCRecordDisabled.DTC) { const Dem_EventParameterType *eventIdParamPtr = configSet->EventParameter; while( (eventIdParamPtr->Arc_EOL == FALSE) && (DEM_DISABLE_DTCRECUP_OK != ret)) { if( (NULL != eventIdParamPtr->DTCClassRef) && (eventHasDTCOnFormat(eventIdParamPtr, DEM_DTC_FORMAT_UDS) == TRUE) && (eventIdParamPtr->DTCClassRef->DTCRef->UDSDTC == DTC) && (DTCIsAvailable(eventIdParamPtr->DTCClassRef) == TRUE)) { /* Event references this DTC */ ret = DEM_DISABLE_DTCRECUP_WRONG_DTCORIGIN; if( eventIdParamPtr->EventClass->EventDestination == DTCOrigin ) { /* Event destination match. Disable update for this DTC and the event destination */ /* @req DEM270 */ DTCRecordDisabled.DTC = DTC; DTCRecordDisabled.Origin = DTCOrigin; ret = DEM_DISABLE_DTCRECUP_OK; } } eventIdParamPtr++; } } else if (DTCRecordDisabled.DTC != DTC) { /* The previously disabled DTC has not been enabled */ /* @req DEM648 *//* @req DEM518 */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_DISABLEDTCRECORDUPDATE_ID, DEM_E_WRONG_CONDITION); ret = DEM_DISABLE_DTCRECUP_PENDING; } else { ret = DEM_DISABLE_DTCRECUP_OK; } return ret; } /* Function: Dem_EnableDTCRecordUpdate * Description: Enables the event memory update of the DTC disabled by Dem_DisableDTCRecordUpdate() before. */ Std_ReturnType Dem_EnableDTCRecordUpdate(void) { Std_ReturnType ret = E_NOT_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_ENABLEDTCRECORDUPDATE_ID, DEM_E_UNINIT, E_NOT_OK); if(NO_DTC_DISABLED != DTCRecordDisabled.DTC) { /* @req DEM271 */ DTCRecordDisabled.DTC = NO_DTC_DISABLED; ret = E_OK; } else { /* No DTC record update has been disabled */ DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_ENABLEDTCRECORDUPDATE_ID, DEM_E_SEQUENCE_ERROR); } return ret; } /** * Gets the data of a freeze frame by event * @param EventId * @param RecordNumber * @param ReportTotalRecord * @param DataId * @param DestBuffer * @param BufSize * @param CareAboutBufsize * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ static Std_ReturnType Dem_GetEventFreezeFrameData_Internal(Dem_EventIdType EventId, uint8 RecordNumber, boolean ReportTotalRecord, uint16 DataId, uint8* DestBuffer, uint8* BufSize, boolean CareAboutBufsize) { /* @req DEM478*/ /* @req DEM479 */ Std_ReturnType ret = E_NOT_OK; const Dem_EventParameterType *eventIdParamPtr = NULL_PTR; uint8 recordToReport = 0u; uint8 destBufferIndex = 0u; uint8 *ffRecordData; EventStatusRecType * eventStatusRec = NULL_PTR; Dem_FreezeFrameKindType ffKind = DEM_FREEZE_FRAME_NON_OBD; if( DEM_INITIALIZED == demState ) { lookupEventIdParameter(EventId, &eventIdParamPtr); lookupEventStatusRec(EventId, &eventStatusRec); if( (NULL != eventIdParamPtr) && (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable) ) { /* Event has freeze frames configured */ if(getFFRecData(eventIdParamPtr, RecordNumber, &ffRecordData, &recordToReport, &ffKind) == TRUE) { /* And the record we are looking for was found */ const Dem_FreezeFrameClassType *freezeFrameClass = NULL_PTR; const Dem_PidOrDidType * const *xidPtr; if(DEM_FREEZE_FRAME_NON_OBD == ffKind ) { getFFClassReference(eventIdParamPtr, (Dem_FreezeFrameClassType **) &freezeFrameClass); xidPtr = freezeFrameClass->FFIdClassRef; } else { freezeFrameClass = configSet->GlobalOBDFreezeFrameClassRef; xidPtr = freezeFrameClass->FFIdClassRef; } uint16 ffDataIndex = 0u; boolean done = FALSE; while( ((*xidPtr)->Arc_EOL == FALSE) && (done == FALSE)) { if(DEM_FREEZE_FRAME_NON_OBD == ffKind ) { ffDataIndex += DEM_DID_IDENTIFIER_SIZE_OF_BYTES; } else { ffDataIndex += DEM_PID_IDENTIFIER_SIZE_OF_BYTES; } if( (ReportTotalRecord == TRUE) || ((DEM_FREEZE_FRAME_NON_OBD == ffKind) && (DataId == (*xidPtr)->DidIdentifier)) || ((DEM_FREEZE_FRAME_NON_OBD != ffKind) && (DataId == (*xidPtr)->PidIdentifier))) { if(CareAboutBufsize == TRUE){ if(((*xidPtr)->PidOrDidSize + destBufferIndex) > *BufSize){ *BufSize = destBufferIndex; return E_NOT_OK; /* buffer full, no info in DLT spec what to do for this case so we return operation failed */ } } memcpy(&DestBuffer[destBufferIndex], &ffRecordData[ffDataIndex], (size_t)((*xidPtr)->PidOrDidSize)); destBufferIndex += (*xidPtr)->PidOrDidSize; done = (ReportTotalRecord == FALSE)? TRUE: FALSE; ret = E_OK; } ffDataIndex += (uint16)((*xidPtr)->PidOrDidSize); xidPtr++; } } } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETEVENTFREEZEFRAMEDATA_ID, DEM_E_UNINIT); } *BufSize = destBufferIndex; return ret; } /** * Gets the data of a freeze frame by event * @param EventId * @param RecordNumber * @param ReportTotalRecord * @param DataId * @param DestBuffer * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ Std_ReturnType Dem_GetEventFreezeFrameData(Dem_EventIdType EventId, uint8 RecordNumber, boolean ReportTotalRecord, uint16 DataId, uint8* DestBuffer) { uint8 BufSize = 0x0; /* dummy size not used */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTFREEZEFRAMEDATA_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV((NULL != DestBuffer), DEM_GETEVENTFREEZEFRAMEDATA_ID, DEM_E_PARAM_POINTER, E_NOT_OK); return Dem_GetEventFreezeFrameData_Internal(EventId,RecordNumber,ReportTotalRecord,DataId,DestBuffer, &BufSize, FALSE); } #if (DEM_TRIGGER_DLT_REPORTS == STD_ON) /** * Gets the most recent data of a freeze frame by event for DLT * @param EventId * @param DestBuffer * @param BufSize * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ Std_ReturnType Dem_DltGetMostRecentFreezeFrameRecordData(Dem_EventIdType EventId, uint8* DestBuffer, uint8* BufSize){ /* @req DEM632 */ /* @req DEM633 */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_DLTGETMOSTRECENTFREEZEFRAMERECORDDATA_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(((NULL != DestBuffer) && (NULL != BufSize)), DEM_DLTGETMOSTRECENTFREEZEFRAMERECORDDATA_ID, DEM_E_PARAM_POINTER, E_NOT_OK); return Dem_GetEventFreezeFrameData_Internal(EventId, MOST_RECENT_FF_RECORD, TRUE,0, DestBuffer, BufSize, TRUE); } #endif /** * Gets the data of an extended data record by event * @param EventId * @param RecordNumber * @param DestBuffer * @param BufSize * @param CareAboutBufsize * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ static Std_ReturnType Dem_GetEventExtendedDataRecord_Internal(Dem_EventIdType EventId, uint8 RecordNumber, uint8* DestBuffer, uint8* BufSize, boolean CareAboutBufsize) { /* @req DEM476 */ /* @req DEM477 */ Std_ReturnType ret = E_NOT_OK; const Dem_EventParameterType *eventIdParamPtr = NULL_PTR; Dem_ExtendedDataRecordClassType const *extendedDataRecordClass = NULL_PTR; ExtDataRecType *extData; uint16 posInExtData = 0u; uint16 extdataIndex = 0u; uint8 extendedDataNumber = RecordNumber; boolean done = FALSE; boolean readFailed = FALSE; uint8 destBufferIndex = 0u; EventStatusRecType * eventStatusRec = NULL_PTR; if( DEM_INITIALIZED == demState ) { if( IS_VALID_EXT_DATA_RECORD(RecordNumber) || (ALL_EXTENDED_DATA_RECORDS == RecordNumber) ) { /* Record number ok */ lookupEventIdParameter(EventId, &eventIdParamPtr); lookupEventStatusRec(EventId, &eventStatusRec); if( (NULL != eventIdParamPtr) && (NULL != eventIdParamPtr->ExtendedDataClassRef) && (NULL != eventStatusRec) && (TRUE == eventStatusRec->isAvailable) ) { /* Event ok and has extended data */ ret = E_OK; while( (done == FALSE) && (NULL != eventIdParamPtr->ExtendedDataClassRef->ExtendedDataRecordClassRef[extdataIndex])) { readFailed = TRUE; if( ALL_EXTENDED_DATA_RECORDS == RecordNumber) { extendedDataNumber = eventIdParamPtr->ExtendedDataClassRef->ExtendedDataRecordClassRef[extdataIndex]->RecordNumber; } else { /* Should only read one specific record */ done = TRUE; } if (lookupExtendedDataRecNumParam(extendedDataNumber, eventIdParamPtr, &extendedDataRecordClass, &posInExtData) == TRUE) { if(CareAboutBufsize == TRUE){ if((extendedDataRecordClass->DataSize + destBufferIndex) > *BufSize){ *BufSize = destBufferIndex; return E_NOT_OK; /* buffer full, no info in DLT spec what to do for this case so we return operation failed */ } } if( extendedDataRecordClass->UpdateRule != DEM_UPDATE_RECORD_VOLATILE ) { if (lookupExtendedDataMem(EventId, &extData, eventIdParamPtr->EventClass->EventDestination) == TRUE ) { // Yes all conditions met, copy the extended data record to destination buffer. memcpy(&DestBuffer[destBufferIndex], &extData->data[posInExtData], (size_t)extendedDataRecordClass->DataSize); /** @req DEM075 */ destBufferIndex += (uint8)extendedDataRecordClass->DataSize; readFailed = FALSE; } } else { if( NULL != extendedDataRecordClass->CallbackGetExtDataRecord ) { if(E_OK == extendedDataRecordClass->CallbackGetExtDataRecord(&DestBuffer[destBufferIndex])) { readFailed = FALSE; } destBufferIndex += (uint8)extendedDataRecordClass->DataSize; } else if (DEM_NO_ELEMENT != extendedDataRecordClass->InternalDataElement ) { getInternalElement(eventIdParamPtr, extendedDataRecordClass->InternalDataElement, &DestBuffer[destBufferIndex], extendedDataRecordClass->DataSize ); destBufferIndex += (uint8)extendedDataRecordClass->DataSize; readFailed = FALSE; } else { /* No callback and no internal element. * IMPROVMENT: Det_error */ } } } if( readFailed == TRUE) { /* Something failed reading the data */ done = TRUE; ret = E_NOT_OK; } extdataIndex++; } } } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETEVENTEXTENDEDDATARECORD_ID, DEM_E_UNINIT); } *BufSize = destBufferIndex; return ret; } /** * Gets the data of an extended data record by event * @param EventId * @param RecordNumber * @param DestBuffer * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ Std_ReturnType Dem_GetEventExtendedDataRecord(Dem_EventIdType EventId, uint8 RecordNumber, uint8* DestBuffer) { uint8 Bufsize = 0; /* Dummy size not used */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTEXTENDEDDATARECORD_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV((NULL != DestBuffer), DEM_GETEVENTEXTENDEDDATARECORD_ID, DEM_E_PARAM_POINTER, E_NOT_OK); return Dem_GetEventExtendedDataRecord_Internal(EventId, RecordNumber, DestBuffer, &Bufsize, FALSE); } #if (DEM_TRIGGER_DLT_REPORTS == STD_ON) /** * Gets all the data of an extended data record by event for DLT * @param EventId * @param DestBuffer * @param BufSize * @return E_OK: Operation was successful, E_NOT_OK: Operation failed */ Std_ReturnType Dem_DltGetAllExtendedDataRecords(Dem_EventIdType EventId, uint8* DestBuffer, uint8* BufSize){ /* @req DEM634 */ /* @req DEM635 */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_DLTGETALLEXTENDEDDATARECORDS_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(((NULL != DestBuffer) && (NULL != BufSize)), DEM_DLTGETALLEXTENDEDDATARECORDS_ID, DEM_E_PARAM_POINTER, E_NOT_OK); return Dem_GetEventExtendedDataRecord_Internal(EventId, ALL_EXTENDED_DATA_RECORDS, DestBuffer, BufSize, TRUE); } #endif #if ( DEM_PRESTORAGE_FF_DATA_IN_MEM ) /** * Captures the freeze frame data for a specific event. * @param EventId * @return E_OK: Freeze frame prestorage was successful, E_NOT_OK: Freeze frame prestorage failed */ /* @req DEM188 */ /* @req DEM189 */ /* @req DEM334 */ Std_ReturnType Dem_PrestoreFreezeFrame(Dem_EventIdType EventId) { Std_ReturnType ret = E_NOT_OK; const Dem_EventParameterType *eventParam; EventStatusRecType *eventStatusRec = NULL; FreezeFrameRecType freezeFrame = {0}; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_PRE_STORE_FF_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(IS_VALID_EVENT_ID(EventId), DEM_PRE_STORE_FF_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* Find eventParameter to each eventId belongs */ lookupEventIdParameter(EventId, &eventParam); /* Find event status */ lookupEventStatusRec(EventId, &eventStatusRec); if ( (eventParam != NULL) && (eventStatusRec != NULL) ) { if (eventStatusRec->isAvailable == TRUE) { if (eventParam->EventClass->FFPrestorageSupported == TRUE) { /* To see if it is NON-OBD check if there is a FF class configured for this event */ if( DEM_FF_NULLREF != getFFIdx(eventParam)) { getFreezeFrameData(eventParam, &freezeFrame, DEM_FREEZE_FRAME_NON_OBD, DEM_DTC_ORIGIN_NOT_USED, TRUE); if (freezeFrame.eventId != DEM_EVENT_ID_NULL) { /* is there already pre-stored FFs */ if (storeFreezeFrameDataMem(eventParam, &freezeFrame, memPreStoreFreezeFrameBuffer, DEM_MAX_NUMBER_PRESTORED_FF, DEM_DTC_ORIGIN_NOT_USED) == TRUE) { /** @req DEM190 */ ret = E_OK; } } } /* check for OBD */ if( DEM_NON_EMISSION_RELATED != (Dem_Arc_EventDTCKindType) *eventParam->EventDTCKind ) { getFreezeFrameData(eventParam, &freezeFrame, DEM_FREEZE_FRAME_OBD, DEM_DTC_ORIGIN_NOT_USED, FALSE); if (freezeFrame.eventId != DEM_EVENT_ID_NULL) { /* is there already pre-stored OBD FFs */ if (storeFreezeFrameDataMem(eventParam, &freezeFrame, memPreStoreFreezeFrameBuffer, DEM_MAX_NUMBER_PRESTORED_FF, DEM_DTC_ORIGIN_NOT_USED) == TRUE) { /** @req DEM190 */ ret = E_OK; } } } } } } return ret; } /** * Clears a prestored freeze frame of a specific event. * @param EventId * @return E_OK: Clear prestored freeze frame was successful, E_NOT_OK: Clear prestored freeze frame failed */ /* @req DEM193 */ /* @req DEM050 */ /* @req DEM334 */ Std_ReturnType Dem_ClearPrestoredFreezeFrame(Dem_EventIdType EventId) { Std_ReturnType ret = E_NOT_OK; const Dem_EventParameterType *eventParam; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_CLEAR_PRE_STORED_FF_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(IS_VALID_EVENT_ID(EventId), DEM_CLEAR_PRE_STORED_FF_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* Find eventParameter to each eventId belongs */ lookupEventIdParameter(EventId, &eventParam); if ( eventParam != NULL ) { if (eventParam->EventClass->FFPrestorageSupported == TRUE) { boolean combinedDTC = FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( DEM_COMBINED_EVENT_NO_DTC_ID != eventParam->CombinedDTCCID ) { combinedDTC = TRUE; } #endif /* It could be OBD or non-OBD */ if (deleteFreezeFrameDataMem(eventParam, DEM_DTC_ORIGIN_NOT_USED, combinedDTC) == TRUE) { /** @req DEM190 */ ret = E_OK; } } else { ret = E_NOT_OK; // DemFFPrestorage is not supported for this EventClass } } else { ret = E_NOT_OK; // Event ID not configured or set to not available } return ret; } #endif /** * Gets the event memory overflow indication status * @param DTCOrigin * @param OverflowIndication * @return E_OK: Operation was successful, E_NOT_OK: Operation failed or is not supported */ /* @req DEM559 *//* @req DEM398 */ Std_ReturnType Dem_GetEventMemoryOverflow(Dem_DTCOriginType DTCOrigin, boolean *OverflowIndication) { VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETEVENTMEMORYOVERFLOW_ID, DEM_E_UNINIT, E_NOT_OK) VALIDATE_RV(NULL != OverflowIndication, DEM_GETEVENTMEMORYOVERFLOW_ID, DEM_E_PARAM_POINTER, E_NOT_OK); return getOverflowIndication(DTCOrigin, OverflowIndication); } #if (DEM_UNIT_TEST == STD_ON) #if ( DEM_FF_DATA_IN_PRE_INIT ) void getFFDataPreInit(FreezeFrameRecType **buf); void getFFDataPreInit(FreezeFrameRecType **buf) { *buf = &preInitFreezeFrameBuffer[0]; return; } #endif #if (DEM_USE_TIMESTAMPS == STD_ON) uint32 getCurTimeStamp(void) { return FF_TimeStamp; } #endif void getEventStatusBufPtr(EventStatusRecType **buf); void getEventStatusBufPtr(EventStatusRecType **buf) { *buf = &eventStatusBuffer[0]; return; } #endif /* DEM_UNIT_TEST */ /**************** * OBD-specific * ***************/ /* * Procedure: Dem_GetDTCOfOBDFreezeFrame * Reentrant: No */ /* @req OBD_DEM_REQ_3 */ Std_ReturnType Dem_GetDTCOfOBDFreezeFrame(uint8 FrameNumber, uint32* DTC ) { /* @req DEM623 */ const FreezeFrameRecType *freezeFrame = NULL; const Dem_EventParameterType *eventParameter = NULL; Std_ReturnType returnCode = E_NOT_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETDTCOFOBDFREEZEFRAME_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(NULL != DTC, DEM_GETDTCOFOBDFREEZEFRAME_ID, DEM_E_PARAM_POINTER, E_NOT_OK); VALIDATE_RV(0 == FrameNumber, DEM_GETDTCOFOBDFREEZEFRAME_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* find the corresponding FF in FF buffer */ /* @req OBD_DEM_REQ_1 */ #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) for(uint16 i = 0; i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM; i++){ if((priMemFreezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL) && (DEM_FREEZE_FRAME_OBD == priMemFreezeFrameBuffer[i].kind)){ freezeFrame = &priMemFreezeFrameBuffer[i]; break; } } #endif /*if FF found,find the corresponding eventParameter*/ if( freezeFrame != NULL ) { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( !IS_COMBINED_EVENT_ID(freezeFrame->eventId) ) { /* Only do this if the entry is NOT a combined event entry. This to avoid Det error. */ lookupEventIdParameter(freezeFrame->eventId, &eventParameter); } #else lookupEventIdParameter(freezeFrame->eventId, &eventParameter); #endif if(eventParameter != NULL){ /* if DTCClass configured,get DTC value */ if((eventParameter->DTCClassRef != NULL) && (DTCIsAvailable(eventParameter->DTCClassRef) == TRUE) && (eventHasDTCOnFormat(eventParameter, DEM_DTC_FORMAT_OBD) == TRUE)){ *DTC = TO_OBD_FORMAT(eventParameter->DTCClassRef->DTCRef->OBDDTC); returnCode = E_OK; } else { /* Event has no DTC or DTC is suppressed */ /* @req 4.2.2/SWS_Dem_01101 *//* @req DEM587 */ } } #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) else { if( IS_COMBINED_EVENT_ID(freezeFrame->eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(freezeFrame->eventId)]; if( (TRUE == DTCISAvailableOnFormat(CombDTCCfg->DTCClassRef, DEM_DTC_FORMAT_OBD)) && (TRUE == DTCIsAvailable(CombDTCCfg->DTCClassRef)) ) { *DTC = TO_OBD_FORMAT(CombDTCCfg->DTCClassRef->DTCRef->OBDDTC); returnCode = E_OK; } } } #endif } return returnCode; } /* * Procedure: Dem_ReadDataOfOBDFreezeFrame * Reentrant: No */ /* @req OBD_DEM_REQ_2 */ /*lint -efunc(818,Dem_ReadDataOfOBDFreezeFrame) Pointers cannot be declared as pointing to const as API defined by AUTOSAR */ Std_ReturnType Dem_ReadDataOfOBDFreezeFrame(uint8 PID, uint8 DataElementIndexOfPid, uint8* DestBuffer, uint8* BufSize) { /* IMPROVEMENT: Validate parameters */ /* @req DEM596 */ VALIDATE_RV(DEM_INITIALIZED == demState, DEM_READDATAOFOBDFREEZEFRAME_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(NULL != DestBuffer, DEM_READDATAOFOBDFREEZEFRAME_ID, DEM_E_PARAM_POINTER, E_NOT_OK); VALIDATE_RV(NULL != BufSize, DEM_READDATAOFOBDFREEZEFRAME_ID, DEM_E_PARAM_POINTER, E_NOT_OK); Std_ReturnType returnCode = E_NOT_OK; /* IMPROVEMENT: DataElementIndexOfPid should be used to get the data of the Pid. But we only support 1 data element * per Pid.. */ (void)DataElementIndexOfPid; #if (DEM_MAX_NR_OF_PIDS_IN_FREEZEFRAME_DATA > 0) const FreezeFrameRecType *freezeFrame = NULL; const Dem_FreezeFrameClassType *freezeFrameClass; boolean pidFound = FALSE; uint16 offset = 0; uint8 pidDataSize = 0u; SchM_Enter_Dem_EA_0(); freezeFrameClass = configSet->GlobalOBDFreezeFrameClassRef; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) uint8 bufSizeLeft = *BufSize; uint32 timestamp = 0u; for(uint16 i = 0u; i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM; i++) { /* @req OBD_DEM_REQ_1 */ if((priMemFreezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL) && (DEM_FREEZE_FRAME_OBD == priMemFreezeFrameBuffer[i].kind)) { freezeFrame = &priMemFreezeFrameBuffer[i]; if( (freezeFrameClass->FFIdClassRef != NULL) && ((FALSE == pidFound) || (priMemFreezeFrameBuffer[i].timeStamp < timestamp)) ) { timestamp = priMemFreezeFrameBuffer[i].timeStamp; offset = 0u; for(uint16 pidIdx = 0u; (pidIdx < DEM_MAX_NR_OF_PIDS_IN_FREEZEFRAME_DATA) && ((freezeFrameClass->FFIdClassRef[pidIdx]->Arc_EOL) == FALSE); pidIdx++) { offset += DEM_PID_IDENTIFIER_SIZE_OF_BYTES; if(freezeFrameClass->FFIdClassRef[pidIdx]->PidIdentifier == PID) { pidFound = TRUE; /* Found. Copy the data. */ if( (bufSizeLeft >= freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize) && (PID == (freezeFrame->data[offset - DEM_PID_IDENTIFIER_SIZE_OF_BYTES])) && ((offset + (uint16)freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize) <= (uint16)(freezeFrame->dataSize)) && ((offset + (uint16)freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize) <= DEM_MAX_SIZE_FF_DATA)) { memcpy(&DestBuffer[pidDataSize], &freezeFrame->data[offset], (size_t)freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize); returnCode = E_OK; } else { /* Something wrong */ returnCode = E_NOT_OK; } pidDataSize = freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize; break; } else { offset += (uint16)freezeFrameClass->FFIdClassRef[pidIdx]->PidOrDidSize; } } } } } if( (E_OK == returnCode) && (TRUE == pidFound) ) { *BufSize = pidDataSize; } #else #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) /*find the corresponding FF in FF buffer*/ for(uint16 i = 0u; i < DEM_MAX_NUMBER_FF_DATA_PRI_MEM; i++) { /* @req OBD_DEM_REQ_1 */ if((priMemFreezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL) && (DEM_FREEZE_FRAME_OBD == priMemFreezeFrameBuffer[i].kind)) { freezeFrame = &priMemFreezeFrameBuffer[i]; break; } } #endif /*if FF class found,find the corresponding PID*/ if(NULL != freezeFrame) { offset = 0u; if(freezeFrameClass->FFKind == DEM_FREEZE_FRAME_OBD) { if(freezeFrameClass->FFIdClassRef != NULL){ for(uint16 i = 0u; (i < DEM_MAX_NR_OF_PIDS_IN_FREEZEFRAME_DATA) && ((freezeFrameClass->FFIdClassRef[i]->Arc_EOL) == FALSE); i++) { offset += DEM_PID_IDENTIFIER_SIZE_OF_BYTES; if(freezeFrameClass->FFIdClassRef[i]->PidIdentifier == PID){ pidDataSize = freezeFrameClass->FFIdClassRef[i]->PidOrDidSize; pidFound = TRUE; break; } else{ offset += (uint16)freezeFrameClass->FFIdClassRef[i]->PidOrDidSize; } } } } } if( (TRUE == pidFound) && (NULL != freezeFrame) && (offset >= DEM_PID_IDENTIFIER_SIZE_OF_BYTES) ) { if(((*BufSize) >= pidDataSize) && (PID == (freezeFrame->data[offset - DEM_PID_IDENTIFIER_SIZE_OF_BYTES])) && ((offset + (uint16)pidDataSize) <= (uint16)(freezeFrame->dataSize)) && ((offset + (uint16)pidDataSize) <= DEM_MAX_SIZE_FF_DATA)) { memcpy(DestBuffer, &freezeFrame->data[offset], (size_t)pidDataSize); *BufSize = pidDataSize; returnCode = E_OK; } } #endif SchM_Exit_Dem_EA_0(); #else (void)PID; #endif return returnCode; } /* * Procedure: storeOBDFreezeFrameDataMem * Description: store OBD FreezeFrame data record in primary memory */ #ifdef DEM_USE_MEMORY_FUNCTIONS #if ( DEM_FF_DATA_IN_PRE_INIT || DEM_FF_DATA_IN_PRI_MEM ) static boolean storeOBDFreezeFrameDataMem(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *freezeFrame, FreezeFrameRecType* freezeFrameBuffer, uint32 freezeFrameBufferSize, Dem_DTCOriginType origin) { boolean eventIdFound = FALSE; boolean eventIdFreePositionFound = FALSE; uint32 i; boolean dataStored = FALSE; #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && (DEM_MAX_NUM_OBD_FFS > 1) const Dem_EventParameterType *eventParameter; #endif (void)origin; /* Check if already stored */ for (i = 0uL; (i < freezeFrameBufferSize) && (FALSE == eventIdFound); i++){ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && (DEM_MAX_NUM_OBD_FFS > 1) /* Need to be able to store more than one OBD FF. Allow storage if not already stored for this * event or for some other DTC. */ if( (freezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL) && (freezeFrameBuffer[i].kind == DEM_FREEZE_FRAME_OBD) ) { /* Found an OBD freeze frame. Check event ID. */ if( freezeFrameBuffer[i].eventId != eventParam->EventID ) { eventParameter = NULL_PTR; lookupEventIdParameter(freezeFrameBuffer[i].eventId, &eventParameter); if( NULL_PTR != eventParameter ) { if( (NULL_PTR != eventParameter->DTCClassRef) && (NULL_PTR != eventParam->DTCClassRef) && (eventParameter->DTCClassRef != eventParam->DTCClassRef) ) { /* Freeze frame is for different DTC. */ eventIdFound = TRUE; } } } else { /* Same ID. */ eventIdFound = TRUE; } } #else eventIdFound = ((freezeFrameBuffer[i].eventId != DEM_EVENT_ID_NULL) && (freezeFrameBuffer[i].kind == DEM_FREEZE_FRAME_OBD))? TRUE: FALSE; #endif /* DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2 */ } if ( FALSE == eventIdFound ) { /* find the first free position */ for (i = 0uL; (i < freezeFrameBufferSize) && (FALSE == eventIdFreePositionFound); i++){ eventIdFreePositionFound = (freezeFrameBuffer[i].eventId == DEM_EVENT_ID_NULL)? TRUE: FALSE; } /* if found,copy it to this position */ if ( TRUE == eventIdFreePositionFound ) { memcpy(&freezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); } else { #if (DEM_EVENT_DISPLACEMENT_SUPPORT == STD_ON) /* if not found,do displacement */ FreezeFrameRecType *freezeFrameLocal = NULL; if( TRUE == lookupFreezeFrameForDisplacement(eventParam, &freezeFrameLocal, freezeFrameBuffer, freezeFrameBufferSize) ) { if(freezeFrameLocal != NULL){ memcpy(freezeFrameLocal, freezeFrame, sizeof(FreezeFrameRecType)); dataStored = TRUE; } else { setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); } } #else setOverflowIndication(eventParam->EventClass->EventDestination, TRUE); DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_STORE_FF_DATA_MEM_ID, DEM_E_MEM_FF_DATA_BUFF_FULL); #endif /* DEM_EVENT_DISPLACEMENT_SUPPORT */ } } else { #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2) && (DEM_MAX_NUM_OBD_FFS > 1) /* OBD freeze frame was already stored. Check if we should replace it. * We replace it if the new event has higher priority than all the ones * previously stored. */ /* Check all OBD FFs stored */ boolean replaceOBDFF = TRUE; const Dem_EventParameterType *storedEventParam; for (uint32 idx = 0uL; (idx < freezeFrameBufferSize) && (TRUE == replaceOBDFF); idx++){ if( (freezeFrameBuffer[idx].eventId != DEM_EVENT_ID_NULL) && (freezeFrameBuffer[idx].kind == DEM_FREEZE_FRAME_OBD) ) { storedEventParam = NULL_PTR; lookupEventIdParameter(freezeFrameBuffer[idx].eventId, &storedEventParam); if( NULL_PTR != storedEventParam ) { if( storedEventParam->EventClass->EventPriority <= eventParam->EventClass->EventPriority ) { /* Priority of stored event is higher. We should not replace the FF. */ replaceOBDFF = FALSE; } } } } if( TRUE == replaceOBDFF ) { /* We should replace the currently stored OBF FF. There could be more than one stored so * we need to loop through the whole buffer again. */ for (uint32 idx = 0UL; idx < freezeFrameBufferSize; idx++){ if( (freezeFrameBuffer[idx].eventId != DEM_EVENT_ID_NULL) && (freezeFrameBuffer[idx].kind == DEM_FREEZE_FRAME_OBD) ) { #if 0 memset(&freezeFrameBuffer[idx], 0, sizeof(FreezeFrameRecType)); #else freezeFrameBuffer[idx].eventId = DEM_EVENT_ID_NULL; #endif } } memcpy(&freezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); dataStored = TRUE; } #else /* OBD freeze frame was already stored. Check if we should replace it. * We replace it if the new event has higher priority. */ const Dem_EventParameterType *storedEventParam = NULL; boolean replaceOBDFF = TRUE; uint8 priorityStored = 0xFFu;/* Lowest prio. */ #if defined(DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE1) if( IS_COMBINED_EVENT_ID(freezeFrameBuffer[i-1].eventId) ) { const Dem_CombinedDTCCfgType *CombDTCCfg = &configSet->CombinedDTCConfig[TO_COMBINED_EVENT_CFG_IDX(freezeFrameBuffer[i-1].eventId)]; priorityStored = CombDTCCfg->Priority; } else { lookupEventIdParameter(freezeFrameBuffer[i-1].eventId, &storedEventParam); if( NULL != storedEventParam ) { priorityStored = storedEventParam->EventClass->EventPriority; } } #else lookupEventIdParameter(freezeFrameBuffer[i-1].eventId, &storedEventParam); if( NULL != storedEventParam ) { priorityStored = storedEventParam->EventClass->EventPriority; } #endif if( priorityStored <= eventParam->EventClass->EventPriority ) { /* Priority of the new event is lower or equal to the stored event. * Should NOT replace the FF. */ replaceOBDFF = FALSE; } if( TRUE == replaceOBDFF ) { memcpy(&freezeFrameBuffer[i-1], freezeFrame, sizeof(FreezeFrameRecType)); dataStored = TRUE; } #endif/* DEM_EVENT_COMBINATION_DEM_EVCOMB_TYPE2 */ } return dataStored; } #endif /* DEM_FF_DATA_IN_PRE_INIT || DEM_FF_DATA_IN_PRI_MEM */ #endif /* DEM_USE_MEMORY_FUNCTIONS */ #if (DEM_OBD_SUPPORT == STD_ON) /** * Service for reporting the event as disabled to the Dem for the PID $41 computation. * * @param EventId: identification of an event by assigned EventId. * @return E_OK set of event to disabled was successful. */ Std_ReturnType Dem_SetEventDisabled(Dem_EventIdType EventId ) { /* @req Dem312 */ /* @req Dem348 */ /* @req Dem294 */ EventStatusRecType *eventStatusRec = NULL; SchM_Enter_Dem_EA_0(); lookupEventStatusRec(EventId, &eventStatusRec); eventStatusRec->isDisabled = 1; SchM_Exit_Dem_EA_0(); return E_OK; } /** * Gets the number of confirmed OBD DTCs. * * @return the number of confirmed OBD DTCs, between 0 and 127. */ static uint8_t getNumberOfConfirmedObdDTCs(void) { /* @req DEM351 */ uint8_t confirmedBitMask = DEM_CONFIRMED_DTC; uint16_t confirmedDTCs = 0; if (DEM_FILTER_ACCEPTED == Dem_SetDTCFilter(confirmedBitMask, DEM_DTC_KIND_EMISSION_REL_DTCS, DEM_DTC_FORMAT_OBD, DEM_DTC_ORIGIN_PRIMARY_MEMORY, DEM_FILTER_WITH_SEVERITY_NO, DEM_SEVERITY_NO_SEVERITY, DEM_FILTER_FOR_FDC_NO)) { while (Dem_GetNumberOfFilteredDtc(&confirmedDTCs) == DEM_NUMBER_PENDING) { // wait until it either succeeded or failed } // Can store at most a non-negative number of 6 bits (127) if (confirmedDTCs > 127) { confirmedDTCs = 127; } } return (uint8_t) confirmedDTCs; } /** * Gets the MIL status. * * @param numberOfConfirmedDtcs: The number of confirmed OBD DTCs. * @return TRUE if MIL is ON, otherwise FALSE. */ static uint8_t isObdMilOn(uint8_t numberOfConfirmedDtcs) { /* @req DEM352 */ uint8 milStatus = 0; // According to req. DEM544, SAE J1979 and CARB OBD legislation, // this status should reflect if there is any confirmed DTC, // NOT if the MIL bulb is lit up, as it can be ON for different reasons as well (see SAE J1979). if (0u != numberOfConfirmedDtcs) { milStatus = 1; } return milStatus; } /** * Checks if the the event (test) has been marked as completed since last clear. * If the event (test) failed, it will be reported as incomplete. * * @param eventIndex: the event's current location in the event status buffer. * @return TRUE if test is complete, otherwise FALSE. */ static boolean isMonitoringNotCompleteSinceLastClear(uint16 eventIndex) { boolean testFailedSinceLastClear = (0 != (eventStatusBuffer[eventIndex].eventStatusExtended & DEM_TEST_FAILED_SINCE_LAST_CLEAR))? TRUE: FALSE; boolean monitoringNotComplete = (0 != (eventStatusBuffer[eventIndex].eventStatusExtended & DEM_TEST_NOT_COMPLETED_SINCE_LAST_CLEAR))? TRUE: FALSE; monitoringNotComplete |= testFailedSinceLastClear; return monitoringNotComplete; } #if (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_SPARK) /** * Service to report the value of PID $01 computed by the Dem. * Reentrant: Yes * * FOR SPARK ENGINE CONFIGURATION * * @param PID01value: Buffer containing the contents of PID $01 computed by the Dem. * @return Always E_OK is returned, as E_NOT_OK will never appear.. */ Std_ReturnType Dem_DcmReadDataOfPID01(uint8* PID01value) { // Reset PID value PID01value[0] = 0; // Byte A PID01value[1] = 0; // Byte B PID01value[2] = 0; // Byte C PID01value[3] = 0; // Byte D /** * Get number of confirmed OBD DTCs (Byte A) */ uint8_t confirmedDTCs = getNumberOfConfirmedObdDTCs(); /** * Get MIL status (Byte A) */ uint8_t milStatus = isObdMilOn(confirmedDTCs); /** * Get engine systems' monitors availability (Byte B and C) * * Get engine systems' monitors readiness (Byte B and D) */ boolean ENG_TYPE = 0; // Compression ignition monitoring supported boolean MIS_SUP = 0; // Misfire monitoring supported (All) boolean FUEL_SUP = 0; // Fuel system monitoring supported (All) boolean CCM_SUP = 0; // Comprehensive component monitoring supported (All) boolean CAT_SUP = 0; // Catalyst monitoring supported (Gasoline) boolean HCAT_SUP = 0; // Heated catalyst monitoring supported (Gasoline) boolean EVAP_SUP = 0; // Evaporative system monitoring supported (Gasoline) boolean AIR_SUP = 0; // Secondary air system monitoring supported (Gasoline) boolean ACRF_SUP = 0; // A/C system refrigerant monitoring supported (Gasoline) boolean O2S_SUP = 0; // Oxygen sensor monitoring supported (Gasoline) boolean HTR_SUP = 0; // Oxygen sensor heater monitoring supported (Gasoline) boolean EGR_SUP = 0; // EGR system monitoring supported (All) boolean MIS_RDY = 0; // Misfire monitoring ready (All) boolean FUEL_RDY = 0; // Fuel system monitoring ready (All) boolean CCM_RDY = 0; // Comprehensive component monitoring ready (All) boolean CAT_RDY = 0; // Catalyst monitoring ready (Gasoline) boolean HCAT_RDY = 0; // Heated catalyst monitoring ready (Gasoline) boolean EVAP_RDY = 0; // Evaporative system monitoring ready (Gasoline) boolean AIR_RDY = 0; // Secondary air system monitoring ready (Gasoline) boolean ACRF_RDY = 0; // A/C system refrigerant monitoring ready (Gasoline) boolean O2S_RDY = 0; // Oxygen sensor monitoring ready (Gasoline) boolean HTR_RDY = 0; // Oxygen sensor heater monitoring ready (Gasoline) boolean EGR_RDY = 0; // EGR system monitoring ready (All) // Quoted from ASR 4.3: // According to SAEJ1979, the group AirCondition Component (ACRF) shall not be supported anymore. // However, it is still included in ISO 15031-5. /* @req DEM354 */ for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if (DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) { Dem_EventOBDReadinessGroup readinessGroup = eventStatusBuffer[i].eventParamRef->EventClass->OBDReadinessGroup; boolean monitoringNotComplete = isMonitoringNotCompleteSinceLastClear(i); switch(readinessGroup) { case DEM_OBD_RDY_MISF: MIS_SUP = 1; MIS_RDY = 0; // Always complete break; case DEM_OBD_RDY_FLSYS: FUEL_SUP = 1; FUEL_RDY = 0; // Always complete break; case DEM_OBD_RDY_CMPRCMPT: CCM_SUP = 1; CCM_RDY = 0; // Always complete break; case DEM_OBD_RDY_CAT: CAT_SUP = 1; CAT_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_HTCAT: HCAT_SUP = 1; HCAT_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_EVAP: EVAP_SUP = 1; EVAP_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_SECAIR: AIR_SUP = 1; AIR_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_AC: ACRF_SUP = 1; ACRF_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_O2SENS: O2S_SUP = 1; O2S_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_O2SENSHT: HTR_SUP = 1; HTR_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_ERG: EGR_SUP = 1; EGR_RDY |= monitoringNotComplete; break; } } } /** * Pack availability and readiness values */ // Byte A PID01value[0] = confirmedDTCs | (milStatus << 6); // Byte B PID01value[1] = (uint8)((MIS_SUP << 0) | (FUEL_SUP << 1) | (CCM_SUP << 2) | (ENG_TYPE << 3) | (MIS_RDY << 4) | (FUEL_RDY << 5) | (CCM_RDY << 6)); // Bit 7 reserved // Byte C PID01value[2] = (uint8)((CAT_SUP << 0) | (HCAT_SUP << 1) | (EVAP_SUP << 2) | (AIR_SUP << 3) | (ACRF_SUP << 4) | (O2S_SUP << 5) | (HTR_SUP << 6) | (EGR_SUP << 7)); // Byte D PID01value[3] = (uint8)((CAT_RDY << 0) | (HCAT_RDY << 1) | (EVAP_RDY << 2) | (AIR_RDY << 3) | (ACRF_RDY << 4) | (O2S_RDY << 5) | (HTR_RDY << 6) | (EGR_RDY << 7)); return E_OK; } #elif (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_COMPR) /** * Service to report the value of PID $01 computed by the Dem. * Reentrant: Yes * * FOR COMPRESSION ENGINE CONFIGURATION * * @param PID01value: buffer containing the contents of PID $01 computed by the Dem. * @return Always E_OK is returned, as E_NOT_OK will never appear. */ Std_ReturnType Dem_DcmReadDataOfPID01(uint8* PID01value) { // Reset PID value PID01value[0] = 0; // Byte A PID01value[1] = 0; // Byte B PID01value[2] = 0; // Byte C PID01value[3] = 0; // Byte D /** * Get number of confirmed OBD DTCs (Byte A) */ uint8_t confirmedDTCs = getNumberOfConfirmedObdDTCs(); /** * Get MIL status (Byte A) */ uint8_t milStatus = isObdMilOn(confirmedDTCs); /** * Get engine systems' monitors availability (Byte B and C) * * Get engine systems' monitors readiness (Byte B and D) */ boolean ENG_TYPE = 0; // Compression ignition monitoring supported boolean MIS_SUP = 0; // Misfire monitoring supported (All) boolean FUEL_SUP = 0; // Fuel system monitoring supported (All) boolean CCM_SUP = 0; // Comprehensive component monitoring supported (All) boolean HCCATSUP = 0; // NMHC catalyst monitoring supported (Diesel) boolean NCAT_SUP = 0; // NOx aftertreatment monitoring supported (Diesel) boolean BP_SUP = 0; // Boost pressure system monitoring supported (Diesel) boolean EGS_SUP = 0; // Exhaust gas sensor monitoring supported (Diesel) boolean PM_SUP = 0; // PM Filter monitoring supported (Diesel) boolean EGR_SUP = 0; // EGR system monitoring supported (All) boolean MIS_RDY = 0; // Misfire monitoring ready (All) boolean FUEL_RDY = 0; // Fuel system monitoring ready (All) boolean CCM_RDY = 0; // Comprehensive component monitoring ready (All) boolean HCCATRDY = 0; // NMHC catalyst monitoring ready (Diesel) boolean NCAT_RDY = 0; // NOx aftertreatment monitoring ready (Diesel) boolean BP_RDY = 0; // Boost pressure system monitoring ready (Diesel) boolean EGS_RDY = 0; // Exhaust gas sensor monitoring ready (Diesel) boolean PM_RDY = 0; // PM Filter monitoring ready (Diesel) boolean EGR_RDY = 0; // EGR system monitoring ready (All) ENG_TYPE = 1; /* @req DEM354 */ for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if (DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) { Dem_EventOBDReadinessGroup readinessGroup = eventStatusBuffer[i].eventParamRef->EventClass->OBDReadinessGroup; boolean monitoringNotComplete = isMonitoringNotCompleteSinceLastClear(i); switch(readinessGroup) { case DEM_OBD_RDY_MISF: MIS_SUP = 1; MIS_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_FLSYS: FUEL_SUP = 1; FUEL_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_CMPRCMPT: CCM_SUP = 1; CCM_RDY = 0; break; case DEM_OBD_RDY_HCCAT: HCCATSUP = 1; HCCATRDY |= monitoringNotComplete; break; case DEM_OBD_RDY_NOXCAT: NCAT_SUP = 1; NCAT_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_BOOSTPR: BP_SUP = 1; BP_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_EGSENS: EGS_SUP = 1; EGS_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_PMFLT: PM_SUP = 1; PM_RDY |= monitoringNotComplete; break; case DEM_OBD_RDY_ERG: EGR_SUP = 1; EGR_RDY |= monitoringNotComplete; break; } } } /** * Pack availability and readiness values */ // Byte A PID01value[0] = ((uint8) confirmedDTCs) | (milStatus << 6); // Byte B PID01value[1] = (MIS_SUP << 0) | (FUEL_SUP << 1) | (CCM_SUP << 2) | (ENG_TYPE << 3) | (MIS_RDY << 4) | (FUEL_RDY << 5) | (CCM_RDY << 6); // Bit 7 reserved // Byte C PID01value[2] = (HCCATSUP << 0) | (NCAT_SUP << 1) | (BP_SUP << 3) | (EGS_SUP << 5) | (PM_SUP << 6) | (EGR_SUP << 7); // bit 2 reserved // bit 4 reserved // Byte D PID01value[3] = (HCCATRDY << 0) | (NCAT_RDY << 1) | (BP_RDY << 3) | (EGS_RDY << 5) | (PM_RDY << 6) | (EGR_RDY << 7); // bit 2 reserved // bit 4 reserved return E_OK; } #endif /** * Checks whether the event (test) has been marked as completed in current driving cycle. * If the event (test) failed, it will be reported as incomplete. * * @param eventIndex: the event's current location in the event status buffer. * @return TRUE if test is complete, otherwise FALSE. */ static DEM_TRISTATE isMonitoringNotCompleteThisDrivingCycle(uint16 eventIndex) { DEM_TRISTATE testFailedThisOperationCycle = (0 != (eventStatusBuffer[eventIndex].eventStatusExtended & DEM_TEST_FAILED_THIS_OPERATION_CYCLE))? 1: 0; DEM_TRISTATE monitoringNotComplete = (0 != (eventStatusBuffer[eventIndex].eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE))? 1: 0; monitoringNotComplete |= testFailedThisOperationCycle; DEM_TRISTATE isEnabledThisDrivingCycle = (FALSE == eventStatusBuffer[eventIndex].isDisabled)? 1: 0; // If the monitor for the component is disabled for this driving cycle then // set all the relevant tests to complete if (isEnabledThisDrivingCycle == DEM_T_FALSE) { monitoringNotComplete = DEM_T_FALSE; } return monitoringNotComplete; } /** * Sets all NULL values to FALSE. * * @param total: number of values to check. * @param monitorValues: monitor values to reset or keep. */ static void resetOrKeepMonitorValues(uint8_t total, DEM_TRISTATE **monitorValues) { for (uint8_t i = 0; i < total; i++) { *monitorValues[i] = (*monitorValues[i] == DEM_T_NULL) ? DEM_T_FALSE : *monitorValues[i]; } } #if (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_SPARK) /** * Service to report the value of PID $41 computed by the Dem. * Reentrant: Yes * * FOR SPARK ENGINE CONFIGURATION * * @param PID41value: buffer containing the contents of PID $41 computed by the Dem. * @return Always E_OK is returned, as E_NOT_OK will never appear. */ Std_ReturnType Dem_DcmReadDataOfPID41(uint8* PID41value) { // Reset PID value PID41value[0] = 0; // Byte A PID41value[1] = 0; // Byte B PID41value[2] = 0; // Byte C PID41value[3] = 0; // Byte D /** * Get number of confirmed OBD DTCs (Byte A) */ // Does not report the number of confirmed DTCs, keep at 0 /** * Get MIL status (Byte A) */ // Does not report the MIL status, keep at 0 /** * Get engine systems' monitors status (Byte B and C) * * Get engine systems' monitors completion (Byte B and D) */ DEM_TRISTATE ENG_TYPE = DEM_T_FALSE; // Compression ignition monitoring supported DEM_TRISTATE MIS_ENA = DEM_T_NULL; // Misfire monitoring enabled (All) DEM_TRISTATE FUEL_ENA = DEM_T_NULL; // Fuel system monitoring enabled (All) DEM_TRISTATE CCM_ENA = DEM_T_NULL; // Comprehensive component monitoring enabled (All) DEM_TRISTATE CAT_ENA = DEM_T_NULL; // Catalyst monitoring enabled (Gasoline) DEM_TRISTATE HCAT_ENA = DEM_T_NULL; // Heated catalyst monitoring enabled (Gasoline) DEM_TRISTATE EVAP_ENA = DEM_T_NULL; // Evaporative system monitoring enabled (Gasoline) DEM_TRISTATE AIR_ENA = DEM_T_NULL; // Secondary air system monitoring enabled (Gasoline) DEM_TRISTATE ACRF_ENA = DEM_T_NULL; // A/C system refrigerant monitoring enabled (Gasoline) DEM_TRISTATE O2S_ENA = DEM_T_NULL; // Oxygen sensor monitoring enabled (Gasoline) DEM_TRISTATE HTR_ENA = DEM_T_NULL; // Oxygen sensor heater monitoring enabled (Gasoline) DEM_TRISTATE EGR_ENA = DEM_T_NULL; // EGR system monitoring enabled (All) DEM_TRISTATE MIS_CMPL = DEM_T_NULL; // Misfire monitoring complete (All) DEM_TRISTATE FUELCMPL = DEM_T_NULL; // Fuel system monitoring complete (All) DEM_TRISTATE CCM_CMPL = DEM_T_NULL; // Comprehensive component monitoring complete (All) DEM_TRISTATE CAT_CMPL = DEM_T_NULL; // Catalyst monitoring complete (Gasoline) DEM_TRISTATE HCATCMPL = DEM_T_NULL; // Heated catalyst monitoring complete (Gasoline) DEM_TRISTATE EVAPCMPL = DEM_T_NULL; // Evaporative system monitoring complete (Gasoline) DEM_TRISTATE AIR_CMPL = DEM_T_NULL; // Secondary air system monitoring complete (Gasoline) DEM_TRISTATE ACRFCMPL = DEM_T_NULL; // A/C system refrigerant monitoring complete (Gasoline) DEM_TRISTATE O2S_CMPL = DEM_T_NULL; // Oxygen sensor monitoring complete (Gasoline) DEM_TRISTATE HTR_CMPL = DEM_T_NULL; // Oxygen sensor heater monitoring complete (Gasoline) DEM_TRISTATE EGR_CMPL = DEM_T_NULL; // EGR system monitoring complete (All) // Quoted from ASR 4.3: // According to SAEJ1979, the group AirCondition Component shall not be supported anymore. // However, it is still included in ISO 15031-5. /* @req DEM355 */ for (uint16 i = 0u; i < DEM_MAX_NUMBER_EVENT; i++){ if (DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) { Dem_EventOBDReadinessGroup readinessGroup = eventStatusBuffer[i].eventParamRef->EventClass->OBDReadinessGroup; DEM_TRISTATE monitoringNotComplete = isMonitoringNotCompleteThisDrivingCycle(i); DEM_TRISTATE isEnabledThisDrivingCycle = (FALSE == eventStatusBuffer[i].isDisabled)? 1 : 0; switch(readinessGroup) { case DEM_OBD_RDY_MISF: MIS_ENA = (MIS_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (MIS_ENA & isEnabledThisDrivingCycle); MIS_CMPL = DEM_T_FALSE; // Always on break; case DEM_OBD_RDY_FLSYS: FUEL_ENA = (FUEL_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (FUEL_ENA & isEnabledThisDrivingCycle); FUELCMPL = DEM_T_FALSE; // Always on break; case DEM_OBD_RDY_CMPRCMPT: CCM_ENA = (CCM_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (CCM_ENA & isEnabledThisDrivingCycle); CCM_CMPL = DEM_T_FALSE; // Always on break; case DEM_OBD_RDY_CAT: CAT_ENA = (CAT_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (CAT_ENA & isEnabledThisDrivingCycle); CAT_CMPL = (CAT_CMPL == DEM_T_NULL) ? monitoringNotComplete : (CAT_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_HTCAT: HCAT_ENA = (HCAT_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (HCAT_ENA & isEnabledThisDrivingCycle); HCATCMPL = (HCATCMPL == DEM_T_NULL) ? monitoringNotComplete : (HCATCMPL & monitoringNotComplete); break; case DEM_OBD_RDY_EVAP: EVAP_ENA = (EVAP_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (EVAP_ENA & isEnabledThisDrivingCycle); EVAPCMPL = (EVAPCMPL == DEM_T_NULL) ? monitoringNotComplete : (EVAPCMPL & monitoringNotComplete); break; case DEM_OBD_RDY_SECAIR: AIR_ENA = (AIR_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (AIR_ENA & isEnabledThisDrivingCycle); AIR_CMPL = (AIR_CMPL == DEM_T_NULL) ? monitoringNotComplete : (AIR_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_AC: ACRF_ENA = (ACRF_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (ACRF_ENA & isEnabledThisDrivingCycle); ACRFCMPL = (ACRFCMPL == DEM_T_NULL) ? monitoringNotComplete : (ACRFCMPL & monitoringNotComplete); break; case DEM_OBD_RDY_O2SENS: O2S_ENA = (O2S_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (O2S_ENA & isEnabledThisDrivingCycle); O2S_CMPL = (O2S_CMPL == DEM_T_NULL) ? monitoringNotComplete : (O2S_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_O2SENSHT: HTR_ENA = (HTR_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (HTR_ENA & isEnabledThisDrivingCycle); HTR_CMPL = (HTR_CMPL == DEM_T_NULL) ? monitoringNotComplete : (HTR_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_ERG: EGR_ENA = (EGR_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (EGR_ENA & isEnabledThisDrivingCycle); EGR_CMPL = (EGR_CMPL == DEM_T_NULL) ? monitoringNotComplete : (EGR_CMPL & monitoringNotComplete); break; } } } /** * Set remaining NULL systems to FALSE */ DEM_TRISTATE *monitorsEnabled[] = {&MIS_ENA, &FUEL_ENA, &CCM_ENA, &CAT_ENA, &HCAT_ENA, &EVAP_ENA, &AIR_ENA, &ACRF_ENA, &O2S_ENA, &HTR_ENA, &EGR_ENA}; resetOrKeepMonitorValues(11, monitorsEnabled); DEM_TRISTATE *monitorsComplete[] = {&MIS_CMPL, &FUELCMPL, &CCM_CMPL, &CAT_CMPL, &HCATCMPL, &EVAPCMPL, &AIR_CMPL, &ACRFCMPL, &O2S_CMPL, &HTR_CMPL, &EGR_CMPL}; resetOrKeepMonitorValues(11, monitorsComplete); /** * Pack status and completion values */ // Byte A // Both 0, does not report // Byte B PID41value[1] = (uint8)((MIS_ENA << 0) | (FUEL_ENA << 1) | (CCM_ENA << 2) | (ENG_TYPE << 3) | (MIS_CMPL << 4) | (FUELCMPL << 5) | (CCM_CMPL << 6)); // Bit 7 reserved // Byte C PID41value[2] = (uint8)((CAT_ENA << 0) | (HCAT_ENA << 1) | (EVAP_ENA << 2) | (AIR_ENA << 3) | (ACRF_ENA << 4) | (O2S_ENA << 5) | (HTR_ENA << 6) | (EGR_ENA << 7)); // Byte D PID41value[3] = (uint8)((CAT_CMPL << 0) | (HCATCMPL << 1) | (EVAPCMPL << 2) | (AIR_CMPL << 3) | (ACRFCMPL << 4) | (O2S_CMPL << 5) | (HTR_CMPL << 6) | (EGR_CMPL << 7)); return E_OK; } #elif (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_COMPR) /** * Service to report the value of PID $41 computed by the Dem. * Reentrant: Yes * * FOR COMPRESSION ENGINE CONFIGURATION * * @param PID41value: buffer containing the contents of PID $41 computed by the Dem. * @return Always E_OK is returned, as E_NOT_OK will never appear. */ Std_ReturnType Dem_DcmReadDataOfPID41(uint8* PID41value) { // Reset PID value PID41value[0] = 0; // Byte A PID41value[1] = 0; // Byte B PID41value[2] = 0; // Byte C PID41value[3] = 0; // Byte D /** * Get number of confirmed OBD DTCs (Byte A) */ // Does not report the number of confirmed DTCs, keep at 0 /** * Get MIL status (Byte A) */ // Does not report the MIL status, keep at 0 /** * Get engine systems' monitors status (Byte B and C) * * Get engine systems' monitors completion (Byte B and D) */ DEM_TRISTATE ENG_TYPE = DEM_T_FALSE; // Compression ignition monitoring supported DEM_TRISTATE MIS_ENA = DEM_T_NULL; // Misfire monitoring enabled (All) DEM_TRISTATE FUEL_ENA = DEM_T_NULL; // Fuel system monitoring enabled (All) DEM_TRISTATE CCM_ENA = DEM_T_NULL; // Comprehensive component monitoring enabled (All) DEM_TRISTATE HCCATENA = DEM_T_NULL; // NMHC catalyst monitoring enabled (Diesel) DEM_TRISTATE NCAT_ENA = DEM_T_NULL; // NOx aftertreatment monitoring enabled (Diesel) DEM_TRISTATE BP_ENA = DEM_T_NULL; // Boost pressure system monitoring enabled (Diesel) DEM_TRISTATE EGS_ENA = DEM_T_NULL; // Exhaust gas sensor monitoring enabled (Diesel) DEM_TRISTATE PM_ENA = DEM_T_NULL; // PM Filter monitoring enabled (Diesel) DEM_TRISTATE EGR_ENA = DEM_T_NULL; // EGR system monitoring enabled (All) DEM_TRISTATE MIS_CMPL = DEM_T_NULL; // Misfire monitoring complete (All) DEM_TRISTATE FUELCMPL = DEM_T_NULL; // Fuel system monitoring complete (All) DEM_TRISTATE CCM_CMPL = DEM_T_NULL; // Comprehensive component monitoring complete (All) DEM_TRISTATE HCCATCMP = DEM_T_NULL; // NMHC catalyst monitoring complete (Diesel) DEM_TRISTATE NCATCMPL = DEM_T_NULL; // NOx aftertreatment monitoring complete (Diesel) DEM_TRISTATE BP_CMPL = DEM_T_NULL; // Boost pressure system monitoring complete (Diesel) DEM_TRISTATE EGS_CMPL = DEM_T_NULL; // Exhaust gas sensor monitoring complete (Diesel) DEM_TRISTATE PM_CMPL = DEM_T_NULL; // PM Filter monitoring complete (Diesel) DEM_TRISTATE EGR_CMPL = DEM_T_NULL; // EGR system monitoring complete (All) ENG_TYPE = 1; /* @req DEM355 */ for (uint16 i = 0; i < DEM_MAX_NUMBER_EVENT; i++) { if (DEM_EVENT_ID_NULL != eventStatusBuffer[i].eventId) { Dem_EventOBDReadinessGroup readinessGroup = eventStatusBuffer[i].eventParamRef->EventClass->OBDReadinessGroup; DEM_TRISTATE monitoringNotComplete = isMonitoringNotCompleteThisDrivingCycle(i); DEM_TRISTATE isEnabledThisDrivingCycle = (! eventStatusBuffer[i].isDisabled); switch(readinessGroup) { case DEM_OBD_RDY_MISF: MIS_ENA = (MIS_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (MIS_ENA & isEnabledThisDrivingCycle); MIS_CMPL = (MIS_CMPL == DEM_T_NULL) ? monitoringNotComplete : (MIS_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_FLSYS: FUEL_ENA = (FUEL_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (FUEL_ENA & isEnabledThisDrivingCycle); FUELCMPL = (FUELCMPL == DEM_T_NULL) ? monitoringNotComplete : (FUELCMPL & monitoringNotComplete); break; case DEM_OBD_RDY_CMPRCMPT: CCM_ENA = (CCM_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (CCM_ENA & isEnabledThisDrivingCycle); CCM_CMPL = DEM_T_FALSE; // Always on break; case DEM_OBD_RDY_HCCAT: HCCATENA = (HCCATENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (HCCATENA & isEnabledThisDrivingCycle); HCCATCMP = (HCCATCMP == DEM_T_NULL) ? monitoringNotComplete : (HCCATCMP & monitoringNotComplete); break; case DEM_OBD_RDY_NOXCAT: NCAT_ENA = (NCAT_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (NCAT_ENA & isEnabledThisDrivingCycle); NCATCMPL = (NCATCMPL == DEM_T_NULL) ? monitoringNotComplete : (NCATCMPL & monitoringNotComplete); break; case DEM_OBD_RDY_BOOSTPR: BP_ENA = (BP_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (BP_ENA & isEnabledThisDrivingCycle); BP_CMPL = (BP_CMPL == DEM_T_NULL) ? monitoringNotComplete : (BP_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_EGSENS: EGS_ENA = (EGS_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (EGS_ENA & isEnabledThisDrivingCycle); EGS_CMPL = (EGS_CMPL == DEM_T_NULL) ? monitoringNotComplete : (EGS_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_PMFLT: PM_ENA = (PM_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (PM_ENA & isEnabledThisDrivingCycle); PM_CMPL = (PM_CMPL == DEM_T_NULL) ? monitoringNotComplete : (PM_CMPL & monitoringNotComplete); break; case DEM_OBD_RDY_ERG: EGR_ENA = (EGR_ENA == DEM_T_NULL) ? isEnabledThisDrivingCycle : (EGR_ENA & isEnabledThisDrivingCycle); EGR_CMPL = (EGR_CMPL == DEM_T_NULL) ? monitoringNotComplete : (EGR_CMPL & monitoringNotComplete); break; } } } /** * Set remaining NULL systems to FALSE */ DEM_TRISTATE *monitorsEnabled[] = {&MIS_ENA, &FUEL_ENA, &CCM_ENA, &HCCATENA, &NCAT_ENA, &BP_ENA, &EGS_ENA, &PM_ENA, &EGR_ENA}; resetOrKeepMonitorValues(9, monitorsEnabled); DEM_TRISTATE *monitorsComplete[] = {&MIS_CMPL, &FUELCMPL, &CCM_CMPL, &HCCATCMP, &NCATCMPL, &BP_CMPL, &EGS_CMPL, &PM_CMPL, &EGR_CMPL}; resetOrKeepMonitorValues(9, monitorsComplete); /** * Pack status and completion values */ // Byte A // Both 0, does not report // Byte B PID41value[1] = (MIS_ENA << 0) | (FUEL_ENA << 1) | (CCM_ENA << 2) | (ENG_TYPE << 3) | (MIS_CMPL << 4) | (FUELCMPL << 5) | (CCM_CMPL << 6); // Bit 7 reserved // Byte C PID41value[2] = (HCCATENA << 0) | (NCAT_ENA << 1) | (BP_ENA << 3) | (EGS_ENA << 5) | (PM_ENA << 6) | (EGR_ENA << 7); // bit 2 reserved // bit 4 reserved // Byte D PID41value[3] = (HCCATCMP << 0) | (NCATCMPL << 1) | (BP_CMPL << 3) | (EGS_CMPL << 5) | (PM_CMPL << 6) | (EGR_CMPL << 7); // bit 2 reserved // bit 4 reserved return E_OK; } #endif #if defined(DEM_USE_IUMPR) /** * Writes current denominator and numerator of a specific ratio to the given data buffer. * * @param dataBuffer * @param startIndex * @param ratioId */ static void getNumeratorDenominator(uint8* dataBuffer, uint8 startIndex, Dem_RatioIdType ratioId) { uint8 currentIndex = startIndex; // write numerator dataBuffer[currentIndex++] = (uint8)(iumprBufferLocal[ratioId].numerator.value >> 8); dataBuffer[currentIndex++] = (uint8)(iumprBufferLocal[ratioId].numerator.value & 0xFF); // write denominator dataBuffer[currentIndex++] = (uint8)(iumprBufferLocal[ratioId].denominator.value >> 8); dataBuffer[currentIndex] = (uint8)(iumprBufferLocal[ratioId].denominator.value & 0xFF); } /** * Writes general denominator count to data buffer * * @param dataBuffer */ static void getGeneralDenominatorCount(uint8* dataBuffer) { dataBuffer[0] = (uint8)(generalDenominatorBuffer.value >> 8); dataBuffer[1] = (uint8)(generalDenominatorBuffer.value & 0xFF); } /** * Writes ignition cycle count to data buffer * * @param dataBuffer */ static void getIgnitionCycleCount(uint8* dataBuffer) { dataBuffer[2] = (uint8)(ignitionCycleCountBuffer >> 8); dataBuffer[3] = (uint8)(ignitionCycleCountBuffer & 0xFF); } #if (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_SPARK) /* @req DEM357 */ /** * Writes denominator and numerator counts to InfoType0 data buffer depending on IUMPR group * * @param iumprGroup * @param Iumprdata08 */ static void setInfoType08NumsDenoms(Dem_IUMPRGroup iumprGroup, uint8* Iumprdata08, Dem_RatioIdType ratioId) { switch(iumprGroup) { case DEM_IUMPR_CAT1: getNumeratorDenominator(Iumprdata08, 4, ratioId); break; case DEM_IUMPR_CAT2: getNumeratorDenominator(Iumprdata08, 8, ratioId); break; case DEM_IUMPR_OXS1: getNumeratorDenominator(Iumprdata08, 12, ratioId); break; case DEM_IUMPR_OXS2: getNumeratorDenominator(Iumprdata08, 16, ratioId); break; case DEM_IUMPR_EGR: getNumeratorDenominator(Iumprdata08, 20, ratioId); break; case DEM_IUMPR_SAIR: getNumeratorDenominator(Iumprdata08, 24, ratioId); break; case DEM_IUMPR_EVAP: getNumeratorDenominator(Iumprdata08, 28, ratioId); break; case DEM_IUMPR_SECOXS1: getNumeratorDenominator(Iumprdata08, 32, ratioId); break; case DEM_IUMPR_SECOXS2: getNumeratorDenominator(Iumprdata08, 36, ratioId); break; case DEM_IUMPR_AFRI1: getNumeratorDenominator(Iumprdata08, 40, ratioId); break; case DEM_IUMPR_AFRI2: getNumeratorDenominator(Iumprdata08, 44, ratioId); break; case DEM_IUMPR_PF1: getNumeratorDenominator(Iumprdata08, 48, ratioId); break; case DEM_IUMPR_PF2: getNumeratorDenominator(Iumprdata08, 52, ratioId); break; } } #endif /* DEM_USE_IUMPR */ /** * Service is used to request for IUMPR data according to InfoType $08. * Reentrant: Yes * * @param Iumprdata08: Buffer containing the contents of InfoType $08. * The buffer is provided by the Dcm. * @return Always E_OK is returned, as E_PENDING and E_NOT_OK will never appear. */ Std_ReturnType Dem_GetInfoTypeValue08(uint8* Iumprdata08) { /* @req DEM316 */ /* @req DEM298 */ if (Iumprdata08 != NULL_PTR && demState == DEM_INITIALIZED) { // reset data memset(Iumprdata08, 0, 56); // get general denominator count getGeneralDenominatorCount(Iumprdata08); // get ignition cycle count getIgnitionCycleCount(Iumprdata08); for (Dem_RatioIdType ratioId = 0; ratioId < DEM_IUMPR_REGISTERED_COUNT; ratioId++) { Dem_IUMPRGroup iumprGroup = Dem_RatiosList[ratioId].IumprGroup; setInfoType08NumsDenoms(iumprGroup, Iumprdata08, ratioId); } } return E_OK; } #elif (DEM_OBD_ENGINE_TYPE == DEM_IGNITION_COMPR) /* @req DEM358 */ static void setInfoType0BNumsDenoms(Dem_IUMPRGroup iumprGroup, uint8* Iumprdata0B, Dem_RatioIdType ratioId) { switch(iumprGroup) { case DEM_IUMPR_NMHCCAT: getNumeratorDenominator(Iumprdata0B, 4, ratioId); break; case DEM_IUMPR_NOXCAT: getNumeratorDenominator(Iumprdata0B, 8, ratioId); break; case DEM_IUMPR_NOXADSORB: getNumeratorDenominator(Iumprdata0B, 12, ratioId); break; case DEM_IUMPR_PMFILTER: getNumeratorDenominator(Iumprdata0B, 16, ratioId); break; case DEM_IUMPR_EGSENSOR: getNumeratorDenominator(Iumprdata0B, 20, ratioId); break; case DEM_IUMPR_EGR: getNumeratorDenominator(Iumprdata0B, 24, ratioId); break; case DEM_IUMPR_BOOSTPRS: getNumeratorDenominator(Iumprdata0B, 28, ratioId); break; case DEM_IUMPR_FLSYS: getNumeratorDenominator(Iumprdata0B, 32, ratioId); break; } } /** * Service is used to request for IUMPR data according to InfoType $0B. * Reentrant: Yes * * @param Iumprdata08: Buffer containing the contents of InfoType $0B. * The buffer is provided by the Dcm. * @return Always E_OK is returned, as E_PENDING and E_NOT_OK will never appear. */ Std_ReturnType Dem_GetInfoTypeValue0B(uint8* Iumprdata0B) { /* @req DEM317 */ /* @req DEM298 */ if ((demState == DEM_INITIALIZED) && (Iumprdata0B != NULL_PTR)) { // reset data memset(Iumprdata0B, 0, 36); // get general denominator count getGeneralDenominatorCount(Iumprdata0B); // get ignition cycle count getIgnitionCycleCount(Iumprdata0B); for (Dem_RatioIdType ratioId = 0; ratioId < DEM_IUMPR_REGISTERED_COUNT; ratioId++) { Dem_IUMPRGroup iumprGroup = Dem_RatiosList[ratioId].IumprGroup; setInfoType0BNumsDenoms(iumprGroup, Iumprdata0B, ratioId); } } return E_OK; } #endif /** * Service for reporting that faults are possibly found because all conditions are fulfilled. * Reentrant: No * * @param RatioID: Ratio Identifier reporting that a respective monitor could have * found a fault - only used when interface option "API" is selected. * @return E_OK report of IUMPR result was successfully reported. */ Std_ReturnType Dem_RepIUMPRFaultDetect(Dem_RatioIdType RatioID) { VALIDATE_RV(DEM_INITIALIZED == demState, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_UNINIT, E_NOT_OK); #if defined(DEM_USE_IUMPR) // valid RatioID VALIDATE_RV(RatioID < DEM_IUMPR_REGISTERED_COUNT, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* @req DEM313 */ /* @req DEM360 */ Std_ReturnType ret = E_NOT_OK; SchM_Enter_Dem_EA_0(); /* @req DEM296 */ if (Dem_RatiosList[RatioID].RatioKind == DEM_RATIO_API) { // is API call ret = incrementIumprNumerator(RatioID); } SchM_Exit_Dem_EA_0(); return ret; #else (void)RatioID; return E_NOT_OK; #endif } /** * Service is used to lock a denominator of a specific monitor. * Reentrant: Yes * * @param RatioID: Ratio Identifier reporting that specific denominator is locked (for * physical reasons - e.g. temperature conditions or minimum activity). * @return E_OK report of IUMPR denominator status was successfully reported. * E_NOT_OK report of IUMPR denominator status was not successfully reported. */ Std_ReturnType Dem_RepIUMPRDenLock(Dem_RatioIdType RatioID) { Std_ReturnType ret = E_NOT_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_UNINIT, E_NOT_OK); #if defined(DEM_USE_IUMPR) // valid RatioID VALIDATE_RV(RatioID < DEM_IUMPR_REGISTERED_COUNT, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* @req DEM314 */ /* @req DEM362 */ /* @req DEM297 */ if (FALSE == iumprBufferLocal[RatioID].denominator.isLocked) { iumprBufferLocal[RatioID].denominator.isLocked = TRUE; ret = E_OK; } #else (void)RatioID; #endif return ret; } /** * Service is used to release a denominator of a specific monitor. * Reentrant: Yes * * @param RatioID: Ratio Identifier reporting that specific denominator is released * (for physical reasons - e.g. temperature conditions or minimum activity). * @return E_OK report of IUMPR denominator status was successfully reported. * E_NOT_OK report of IUMPR denominator status was not successfully reported. */ Std_ReturnType Dem_RepIUMPRDenRelease(Dem_RatioIdType RatioID) { Std_ReturnType ret = E_NOT_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_UNINIT, E_NOT_OK); #if defined(DEM_USE_IUMPR) // valid RatioID VALIDATE_RV(RatioID < DEM_IUMPR_REGISTERED_COUNT, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); /* @req Dem315 */ /* @req Dem362 */ /* @req Dem308 */ if (TRUE == iumprBufferLocal[RatioID].denominator.isLocked) { iumprBufferLocal[RatioID].denominator.isLocked = FALSE; // consider this as qualified driving cycle (if applicable), increment denominator immediately (void) incrementIumprDenominator(RatioID); ret = E_OK; } #else (void)RatioID; #endif return ret; } #if defined(DEM_USE_IUMPR) /** * Increment general denominator if set condition is general denominator and status is reached. * * @param ConditionId: Identification of a IUMPR denominator condition ID (General Denominator, Cold start, EVAP, 500mi). * @param ConditionStatus: Status of the IUMPR denominator condition (Notreached, reached, not reachable / inhibited). */ static void incrementGeneralDenominator(Dem_IumprDenomCondIdType ConditionId, Dem_IumprDenomCondStatusType ConditionStatus) { if (ConditionId == DEM_IUMPR_GENERAL_OBDCOND && ConditionStatus == DEM_IUMPR_DEN_STATUS_REACHED) { if (FALSE == generalDenominatorBuffer.incrementedThisDrivingCycle) { // If driving cycle started if (TRUE == operationCycleIsStarted(DEM_OBD_DCY)) { // If the general denominator reaches the maximum value of 65,535 ±2, the // general denominator shall rollover and increment to zero on the next // driving cycle that meets the general denominator definition to avoid // overflow problems. if (generalDenominatorBuffer.value == 65535) { generalDenominatorBuffer.value = 0; } else { generalDenominatorBuffer.value++; } generalDenominatorBuffer.incrementedThisDrivingCycle = TRUE; } } } } #endif /** * In order to communicate the status of the (additional) denominator conditions among the OBD relevant ECUs, * the API is used to forward the condition status to a Dem of a particular ECU. * API is needed in OBD-relevant ECUs only. * * @param ConditionId: Identification of a IUMPR denominator condition ID (General Denominator, Cold start, EVAP, 500mi). * @param ConditionStatus: Status of the IUMPR denominator condition (Notreached, reached, not reachable / inhibited). * @return E_OK: set of IUMPR denominator condition was successful, * E_NOT_OK: set of IUMPR denominator condition failed or could not be accepted. */ Std_ReturnType Dem_SetIUMPRDenCondition(Dem_IumprDenomCondIdType ConditionId, Dem_IumprDenomCondStatusType ConditionStatus) { Std_ReturnType ret = E_NOT_OK; // dem started VALIDATE_RV(DEM_INITIALIZED == demState, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_UNINIT, E_NOT_OK); // valid condition ID VALIDATE_RV(((ConditionId == DEM_IUMPR_DEN_COND_COLDSTART) || (ConditionId == DEM_IUMPR_DEN_COND_EVAP) || (ConditionId == DEM_IUMPR_DEN_COND_500MI) || (ConditionId == DEM_IUMPR_GENERAL_OBDCOND)), DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); // valid condition status VALIDATE_RV(ConditionStatus < 0x03, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); #if defined(DEM_USE_IUMPR) for (uint8 i = 0; i < DEM_IUMPR_ADDITIONAL_DENOMINATORS_COUNT; i++) { if (iumprAddiDenomCondBuffer[i].condition == ConditionId) { if (iumprAddiDenomCondBuffer[i].status != ConditionStatus) { iumprAddiDenomCondBuffer[i].status = ConditionStatus; ret = E_OK; // if applicable incrementGeneralDenominator(ConditionId, ConditionStatus); } break; } } #endif return ret; } /** * In order to communicate the status of the (additional) denominator conditions among the OBD relevant ECUs, the API is used to retrieve * the condition status from the Dem of the ECU where the conditions are computed. API is needed in OBD-relevant ECUs only. * * @param ConditionId: Identification of a IUMPR denominator condition ID (General Denominator, Cold start, EVAP, 500mi). * @param ConditionStatus: Status of the IUMPR denominator condition (Notreached, reached, not reachable / inhibited) * @return E_OK: get of IUMPR denominator condition status was successful, * E_NOT_OK: get of condition status failed. */ Std_ReturnType Dem_GetIUMPRDenCondition(Dem_IumprDenomCondIdType ConditionId, Dem_IumprDenomCondStatusType* ConditionStatus) { Std_ReturnType ret = E_NOT_OK; // dem started VALIDATE_RV(DEM_INITIALIZED == demState, DEM_REPIUMPRFAULTDETECT_ID, DEM_E_UNINIT, E_NOT_OK); // valid condition ID VALIDATE_RV(((ConditionId == DEM_IUMPR_DEN_COND_COLDSTART) || (ConditionId == DEM_IUMPR_DEN_COND_EVAP) || (ConditionId == DEM_IUMPR_DEN_COND_500MI) || (ConditionId == DEM_IUMPR_GENERAL_OBDCOND)), DEM_REPIUMPRFAULTDETECT_ID, DEM_E_PARAM_DATA, E_NOT_OK); #if defined(DEM_USE_IUMPR) for (uint8 i = 0; i < DEM_IUMPR_ADDITIONAL_DENOMINATORS_COUNT; i++) { if (iumprAddiDenomCondBuffer[i].condition == ConditionId) { *ConditionStatus = iumprAddiDenomCondBuffer[i].status; ret = E_OK; } } #endif return ret; } #endif /** * Set the suppression status of a specific DTC. * @param DTC * @param DTCFormat * @param SuppressionStatus * @return E_OK (Operation was successful), E_NOT_OK (operation failed or event entry for this DTC still exists) */ /* @req DEM589 */ /* @req 4.2.2/SWS_Dem_01047 */ #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) /* @req 4.2.2/SWS_Dem_00586 */ Std_ReturnType Dem_SetDTCSuppression(uint32 DTC, Dem_DTCFormatType DTCFormat, boolean SuppressionStatus) { /* Requirement tag intentionally incorrect. Handled in DEM.py */ /* !req DEM588 Allowing suppression of DTC even if event memory entry exists (this requirement is removed in ASR 4.2.2) */ Std_ReturnType ret = E_NOT_OK; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETDTCSUPPRESSION_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV(IS_VALID_DTC_FORMAT(DTCFormat), DEM_SETDTCSUPPRESSION_ID, DEM_E_PARAM_DATA, E_NOT_OK); const Dem_DTCClassType *DTCClassPtr = configSet->DTCClass; while( FALSE == DTCClassPtr->Arc_EOL ) { if( ((DEM_DTC_FORMAT_UDS == DTCFormat) && (DTCClassPtr->DTCRef->UDSDTC == DTC)) || ((DEM_DTC_FORMAT_OBD == DTCFormat) && (TO_OBD_FORMAT(DTCClassPtr->DTCRef->OBDDTC) == DTC))) { DemDTCSuppressed[DTCClassPtr->DTCIndex].SuppressedByDTC = SuppressionStatus; ret = E_OK; break; } DTCClassPtr++; } return ret; } #endif #if defined(DEM_USE_MEMORY_FUNCTIONS) /** * Check if an event is stored in freeze frame buffer * @param eventId * @param dtcOrigin * @return TRUE: Event stored in FF buffer, FALSE: Event NOT stored in FF buffer */ static boolean isInFFBuffer(Dem_EventIdType eventId, Dem_DTCOriginType dtcOrigin) { boolean ffFound = FALSE; FreezeFrameRecType* freezeFrameBuffer = NULL; uint32 freezeFrameBufferSize = 0; switch (dtcOrigin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: #if ((DEM_USE_PRIMARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_PRI_MEM) freezeFrameBuffer = priMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_PRI_MEM; #endif break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: #if ((DEM_USE_SECONDARY_MEMORY_SUPPORT == STD_ON) && DEM_FF_DATA_IN_SEC_MEM) freezeFrameBuffer = secMemFreezeFrameBuffer; freezeFrameBufferSize = DEM_MAX_NUMBER_FF_DATA_SEC_MEM; #endif break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GLOBAL_ID, DEM_E_NOT_IMPLEMENTED_YET); break; } if (freezeFrameBuffer != NULL) { for (uint32 i = 0uL; (i < freezeFrameBufferSize) && (FALSE == ffFound); i++) { ffFound = (freezeFrameBuffer[i].eventId == eventId)? TRUE: FALSE; } } return ffFound; } #endif /** * Checks if event is stored in event memory * @param EventId * @return TRUE: Event stored in memory, FALSE: event NOT stored in memory */ static boolean EventIsStoredInMemory(Dem_EventIdType EventId) { #if defined(DEM_USE_MEMORY_FUNCTIONS) const Dem_EventParameterType *eventParam; ExtDataRecType *extData; boolean isStored = FALSE; lookupEventIdParameter(EventId, &eventParam); if( (NULL != eventParam) && (DEM_DTC_ORIGIN_NOT_USED != eventParam->EventClass->EventDestination) ) { isStored = ((TRUE == isInEventMemory(eventParam)) || (TRUE == isInFFBuffer(EventId, eventParam->EventClass->EventDestination)) || (TRUE == lookupExtendedDataMem(EventId, &extData, eventParam->EventClass->EventDestination)))? TRUE: FALSE; } return isStored; #else (void)EventId; return FALSE; #endif } /** * Set the available status of a specific Event. * @param EventId: Identification of an event by assigned EventId. * @param AvailableStatus: This parameter specifies whether the respective Event shall be available (TRUE) or not (FALSE). * @return: E_OK: Operation was successful, E_NOT_OK: change of available status not accepted */ /* @req 4.2.2/SWS_Dem_01080 */ Std_ReturnType Dem_SetEventAvailable(Dem_EventIdType EventId, boolean AvailableStatus) { #if (DEM_SET_EVENT_AVAILABLE_PREINIT == STD_ON) VALIDATE_RV(DEM_UNINITIALIZED != demState, DEM_SETEVENTAVAILABLE_ID, DEM_E_UNINIT, E_NOT_OK); #else VALIDATE_RV(DEM_INITIALIZED == demState, DEM_SETEVENTAVAILABLE_ID, DEM_E_UNINIT, E_NOT_OK); #endif VALIDATE_RV(IS_VALID_EVENT_ID(EventId), DEM_SETEVENTAVAILABLE_ID, DEM_E_PARAM_DATA, E_NOT_OK); const Dem_EventParameterType *eventParam = NULL; Dem_EventStatusExtendedType oldStatus; EventStatusRecType *eventStatusRec = NULL; Std_ReturnType ret = E_NOT_OK; if ( (demState == DEM_UNINITIALIZED) #if (DEM_SET_EVENT_AVAILABLE_PREINIT == STD_OFF) || (demState == DEM_PREINITIALIZED) #endif ) { return E_NOT_OK; } SchM_Enter_Dem_EA_0(); lookupEventStatusRec(EventId, &eventStatusRec); lookupEventIdParameter(EventId, &eventParam); /* @req 4.2.2/SWS_Dem_01109 */ if( (NULL != eventStatusRec) && (NULL != eventParam) && (*eventParam->EventClass->EventAvailableByCalibration == TRUE) && (0u == (eventStatusRec->eventStatusExtended & DEM_TEST_FAILED)) && ((DEM_PREINITIALIZED == demState) || (FALSE == EventIsStoredInMemory(EventId))) ) { if( eventStatusRec->isAvailable != AvailableStatus ) { /* Event availability changed */ eventStatusRec->isAvailable = AvailableStatus; oldStatus = eventStatusRec->eventStatusExtended; if( FALSE == AvailableStatus ) { /* @req 4.2.2/SWS_Dem_01110 */ eventStatusRec->eventStatusExtended = 0x00; } else { /* @req 4.2.2/SWS_Dem_01111 */ eventStatusRec->eventStatusExtended = 0x50; } if( oldStatus != eventStatusRec->eventStatusExtended ) { notifyEventStatusChange(eventParam, oldStatus, eventStatusRec->eventStatusExtended); } #if (DEM_DTC_SUPPRESSION_SUPPORT == STD_ON) /* Check if suppression of DTC is affected */ boolean suppressed = TRUE; EventStatusRecType *dtcEventStatusRec; if( (NULL != eventParam->DTCClassRef) && (NULL != eventParam->DTCClassRef->Events) ) { for( uint16 i = 0; (i < eventParam->DTCClassRef->NofEvents) && (TRUE == suppressed); i++ ) { dtcEventStatusRec = NULL; lookupEventStatusRec(eventParam->DTCClassRef->Events[i], &dtcEventStatusRec); if( (NULL != dtcEventStatusRec) && (TRUE == dtcEventStatusRec->isAvailable) ) { /* Event is available -> DTC NOT suppressed */ suppressed = FALSE; } } if( 0 != eventParam->DTCClassRef->NofEvents ) { DemDTCSuppressed[eventParam->DTCClassRef->DTCIndex].SuppressedByEvent = suppressed; } } #endif } ret = E_OK; } SchM_Exit_Dem_EA_0(); return ret; } /** * Gets the current monitor status for an event. * @param EventID * @param MonitorStatus * @return E_OK: Get monitor status was successful, E_NOT_OK: getting the monitor status failed (e.g.an invalid event id was provided). */ /* @req 4.3.0/SWS_Dem_91007 */ Std_ReturnType Dem_GetMonitorStatus(Dem_EventIdType EventID, Dem_MonitorStatusType* MonitorStatus) { Std_ReturnType ret = E_NOT_OK; EventStatusRecType * eventStatusRec; VALIDATE_RV(DEM_INITIALIZED == demState, DEM_GETMONITORSTATUS_ID, DEM_E_UNINIT, E_NOT_OK); VALIDATE_RV((NULL != MonitorStatus), DEM_GETMONITORSTATUS_ID, DEM_E_PARAM_POINTER, E_NOT_OK); if( IS_VALID_EVENT_ID(EventID) ) { /* @req 4.3.0/SWS_Dem_01287 */ lookupEventStatusRec(EventID, &eventStatusRec); if( NULL != eventStatusRec ) { *MonitorStatus = 0u; if( 0u != (eventStatusRec->eventStatusExtended & DEM_TEST_FAILED) ) { *MonitorStatus |= DEM_MONITOR_STATUS_TF; } if( 0u != (eventStatusRec->eventStatusExtended & DEM_TEST_NOT_COMPLETED_THIS_OPERATION_CYCLE) ) { *MonitorStatus |= DEM_MONITOR_STATUS_TNCTOC; } ret = E_OK; } } else { DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETMONITORSTATUS_ID, DEM_E_PARAM_DATA); /* @req 4.3.0/SWS_Dem_01288 */ } return ret; }
2301_81045437/classic-platform
diagnostic/Dem/src/Dem.c
C
unknown
447,421
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Dem.h" #include "Dem_Types.h" #include "Dem_Lcfg.h" #include "Dem_Internal.h" #if defined(USE_DEM_EXTENSION) #include "Dem_Extension.h" #endif /* Local defines */ #define DEM_UDS_TEST_FAILED_TRESHOLD (sint32)127 #define DEM_UDS_TEST_PASSED_TRESHOLD (sint32)(-128) #define DEM_UDS_FDC_RANGE (sint32)(DEM_UDS_TEST_FAILED_TRESHOLD - (DEM_UDS_TEST_PASSED_TRESHOLD)) /* Local variables */ #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) /* Buffer for time based debounce */ static TimeBaseStatusType DemTimeBaseBuffer[DEM_NOF_TIME_BASE_PREDEB]; #endif /* Local functions */ /** * Translates internal FDC to external FDC * @param fdcInternal * @param pdVars * @return FDC */ static sint8 fdcInternalToUDSFdc(sint16 fdcInternal, const Dem_PreDebounceCounterBasedType* pdVars) { /* Map the internal counter to the corresponding UDS fdc. I.e. map from [FailedThreshold, PassedThreshold] to [-128, 127]. */ sint32 pdRange = (sint32)((sint32)pdVars->FailedThreshold - (sint32)pdVars->PassedThreshold); sint32 temp = (DEM_UDS_FDC_RANGE*((sint32)((sint32)fdcInternal - (sint32)pdVars->PassedThreshold))) + (DEM_UDS_TEST_PASSED_TRESHOLD*pdRange); return (sint8)(temp/pdRange); } /* * Procedure: preDebounceNone * Description: Returns the result of the debouncing. */ static Dem_EventStatusType preDebounceNone(const Dem_EventStatusType reportedStatus) { /* @req DEM437 */ Dem_EventStatusType returnCode; switch (reportedStatus) { case DEM_EVENT_STATUS_FAILED: case DEM_EVENT_STATUS_PASSED: // Already debounced, do nothing. break; default: // NOTE: What to do with PREFAIL and PREPASSED on no debouncing? DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_PREDEBOUNCE_NONE_ID, DEM_E_PARAM_DATA); break; } returnCode = reportedStatus; return returnCode; } /* * Procedure: preDebounceCounterBased * Description: Returns the result of the debouncing. */ static Dem_EventStatusType preDebounceCounterBased(Dem_EventStatusType reportedStatus, EventStatusRecType* statusRecord) { Dem_EventStatusType returnCode; const Dem_PreDebounceCounterBasedType* pdVars = statusRecord->eventParamRef->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceCounterBased; switch (reportedStatus) { case DEM_EVENT_STATUS_PREFAILED: if (statusRecord->fdcInternal < pdVars->FailedThreshold) { if ((pdVars->JumpUp ==TRUE) && (statusRecord->fdcInternal < pdVars->JumpUpValue)) { statusRecord->fdcInternal = pdVars->JumpUpValue;/* @req 4.2.2/SWS_DEM_00423 */ } if (((sint32)statusRecord->fdcInternal + (sint32)pdVars->IncrementStepSize) < pdVars->FailedThreshold) { statusRecord->fdcInternal += pdVars->IncrementStepSize;/*lint !e734 OK since we check above that it will not overflow*/ /* @req DEM418 */ } else { statusRecord->fdcInternal = pdVars->FailedThreshold; } } break; case DEM_EVENT_STATUS_PREPASSED: if (statusRecord->fdcInternal > pdVars->PassedThreshold) { if ((pdVars->JumpDown==TRUE) && (statusRecord->fdcInternal > pdVars->JumpDownValue)) { statusRecord->fdcInternal = pdVars->JumpDownValue;/* @req 4.2.2/SWS_DEM_00425 */ } if (((sint32)statusRecord->fdcInternal - (sint32)pdVars->DecrementStepSize) > pdVars->PassedThreshold) { statusRecord->fdcInternal -= pdVars->DecrementStepSize;/*lint !e734 OK since we check above that it will not overflow*/ /* @req DEM419 */ } else { statusRecord->fdcInternal = pdVars->PassedThreshold; } } break; case DEM_EVENT_STATUS_FAILED: statusRecord->fdcInternal = pdVars->FailedThreshold; /* @req DEM420 */ break; case DEM_EVENT_STATUS_PASSED: statusRecord->fdcInternal = pdVars->PassedThreshold; /* @req DEM421 */ break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_PREDEBOUNCE_COUNTER_BASED_ID, DEM_E_PARAM_DATA); break; } #if defined(USE_DEM_EXTENSION) Dem_Extension_PostPreDebounceCounterBased(reportedStatus, statusRecord); #endif if( statusRecord->fdcInternal >= pdVars->FailedThreshold ) { returnCode = DEM_EVENT_STATUS_FAILED; } else if( statusRecord->fdcInternal <= pdVars->PassedThreshold ) { returnCode = DEM_EVENT_STATUS_PASSED; } else { returnCode = reportedStatus; } /* @req DEM415 */ statusRecord->UDSFdc = fdcInternalToUDSFdc(statusRecord->fdcInternal, pdVars); statusRecord->maxUDSFdc = MAX(statusRecord->maxUDSFdc, statusRecord->UDSFdc); return returnCode; } #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) /** * Calculates FDC based on timer * @param debounceTimer * @param pdVars * @return FDC */ static sint8 getTimeBasedFDC(const TimeBaseStatusType *debounceTimer, const Dem_PreDebounceTimeBasedType *pdVars) { /* @req DEM427 */ sint8 FDC = 0; sint64 temp; if( TRUE == debounceTimer->started ) { if( TRUE == debounceTimer->failureCounting ) { /* 0 - pdVars->TimeFailedThreshold -> 0 - 127*/ if( 0UL != pdVars->TimeFailedThreshold ) { temp = ((sint64)debounceTimer->debounceTime * DEM_UDS_TEST_FAILED_TRESHOLD) / pdVars->TimeFailedThreshold; temp = MIN(temp, DEM_UDS_TEST_FAILED_TRESHOLD); FDC = (sint8)temp; } else { FDC = (sint8)DEM_UDS_TEST_FAILED_TRESHOLD; } } else { /* 0 - pdVars->TimePassedThreshold -> 0 - -128*/ if(0UL != pdVars->TimePassedThreshold) { temp = ((sint64)debounceTimer->debounceTime * DEM_UDS_TEST_PASSED_TRESHOLD) / pdVars->TimePassedThreshold; temp = MAX(temp, DEM_UDS_TEST_PASSED_TRESHOLD); FDC = (sint8)temp; } else { FDC = (sint8)DEM_UDS_TEST_PASSED_TRESHOLD; } } } return FDC; } /** * Handles starting time based debouncing * @param reportedStatus * @param eventParam * @return */ static Dem_EventStatusType preDebounceTimeBased(Dem_EventStatusType reportedStatus, const Dem_EventParameterType *eventParam) { Dem_EventStatusType ret = reportedStatus; const Dem_PreDebounceTimeBasedType* pdVars = eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased; DemTimeBaseBuffer[pdVars->Index].EventId = eventParam->EventID; switch (reportedStatus) { case DEM_EVENT_STATUS_FAILED: case DEM_EVENT_STATUS_PREFAILED: /* @req DEM428 */ /* @req DEM429 */ if( (FALSE == DemTimeBaseBuffer[pdVars->Index].started) || (FALSE == DemTimeBaseBuffer[pdVars->Index].failureCounting) ) { DemTimeBaseBuffer[pdVars->Index].started = TRUE; DemTimeBaseBuffer[pdVars->Index].failureCounting = TRUE; if( (DEM_EVENT_STATUS_FAILED == reportedStatus) || (0UL == pdVars->TimeFailedThreshold) ) { /* @req DEM431 */ DemTimeBaseBuffer[pdVars->Index].debounceTime = pdVars->TimeFailedThreshold; DemTimeBaseBuffer[pdVars->Index].errorReported = TRUE; DemTimeBaseBuffer[pdVars->Index].counterReset = FALSE; ret = DEM_EVENT_STATUS_FAILED; } else { DemTimeBaseBuffer[pdVars->Index].debounceTime = 0; DemTimeBaseBuffer[pdVars->Index].errorReported = FALSE; DemTimeBaseBuffer[pdVars->Index].counterReset = TRUE; } } break; case DEM_EVENT_STATUS_PASSED: case DEM_EVENT_STATUS_PREPASSED: /* @req DEM432 */ /* @req DEM433 */ if( (FALSE == DemTimeBaseBuffer[pdVars->Index].started) || (TRUE == DemTimeBaseBuffer[pdVars->Index].failureCounting) ) { DemTimeBaseBuffer[pdVars->Index].started = TRUE; DemTimeBaseBuffer[pdVars->Index].failureCounting = FALSE; if( (DEM_EVENT_STATUS_PASSED == reportedStatus) || (0UL == pdVars->TimePassedThreshold) ) { /* @req DEM435 */ DemTimeBaseBuffer[pdVars->Index].debounceTime = pdVars->TimePassedThreshold; DemTimeBaseBuffer[pdVars->Index].errorReported = TRUE; DemTimeBaseBuffer[pdVars->Index].counterReset = FALSE; ret = DEM_EVENT_STATUS_PASSED; } else { DemTimeBaseBuffer[pdVars->Index].debounceTime = 0; DemTimeBaseBuffer[pdVars->Index].errorReported = FALSE; DemTimeBaseBuffer[pdVars->Index].counterReset = TRUE; } } break; default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_PREDEBOUNCE_COUNTER_BASED_ID, DEM_E_PARAM_DATA); break; } return ret; } #endif /* Exported functions */ #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) /** * Main function for time based predebounce */ void TimeBasedDebounceMainFunction(void) { /* Handle time based predebounce */ /* @req DEM426 */ const Dem_EventParameterType *eventParam; EventStatusRecType *eventStatusRec; for( uint16 idx = 0; idx < DEM_NOF_TIME_BASE_PREDEB; idx++ ) { eventParam = NULL; eventStatusRec = NULL; if( DEM_EVENT_ID_NULL != DemTimeBaseBuffer[idx].EventId ) { lookupEventIdParameter(DemTimeBaseBuffer[idx].EventId, &eventParam); /*lint !e934 eventParam only used in this function */ lookupEventStatusRec(DemTimeBaseBuffer[idx].EventId, &eventStatusRec); /*lint !e934 eventStatusRec only used in this function */ if( (NULL != eventParam) && (NULL != eventStatusRec) && (NULL != eventParam->EventClass->PreDebounceAlgorithmClass) && (DEM_PRE_DEBOUNCE_TIME_BASED == eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceName)) { const Dem_PreDebounceTimeBasedType* pdVars = eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased; if( TRUE == operationCycleIsStarted(eventParam->EventClass->OperationCycleRef) ) { if( TRUE == DemTimeBaseBuffer[idx].started ) { if(FALSE == DemTimeBaseBuffer[idx].counterReset) { if( TRUE == DemTimeBaseBuffer[idx].failureCounting ) { if( DemTimeBaseBuffer[idx].debounceTime < pdVars->TimeFailedThreshold ) { DemTimeBaseBuffer[idx].debounceTime += DEM_TASK_TIME; } /* @req DEM430 */ if( DemTimeBaseBuffer[idx].debounceTime >= pdVars->TimeFailedThreshold ) { /* FAILED! */ if(E_OK == handleEvent(DemTimeBaseBuffer[idx].EventId, DEM_EVENT_STATUS_FAILED) ) { DemTimeBaseBuffer[idx].errorReported = TRUE; } } } else { if( DemTimeBaseBuffer[idx].debounceTime < pdVars->TimePassedThreshold ) { DemTimeBaseBuffer[idx].debounceTime += DEM_TASK_TIME; } /* @req DEM434 */ if( DemTimeBaseBuffer[idx].debounceTime >= pdVars->TimePassedThreshold ) { /* PASSED! */ if( E_OK == handleEvent(DemTimeBaseBuffer[idx].EventId, DEM_EVENT_STATUS_PASSED) ) { DemTimeBaseBuffer[idx].errorReported = TRUE; } } } } else { DemTimeBaseBuffer[idx].counterReset = FALSE; } eventStatusRec->UDSFdc = getTimeBasedFDC(&DemTimeBaseBuffer[idx], pdVars); eventStatusRec->maxUDSFdc = MAX(eventStatusRec->UDSFdc, eventStatusRec->maxUDSFdc); } } else { /* Operation cycle is not started. * Cancel timer. */ DemTimeBaseBuffer[idx].started = FALSE; DemTimeBaseBuffer[idx].errorReported = FALSE; } } } } } #endif /** * Resets debounce counter of event * @param eventStatusRec */ void resetDebounceCounter(EventStatusRecType *eventStatusRec) { sint8 startFDC = getDefaultUDSFdc(eventStatusRec->eventId); eventStatusRec->UDSFdc = startFDC;/* @req DEM344 */ eventStatusRec->maxUDSFdc = startFDC; eventStatusRec->fdcInternal = 0; #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) const Dem_EventParameterType *eventParam = NULL; lookupEventIdParameter(eventStatusRec->eventId, &eventParam); /*lint !e934 eventParam only used in this function */ if( NULL != eventParam ) { if( (NULL != eventParam->EventClass->PreDebounceAlgorithmClass) && (DEM_PRE_DEBOUNCE_TIME_BASED == eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceName) ) { DemTimeBaseBuffer[eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased->Index].started = FALSE; DemTimeBaseBuffer[eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased->Index].errorReported = FALSE; DemTimeBaseBuffer[eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased->Index].debounceTime = 0UL; } } #endif } /* * Procedure: getFaultDetectionCounter * Description: Returns pre debounce counter of "eventId" in "counter" and return value E_OK if * the counter was available else E_NOT_OK. */ Std_ReturnType getFaultDetectionCounter(Dem_EventIdType eventId, sint8 *counter) { Std_ReturnType returnCode = E_NOT_OK; const Dem_EventParameterType *eventParam; EventStatusRecType *eventStatusRec = NULL_PTR; lookupEventStatusRec(eventId, &eventStatusRec); /*lint !e934 eventStatusRec only used in this function */ lookupEventIdParameter(eventId, &eventParam); /*lint !e934 eventParam only used in this function */ if ((eventParam != NULL_PTR) && (NULL_PTR != eventStatusRec) && (TRUE == eventStatusRec->isAvailable)) { if (eventParam->EventClass->PreDebounceAlgorithmClass != NULL_PTR) { switch (eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceName) { case DEM_NO_PRE_DEBOUNCE: if (eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceMonitorInternal != NULL_PTR) { if (eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceMonitorInternal->CallbackGetFDCntFnc != NULL_PTR) { /* @req DEM204 None */ /* @req DEM264 */ /* @req DEM439 */ returnCode = eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceMonitorInternal->CallbackGetFDCntFnc(counter); } } break; case DEM_PRE_DEBOUNCE_COUNTER_BASED: *counter = eventStatusRec->UDSFdc; /* @req DEM204 Counter */ returnCode = E_OK; break; #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) case DEM_PRE_DEBOUNCE_TIME_BASED: /* Map timer to FDC */ *counter = getTimeBasedFDC(&DemTimeBaseBuffer[eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased->Index], eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceTimeBased); returnCode = E_OK; break; #endif default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_GETFAULTDETECTIONCOUNTER_ID, DEM_E_PARAM_DATA); break; } } } return returnCode; } /** * Initializes time based debounce buffer */ #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) void InitTimeBasedDebounce(void) { for( uint16 idx = 0; idx < DEM_NOF_TIME_BASE_PREDEB; idx++ ) { DemTimeBaseBuffer[idx].EventId = DEM_EVENT_ID_NULL; DemTimeBaseBuffer[idx].started = FALSE; } } #endif /** * Gets the default UDS fdc * @param eventId * @return */ sint8 getDefaultUDSFdc(Dem_EventIdType eventId) { sint8 udsFdc = 0; const Dem_EventParameterType *eventParam = NULL_PTR; lookupEventIdParameter(eventId, &eventParam); /*lint !e934 eventParam only used in this function */ if( NULL_PTR != eventParam ) { if (eventParam->EventClass->PreDebounceAlgorithmClass != NULL_PTR) { switch (eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceName) { case DEM_PRE_DEBOUNCE_COUNTER_BASED: udsFdc = fdcInternalToUDSFdc(0, eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceAlgorithm.PreDebounceCounterBased); break; default: break; } } } return udsFdc; } /** * Runs predebounce for event * @param reportedEventStatus * @param eventStatusRecPtr * @param eventParam * @return calculated eventStatus */ Dem_EventStatusType RunPredebounce(Dem_EventStatusType reportedEventStatus, EventStatusRecType *eventStatusRecPtr, const Dem_EventParameterType *eventParam) { Dem_EventStatusType eventStatus = reportedEventStatus; if (eventParam->EventClass->PreDebounceAlgorithmClass != NULL_PTR) { switch (eventParam->EventClass->PreDebounceAlgorithmClass->PreDebounceName) { case DEM_NO_PRE_DEBOUNCE: eventStatus = preDebounceNone(reportedEventStatus); break; case DEM_PRE_DEBOUNCE_COUNTER_BASED: eventStatus = preDebounceCounterBased(reportedEventStatus, eventStatusRecPtr); break; #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) case DEM_PRE_DEBOUNCE_TIME_BASED: eventStatus = preDebounceTimeBased(reportedEventStatus, eventParam); break; #endif default: DET_REPORTERROR(DEM_MODULE_ID, 0, DEM_UPDATE_EVENT_STATUS_ID, DEM_E_NOT_IMPLEMENTED_YET); break; } } return eventStatus; }
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_Debounce.c
C
unknown
20,034
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Dem_Extension.h" #include "Dem.h" #include "Std_Types.h" void Dem_Extension_MainFunction(void) { } void Dem_Extension_ClearEvent(const Dem_EventParameterType *eventParam) { (void)eventParam; } void Dem_Extension_UpdateEventstatus(EventStatusRecType *eventStatusRecPtr, uint8 eventStatusExtendedBeforeUpdate, Dem_EventStatusType eventStatus) { (void)eventStatusRecPtr; (void)eventStatusExtendedBeforeUpdate; (void)eventStatus; } void Dem_Extension_OperationCycleStart(Dem_OperationCycleIdType operationCycleId, EventStatusRecType *eventStatusRecPtr) { (void)operationCycleId; (void)eventStatusRecPtr; } void Dem_Extension_OperationCycleEnd(Dem_OperationCycleIdType operationCycleId, EventStatusRecType *eventStatusRecPtr) { (void)operationCycleId; (void)eventStatusRecPtr; } void Dem_Extension_PreInit(const Dem_ConfigType *ConfigPtr) { (void)ConfigPtr; } void Dem_Extension_Init_PostEventMerge(Dem_DTCOriginType origin) { } void Dem_Extension_Init_Complete(void) { } void Dem_Extension_Shutdown(void) { } void Dem_Extension_GetExtendedDataInternalElement(Dem_EventIdType eventId, Dem_InternalDataElementType internalElement, uint8 *dataBuf, uint16 size) { (void)eventId; (void)internalElement; (void)dataBuf; (void)size; } void Dem_Extension_PostPreDebounceCounterBased(Dem_EventStatusType reportedStatus, EventStatusRecType* statusRecord) { (void)reportedStatus; (void)statusRecord; } void Dem_Extension_HealedEvent(Dem_EventIdType eventId) { (void)eventId; } #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) void Dem_Extension_GetExtDataEventForDisplacement(const Dem_EventParameterType *eventParam, const ExtDataRecType *extDataBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { (void)eventParam; (void)extDataBuffer; (void)bufferSize; (void)eventParam; } void Dem_Extension_GetEventForDisplacement(const Dem_EventParameterType *eventParam, const EventRecType *eventRecordBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { (void)eventParam; (void)eventRecordBuffer; (void)bufferSize; (void)eventParam; } void Dem_Extension_GetFFEventForDisplacement(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *ffBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove) { (void)eventParam; (void)ffBuffer; (void)bufferSize; (void)eventParam; } #endif void Dem_Extension_EventDataDisplaced(Dem_EventIdType eventId) { (void)eventId; } void Dem_Extension_EventExtendedDataDisplaced(Dem_EventIdType eventId) { (void)eventId; } void Dem_Extension_EventFreezeFrameDataDisplaced(Dem_EventIdType eventId) { (void)eventId; } void Dem_Extension_PreMergeExtendedData(Dem_EventIdType eventId, boolean *UpdateAllData) { (void)eventId; (void)UpdateAllData; } void Dem_Extension_PreTransferPreInitFreezeFrames(Dem_EventIdType eventId, boolean *removeOldRecords, Dem_DTCOriginType origin) { (void)eventId; (void)removeOldRecords; (void)origin; }
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_Extension.c
C
unknown
3,933
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_EXTENSION_H_ #define DEM_EXTENSION_H_ #include "Dem.h" #include "Dem_Internal.h" #define DEM_EXTENSION_UPDATE_EVENT_STATUS_ID 0xA0 #define DEM_EXTENSION_INIT_ID 0xA1 #define DEM_EXTENSION_PRE_INIT_ID 0xA2 #define DEM_EXTENSION_EVENT_DATA_DISPLACED_ID 0xA3 /* Errors only used in the extension module */ #define DEM_E_EXTENSION_PRE_INIT_BUFFER_FULL 0x60 #define DEM_E_EXTENSION_EVENT_BUFF_FULL 0x61 void Dem_Extension_MainFunction(void); void Dem_Extension_ClearEvent(const Dem_EventParameterType *eventParam); void Dem_Extension_UpdateEventstatus(EventStatusRecType *eventStatusRecPtr, uint8 eventStatusExtendedBeforeUpdate, Dem_EventStatusType eventStatus); void Dem_Extension_OperationCycleStart(Dem_OperationCycleIdType operationCycleId, EventStatusRecType *eventStatusRecPtr); void Dem_Extension_OperationCycleEnd(Dem_OperationCycleIdType operationCycleId, EventStatusRecType *eventStatusRecPtr); void Dem_Extension_PreInit(const Dem_ConfigType *ConfigPtr); void Dem_Extension_Init_PostEventMerge(Dem_DTCOriginType origin); void Dem_Extension_Init_Complete(void); void Dem_Extension_Shutdown(void); void Dem_Extension_GetExtendedDataInternalElement(Dem_EventIdType eventId, Dem_InternalDataElementType internalElement, uint8 *dataBuf, uint16 size); void Dem_Extension_PostPreDebounceCounterBased(Dem_EventStatusType reportedStatus, EventStatusRecType* statusRecord); void Dem_Extension_HealedEvent(Dem_EventIdType eventId); #if defined(DEM_DISPLACEMENT_PROCESSING_DEM_EXTENSION) void Dem_Extension_GetExtDataEventForDisplacement(const Dem_EventParameterType *eventParam, const ExtDataRecType *extDataBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove); void Dem_Extension_GetEventForDisplacement(const Dem_EventParameterType *eventParam, const EventRecType *eventRecordBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove); /*lint !e9018 'eventRecordBuffer' with union based type 'EventRecType */ void Dem_Extension_GetFFEventForDisplacement(const Dem_EventParameterType *eventParam, const FreezeFrameRecType *ffBuffer, uint32 bufferSize, Dem_EventIdType *eventToRemove); #endif void Dem_Extension_EventDataDisplaced(Dem_EventIdType eventId); void Dem_Extension_EventExtendedDataDisplaced(Dem_EventIdType eventId); void Dem_Extension_EventFreezeFrameDataDisplaced(Dem_EventIdType eventId); void Dem_Extension_PreMergeExtendedData(Dem_EventIdType eventId, boolean *UpdateAllData); void Dem_Extension_PreTransferPreInitFreezeFrames(Dem_EventIdType eventId, boolean *removeOldRecords, Dem_DTCOriginType origin); Std_ReturnType Dem_GetSI30Status(Dem_EventIdType EventId, uint8* Status); Std_ReturnType Dem_Extension_GetEventId(uint32 const dtc, Dem_EventIdType *EventId); #endif /* DEM_EXTENSION_H_ */
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_Extension.h
C
unknown
3,613
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_INTERNAL_H_ #define DEM_INTERNAL_H_ #if defined(DEM_FREEZE_FRAME_CAPTURE_EXTENSION) #define DEM_EXT_STORE_FF_BIT (uint8)(1u<<0u) #define DEM_EXT_CLEAR_BEFORE_STORE_FF_BIT (uint8)(1u<<1u) #endif #if defined(DEM_EXTENDED_DATA_CAPTURE_EXTENSION) #define DEM_EXT_STORE_EXT_DATA_BIT (uint8)(1u<<2u) #define DEM_EXT_CLEAR_BEFORE_STORE_EXT_DATA_BIT (uint8)(1u<<3u) #endif #include "Dem.h" #if ( DEM_DEV_ERROR_DETECT == STD_ON ) #if defined(USE_DET) #include "Det.h" #endif /** @req DEM117 */ #define DET_REPORTERROR(_x,_y,_z,_q) (void)Det_ReportError(_x, _y, _z, _q) #else #define DET_REPORTERROR(_x,_y,_z,_q) #endif #if (DEM_NOF_TIME_BASE_PREDEB > 0) #define DEM_USE_TIME_BASE_PREDEBOUNCE #endif // For keeping track of the events status /* NOTE: Do not change EventStatusRecType without also changing generation of measurement tags */ typedef struct { const Dem_EventParameterType *eventParamRef; uint32 timeStamp; Dem_EventIdType eventId; uint16 occurrence; /** @req DEM011 */ sint16 fdcInternal; /** @req DEM414 */ sint8 UDSFdc; sint8 maxUDSFdc; uint8 failureCounter; uint8 agingCounter; Dem_EventStatusExtendedType eventStatusExtended; /** @req DEM006 */ uint8 extensionDataStoreBitfield; boolean failedDuringAgingCycle:1; /*lint !e46 *//*structure must remain the same, field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean passedDuringAgingCycle:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean failedDuringFailureCycle:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean passedDuringFailureCycle:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean errorStatusChanged:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean extensionDataChanged:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean indicatorDataChanged:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean isAvailable:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean isDisabled:1; /*lint !e46 *//*structure must remain the same,field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ } EventStatusRecType; // Types for storing different event data on event memory /* ****************************************************************************************************** * WARNING: DO NOT CHANGE THESE STRUCTURES WITHOUT UPDATED THE DEM GENERATOR!! * ******************************************************************************************************/ typedef union { struct { #if (DEM_USE_TIMESTAMPS == STD_ON) uint32 timeStamp; #endif Dem_EventIdType eventId; uint16 occurrence; Dem_EventStatusExtendedType eventStatusExtended; #if defined(DEM_FAILURE_PROCESSING_DEM_INTERNAL) uint8 failureCounter; #endif #if defined(DEM_AGING_PROCESSING_DEM_INTERNAL) uint8 agingCounter;/* @req DEM492 */ #endif }EventData; struct { /* NOTE: This must be kept smaller than the event data */ uint16 magic; boolean overflow; }AdminData; } EventRecType; typedef struct { #if (DEM_USE_TIMESTAMPS == STD_ON) uint32 timeStamp; #endif Dem_EventIdType eventId; uint8 data[DEM_MAX_SIZE_EXT_DATA]; } ExtDataRecType; #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) typedef struct { uint32 debounceTime; Dem_EventIdType EventId; boolean started:1;/*lint !e46 *//*structure must remain the same, field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean failureCounting:1;/*lint !e46 *//*structure must remain the same, field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean errorReported:1;/*lint !e46 *//*structure must remain the same, field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ boolean counterReset:1;/*lint !e46 *//*structure must remain the same, field type should be _Bool, unsigned int or signed int [MISRA 2004 6.4, 2012 6.1]*/ }TimeBaseStatusType; #endif typedef struct { // uint32 UDSDTC; uint32 OBDDTC; }PermanentDTCType; void lookupEventStatusRec(Dem_EventIdType eventId, EventStatusRecType **const eventStatusRec); boolean operationCycleIsStarted(Dem_OperationCycleIdType opCycle); #if (DEM_UNIT_TEST == STD_ON) void demZeroPriMemBuffers(void); void demZeroSecMemBuffers(void); void demZeroPermMemBuffers(void); void demZeroPreStoreFFMemBuffer(void); void demZeroIumprBuffer(void); void demSetIgnitionCounterToMax(void); void demSetDenominatorToMax(Dem_RatioIdType ratioId); void demSetNumeratorToMax(Dem_RatioIdType ratioId); #endif void lookupEventIdParameter(Dem_EventIdType eventId, const Dem_EventParameterType **const eventIdParam); Std_ReturnType handleEvent(Dem_EventIdType eventId, Dem_EventStatusType eventStatus); /* Debouncing functions */ void resetDebounceCounter(EventStatusRecType *eventStatusRec); Std_ReturnType getFaultDetectionCounter(Dem_EventIdType eventId, sint8 *counter); sint8 getDefaultUDSFdc(Dem_EventIdType eventId); Dem_EventStatusType RunPredebounce(Dem_EventStatusType reportedEventStatus, EventStatusRecType *eventStatusRecPtr, const Dem_EventParameterType *eventParam); #if defined(DEM_USE_TIME_BASE_PREDEBOUNCE) void InitTimeBasedDebounce(void); void TimeBasedDebounceMainFunction(void); #endif #if defined(USE_DEM_EXTENSION) boolean Dem_LookupEventOfUdsDTC(uint32 dtc, EventStatusRecType **eventStatusRec); #endif #define DEM_TRISTATE int8_t #define DEM_T_NULL -1 #define DEM_T_FALSE 0 #define DEM_T_TRUE 1 #endif /* DEM_INTERNAL_H_ */
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_Internal.h
C
unknown
7,613
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Dem_NvM.h" #if defined(USE_NVM) #include "NvM.h" #endif /* Local defines */ #define DEM_NO_NVM_BLOCK 0u /* Local types */ #if defined(NVM_NOT_SERVICE_COMPONENT) && defined(USE_RTE) && defined(USE_NVM) && (DEM_USE_NVM == STD_ON) /* NvM_BlockIdType is defined in the RTE when using NvM service component or in NvM when not using rte * If neither is fulfilled, typedef it here since used by DEM */ typedef uint16 NvM_BlockIdType; #endif typedef enum { DEM_NVMBLOCK_PRIMARY_EVENT = 0, DEM_NVMBLOCK_PRIMARY_FF, DEM_NVMBLOCK_PRIMARY_EXTDATA, DEM_NVMBLOCK_SECONDARY_EVENT, DEM_NVMBLOCK_SECONDARY_FF, DEM_NVMBLOCK_SECONDARY_EXTDATA, DEM_NVMBLOCK_INDICATORS, DEM_NVMBLOCK_STATUSBIT, DEM_NVMBLOCK_PERMANENT, DEM_NVMBLOCK_PRESTORED_FF, DEM_NVMBLOCK_IUMPR, #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) DEM_NOF_SUPPORTED_NVM_BLOCKS #endif }DemNvMBlockIdType; #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) typedef enum { DEM_NVM_IDLE = 0, DEM_NVM_SETRAMBLOCKSTATUS, DEM_NVM_WRITEBLOCK, DEM_NVM_WAIT_DONE }DemNvMStateType; typedef struct { DemNvMStateType State; boolean Dirty; boolean PendingWrite; }DemNvMBlockStatusType; typedef struct { NvM_BlockIdType BlockId; }DemNvMBlockCfgType; #endif /* Local function prototypes */ static void setNvMBlockChanged(DemNvMBlockIdType blockId, boolean ImmediateStorage); /* Local constants */ #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) const DemNvMBlockCfgType DemNvMBlockConfig[DEM_NOF_SUPPORTED_NVM_BLOCKS] = { [DEM_NVMBLOCK_PRIMARY_EVENT] = { .BlockId = DEM_EVENT_PRIMARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_PRIMARY_FF] = { .BlockId = DEM_FREEZE_FRAME_PRIMARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_PRIMARY_EXTDATA] = { .BlockId = DEM_EXTENDED_DATA_PRIMARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_SECONDARY_EVENT] = { .BlockId = DEM_EVENT_SECONDARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_SECONDARY_FF] = { .BlockId = DEM_FREEZE_FRAME_SECONDARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_SECONDARY_EXTDATA] = { .BlockId = DEM_EXTENDED_DATA_SECONDARY_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_INDICATORS] = { .BlockId = DEM_INDICATOR_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_STATUSBIT] = { .BlockId = DEM_STATUSBIT_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_PERMANENT] = { .BlockId = DEM_PERMANENT_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_PRESTORED_FF] = { .BlockId = DEM_PRESTORE_FF_NVM_BLOCK_HANDLE }, [DEM_NVMBLOCK_IUMPR] = { .BlockId = DEM_PERMANENT_NVM_BLOCK_HANDLE } }; /* Local variables */ static DemNvMBlockStatusType DemNvMBlockStatus[DEM_NOF_SUPPORTED_NVM_BLOCKS]; #endif /* Local functions */ /** * * @param blockId * @param ImmediateStorage */ /*lint --e{522} CONFIGURATION */ static void setNvMBlockChanged(DemNvMBlockIdType blockId, boolean ImmediateStorage) { #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) if( DEM_NO_NVM_BLOCK != DemNvMBlockConfig[blockId].BlockId ) { DemNvMBlockStatus[blockId].Dirty = TRUE; if( TRUE == ImmediateStorage ) { DemNvMBlockStatus[blockId].PendingWrite = TRUE; } } #else (void)blockId; (void)ImmediateStorage; #endif } /* Exported functions */ /** * * @param Origin * @param ImmediateStorage */ void Dem_NvM_SetEventBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage) { switch(Origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_PRIMARY_EVENT, ImmediateStorage); break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_SECONDARY_EVENT, ImmediateStorage); break; default: break; } } /** * * @param Origin * @param ImmediateStorage */ void Dem_NvM_SetFreezeFrameBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage) { switch(Origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_PRIMARY_FF, ImmediateStorage); break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_SECONDARY_FF, ImmediateStorage); break; default: break; } } void Dem_NvM_SetPreStoreFreezeFrameBlockChanged(boolean ImmediateStorage) { setNvMBlockChanged(DEM_NVMBLOCK_PRESTORED_FF, ImmediateStorage); } /** * * @param Origin * @param ImmediateStorage */ void Dem_NvM_SetExtendedDataBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage) { switch(Origin) { case DEM_DTC_ORIGIN_PRIMARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_PRIMARY_EXTDATA, ImmediateStorage); break; case DEM_DTC_ORIGIN_SECONDARY_MEMORY: setNvMBlockChanged(DEM_NVMBLOCK_SECONDARY_EXTDATA, ImmediateStorage); break; default: break; } } /** * * @param ImmediateStorage */ void Dem_NvM_SetIndicatorBlockChanged(boolean ImmediateStorage) { setNvMBlockChanged(DEM_NVMBLOCK_INDICATORS, ImmediateStorage); } /** * * @param ImmediateStorage */ void Dem_NvM_SetStatusBitSubsetBlockChanged(boolean ImmediateStorage) { setNvMBlockChanged(DEM_NVMBLOCK_STATUSBIT, ImmediateStorage); } /** * * @param ImmediateStorage */ void Dem_NvM_SetPermanentBlockChanged(boolean ImmediateStorage) { setNvMBlockChanged(DEM_NVMBLOCK_PERMANENT, ImmediateStorage); } /** * * @param ImmediateStorage */ void Dem_Nvm_SetIumprBlockChanged(boolean ImmediateStorage) { setNvMBlockChanged(DEM_NVMBLOCK_IUMPR, ImmediateStorage); } /** * Init function for Dem_NvM */ void Dem_NvM_Init(void) { #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) for( uint8 blockId = 0u; blockId < (uint8)DEM_NOF_SUPPORTED_NVM_BLOCKS; blockId++ ) { DemNvMBlockStatus[blockId].Dirty = FALSE; DemNvMBlockStatus[blockId].PendingWrite = FALSE; DemNvMBlockStatus[blockId].State = DEM_NVM_IDLE; } #endif } /** * Main function for Dem_NvM. Should be called periodically. */ void Dem_NvM_MainFunction(void) { /* !req DEM579 *//* No NOT ignore return values. Try again. Although the actual result of the write job */ /* @req DEM164 *//* Only NvM_WriteBlock is used. */ /* @req DEM329 */ #if defined(USE_NVM) && (DEM_USE_NVM == STD_ON) NvM_RequestResultType reqRes; for( uint8 blockId = 0u; blockId < (uint8)DEM_NOF_SUPPORTED_NVM_BLOCKS; blockId++ ) { /* Check if any pending write job */ if( (DEM_NVM_IDLE == DemNvMBlockStatus[blockId].State) && ( (TRUE == DemNvMBlockStatus[blockId].PendingWrite) || (TRUE == DemNvMBlockStatus[blockId].Dirty) ) ) { #if (NVM_SET_RAM_BLOCK_STATUS_API == STD_ON) DemNvMBlockStatus[blockId].State = DEM_NVM_SETRAMBLOCKSTATUS; #else DemNvMBlockStatus[blockId].State = DEM_NVM_WRITEBLOCK; #endif } switch(DemNvMBlockStatus[blockId].State) { case DEM_NVM_SETRAMBLOCKSTATUS: #if (NVM_SET_RAM_BLOCK_STATUS_API == STD_ON) if(E_OK == NvM_GetErrorStatus(DemNvMBlockConfig[blockId].BlockId, &reqRes)) { if(NVM_REQ_PENDING != reqRes) { if( E_OK == NvM_SetRamBlockStatus(DemNvMBlockConfig[blockId].BlockId, TRUE) ) { DemNvMBlockStatus[blockId].Dirty = FALSE; if(TRUE == DemNvMBlockStatus[blockId].PendingWrite) { DemNvMBlockStatus[blockId].State = DEM_NVM_WRITEBLOCK; } else { DemNvMBlockStatus[blockId].State = DEM_NVM_WAIT_DONE; } } } } #endif break; case DEM_NVM_WRITEBLOCK: if(E_OK == NvM_GetErrorStatus(DemNvMBlockConfig[blockId].BlockId, &reqRes)) { if(NVM_REQ_PENDING != reqRes) { if( E_OK == NvM_WriteBlock(DemNvMBlockConfig[blockId].BlockId, NULL) ) { DemNvMBlockStatus[blockId].PendingWrite = FALSE; DemNvMBlockStatus[blockId].Dirty = FALSE; DemNvMBlockStatus[blockId].State = DEM_NVM_WAIT_DONE; } } } break; case DEM_NVM_WAIT_DONE: if(E_OK == NvM_GetErrorStatus(DemNvMBlockConfig[blockId].BlockId, &reqRes)) { if(NVM_REQ_PENDING != reqRes) { /* Write job done */ DemNvMBlockStatus[blockId].State = DEM_NVM_IDLE; } } break; default: break; } } #endif }
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_NvM.c
C
unknown
9,884
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef DEM_NVM_H_ #define DEM_NVM_H_ #include "Dem.h" void Dem_NvM_SetEventBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage); void Dem_NvM_SetFreezeFrameBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage); void Dem_NvM_SetExtendedDataBlockChanged(Dem_DTCOriginType Origin, boolean ImmediateStorage); void Dem_NvM_SetIndicatorBlockChanged(boolean ImmediateStorage); void Dem_NvM_SetStatusBitSubsetBlockChanged(boolean ImmediateStorage); void Dem_NvM_SetPermanentBlockChanged(boolean ImmediateStorage); void Dem_NvM_SetPreStoreFreezeFrameBlockChanged(boolean ImmediateStorage); void Dem_Nvm_SetIumprBlockChanged(boolean ImmediateStorage); void Dem_NvM_Init(void); void Dem_NvM_MainFunction(void); #endif /* DEM_NVM_H_ */
2301_81045437/classic-platform
diagnostic/Dem/src/Dem_NvM.h
C
unknown
1,520
#DET obj-$(USE_DET) += Det.o obj-$(USE_DET) += Det_Cfg.o inc-$(USE_DET) += $(ROOTDIR)/diagnostic/Det/inc inc-$(USE_DET) += $(ROOTDIR)/diagnostic/Det/src vpath-$(USE_DET) += $(ROOTDIR)/diagnostic/Det/src
2301_81045437/classic-platform
diagnostic/Det/Det.mod.mk
Makefile
unknown
207
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ /** @file Det.h * * The Det (Default Error Tracer) Module provides functionality to collect errors * in the system. In order to do so it has a function that can be called by any other * module Det_RerportError. This function can then depending on configuration distribute * the error within the system. */ /* @req SWS_Det_00004 * The Default Error Tracer module’s source code shall offer a headerfileDet.h * * @req SWS_Det_00037 * Det.h includes all user relevant information for the tracing of errors reported via its services. * */ #ifndef DET_H #define DET_H /* @req SWS_BSW_00024 Include AUTOSAR Standard Types Header in implementation header */ #include "Std_Types.h" #define DET_MODULE_ID 15u #define DET_VENDOR_ID 60u /* @req SWS_BSW_00059 Published information */ /* Implementation version */ #define DET_SW_MAJOR_VERSION 2u #define DET_SW_MINOR_VERSION 0u #define DET_SW_PATCH_VERSION 0u /* AUTOSAR specification document version */ #define DET_AR_MAJOR_VERSION 4u #define DET_AR_MINOR_VERSION 3u #define DET_AR_RELEASE_REVISION_VERSION 0u #define DET_AR_RELEASE_MAJOR_VERSION DET_AR_MAJOR_VERSION #define DET_AR_RELEASE_MINOR_VERSION DET_AR_MINOR_VERSION /* @req SWS_BSW_00020 */ #include "Det_Cfg.h" /* Type needed by config file. */ /* @req SWS_Det_00180 */ typedef void (*detCbk_t)( uint16 ModuleId, uint8 InstanceId , uint8 ApiId, uint8 ErrorId); /* @req SWS_BSW_00201 Development errors should be of type uint8 */ /* @req SWS_BSW_00073 Implementation specific errors */ // Error codes #define DET_E_PARAM_POINTER 0x01u #define DET_E_CBK_REGISTRATION_FAILED 0x02u #define DET_E_INDEX_OUT_OF_RANGE 0x03u #define DET_CALLBACK_API 0xFFu #define DET_CBK_REGISTRATION_FAILED_INDEX 0xFFu #define DET_INIT_SERVICE_ID 0x00u #define DET_REPORTERROR_SERVICE_ID 0x01u #define DET_START_SERVICE_ID 0x02u #define DET_GETVERSIONINFO_SERVICE_ID 0x03u typedef uint8 Det_ReturnType; #define DET_OK (Det_ReturnType)0u #define DET_EMPTY (Det_ReturnType)1u #define DET_ERROR (Det_ReturnType)2u // Type used to store errors typedef struct { uint16 moduleId; uint8 instanceId; uint8 apiId; uint8 errorId; } Det_EntryType; typedef uint8 Det_ConfigType; /** Empty type for supporting new 4.3.0 API */ #if ( DET_ENABLE_CALLBACKS == STD_ON ) /* * Add a callback function to the array of callback. After a call to Det_ReportError the callback * is called. This can be used in for instance unit tests to verify that correct errors are * reported when sending invalid parameters to a function. * * */ /** @brief Add a callback function to the array of callback. After a call to Det_ReportError the callback * is called. This can be used in for instance unit tests to verify that correct errors are * reported when sending invalid parameters to a function. * * @param detCbk The callback that should be used. * @return This function returns the index of the callback in the array when registration is successful. If not DET_CBK_REGISTRATION_FAILED_INDEX is returned. */ uint8 Det_AddCbk ( detCbk_t detCbk); /** @brief Removed a callback from the list of callbacks. * * @param detCbkIndex The index of the callback. This index was returned from the Det_AddCbk function. * @return void. */ void Det_RemoveCbk ( uint8 detCbkIndex); #endif /** @brief Initialize the module * This is kept here for backward compatibility * @return void. */ /* @req SWS_Det_00019 * @req SWS_Det_00008 * The DET shall provide the initialization function Det_Init */ void Det_Init( void /*const Det_ConfigType* ConfigPtr*/ ); /** @brief Deinitialize the module * @return void. */ #if (DET_DEINIT_API == STD_ON) void Det_DeInit( void ); #endif /** @brief Start the module * @return void. */ /* @req SWS_Det_00025 * The Default Error Tracer shall provide the function Det_Start * * @req SWS_Det_00010 */ void Det_Start( void ); /** @brief This service should be used by other modules or components in the software * to report errors. * @param ModuleId The module reporting the error. Modeule IDs are defined in the module specific header files. * @param InstanceId If there are more that one instance of a modeule it can be reported here. * @param ApiId The API that reports the error (Module specific) * @param ErrorId The error that is reporter (API specific) * @return E_OK if everything was OK otherwise an internal error is reported. */ /* @req SWS_Det_00009 */ Std_ReturnType Det_ReportError( uint16 ModuleId, uint8 InstanceId, uint8 ApiId, uint8 ErrorId); /** @brief Return the version information of Det module. * * The function Det_GetVersionInfo shall return the version * information of the Det module. * The version information includes: * - Module Id * - Vendor Id * - sw_major_version * - sw_minor_version * - sw_patch_version * * @param Std_VersionInfoType The type including Module and Vendor ID for the Det Module. * @return void. */ /* @req SWS_BSW_00051 */ /* @req SWS_Det_00011 */ #if (DET_VERSIONINFO_API == STD_ON) void Det_GetVersionInfo(Std_VersionInfoType* vi); #endif /** @brief This service is used by the Safety Monitor to read out the latest error reporter to Det * @param entry Pointer to an entry that will be filled with information in the service. * @return status of the call: * DET_OK - The entry value will include latest error * DET_EMPTY - There was no new errors reported * DET_ERROR - There was an internal error inside of Det */ #if (DET_SAFETYMONITOR_API == STD_ON) Det_ReturnType Det_GetNextError(Det_EntryType* entry); #endif #endif /*DET_H*/
2301_81045437/classic-platform
diagnostic/Det/inc/Det.h
C
unknown
6,690
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ /* @req SWS_BSW_00005 include implementation file */ #include "Det.h" #if (DET_SAFETYMONITOR_API == STD_ON) #include <string.h> #include "Safety_Queue.h" #endif #define DEBUG_LVL 1 #include "debug.h" #include "SchM_Det.h" #if (DET_FORWARD_TO_DLT == STD_ON) #include "Dlt.h" #endif /* ----------------------------[Version check]------------------------------*/ #if !(((DET_SW_MAJOR_VERSION == 2) && (DET_SW_MINOR_VERSION == 0)) ) #error Det: Expected BSW module version to be 2.0.* #endif #if !(((DET_AR_MAJOR_VERSION == 4) && (DET_AR_MINOR_VERSION == 3)) ) #error Det: Expected AUTOSAR version to be 4.3.* #endif /* ----------------------------[private define]------------------------------*/ typedef enum { DET_UNINITIALIZED = 0, DET_INITIALIZED, DET_STARTED } Det_StateType; #define DET_STATE_START_SEC_VAR_CLEARED_UNSPECIFIED /*lint -e9019 MISRA:EXTERNAL_FILE:suppressed due to Det_BswMemMap.h include is needed:[MISRA 2012 Rule 20.1, advisory] */ /*lint -e451 MISRA:CONFIGURATION:suppressed due to Det_BswMemMap.h include is needed:[MISRA 2012 Directive 4.10, required] */ #include "Det_BswMemMap.h" static Det_StateType detState = DET_UNINITIALIZED; #define DET_STATE_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" /* @req SWS_BSW_00006 include BSW Memory mapping header*/ #if (DET_SAFETYMONITOR_API == STD_ON) #define DET_SIZEOF_SMQUEUE (32) #define DET_MONITOR_START_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" /*lint -e9003 MISRA:OTHER:To store error values:[MISRA 2012 Rule 8.9, advisory]*/ static Det_EntryType Det_SafetyMonitorBuffer[DET_SIZEOF_SMQUEUE]; #define DET_MONITOR_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" #define DET_MONITOR_START_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" static Safety_Queue_t Det_SafetyMonitorQueue; #define DET_MONITOR_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" // Just a dummy to make the queue happy. typedef int local_int; static local_int DummyFunc(void *A, void *B, size_t size) { (void)A; /*lint !e920 MISRA:STANDARDIZED_INTERFACE:to store dummy values:[MISRA 2012 Rule 1.3, required]*/ (void)B;/*lint !e920 MISRA:STANDARDIZED_INTERFACE:to store dummy values:[MISRA 2012 Rule 1.3, required]*/ (void)size; return 0; } #endif #if ( DET_USE_RAMLOG == STD_ON ) // Ram log variables in uninitialized memory SECTION_RAMLOG uint32 Det_RamlogIndex; SECTION_RAMLOG Det_EntryType Det_RamLog[DET_RAMLOG_SIZE] ; #endif #if ( DET_USE_STATIC_CALLBACKS == STD_ON ) /*lint -e{9003} MISRA:EXTERNAL_FILE:variable declared outside:[MISRA 2012 Rule 8.9, advisory]*/ extern detCbk_t DetStaticHooks[]; #endif #if ( DET_ENABLE_CALLBACKS == STD_ON ) #define DET_STATE_START_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" static detCbk_t detCbk_List[DET_NUMBER_OF_CALLBACKS]; #define DET_STATE_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "Det_BswMemMap.h" uint8 Det_AddCbk(detCbk_t detCbk) { uint8 rv = DET_CBK_REGISTRATION_FAILED_INDEX; // Return DET_CBK_REGISTRATION_FAILED_INDEX if the registration fails if (detState != DET_UNINITIALIZED) { for (uint8 i = 0; i < DET_NUMBER_OF_CALLBACKS; i++) { if (NULL == detCbk_List[i]) { detCbk_List[i] = detCbk; rv = i; break; } } } if (rv == DET_CBK_REGISTRATION_FAILED_INDEX) { /* Ignoring return value */ (void)Det_ReportError(DET_MODULE_ID, 0, DET_CALLBACK_API, DET_E_CBK_REGISTRATION_FAILED); } return rv; } void Det_RemoveCbk(uint8 detCbkIndex) { /* @req SWS_BSW_00049 Parameter checking*/ // Validate the index if (detCbkIndex >= DET_NUMBER_OF_CALLBACKS) { /* Ignoring return value */ (void)Det_ReportError(DET_MODULE_ID, 0, DET_CALLBACK_API, DET_E_INDEX_OUT_OF_RANGE); } else { detCbk_List[detCbkIndex]=NULL; } } #endif /* @req SWS_Det_00020 * Each call of the Det_Init function shall be used to set the Default Error Tracer to a defined initial status */ /* @req SWS_BSW_00071 initialize BSW module*/ void Det_Init(void /*const Det_ConfigType* ConfigPtr*/) { #if ( DET_ENABLE_CALLBACKS == STD_ON ) for (uint32 i=0; i<DET_NUMBER_OF_CALLBACKS; i++) { detCbk_List[i]=NULL; } #endif #if ( DET_USE_RAMLOG == STD_ON ) for(uint32 i=0; i < DET_RAMLOG_SIZE; i++) { Det_RamLog[i].moduleId = 0; Det_RamLog[i].instanceId = 0; Det_RamLog[i].apiId = 0; Det_RamLog[i].errorId = 0; } Det_RamlogIndex = 0; #endif #if (DET_SAFETYMONITOR_API == STD_ON) for(uint32 i=0; i < DET_SIZEOF_SMQUEUE; i++) { Det_SafetyMonitorBuffer[i].moduleId = 0; Det_SafetyMonitorBuffer[i].instanceId = 0; Det_SafetyMonitorBuffer[i].apiId = 0; Det_SafetyMonitorBuffer[i].errorId = 0; } memset(&Det_SafetyMonitorQueue, 0 , sizeof(Safety_Queue_t)); if (E_OK == Safety_Queue_Init(&Det_SafetyMonitorQueue, Det_SafetyMonitorBuffer, DET_SIZEOF_SMQUEUE, sizeof(Det_EntryType), DummyFunc)) { detState = DET_INITIALIZED; } #else detState = DET_INITIALIZED; #endif } /* @req SWS_BSW_00072 deinitialize BSW module */ #if DET_DEINIT_API == STD_ON void Det_DeInit( void ) { detState = DET_UNINITIALIZED; } #endif /* @req SWS_Det_00039 */ Std_ReturnType Det_ReportError(uint16 ModuleId, uint8 InstanceId, uint8 ApiId, uint8 ErrorId) { Std_ReturnType rVal = E_OK; #if (DET_SAFETYMONITOR_API == STD_ON) Det_EntryType error; #endif /* @req SWS_Det_00024 */ if (detState == DET_STARTED) // No action is taken if the module is not started { /* @req SWS_Det_00207 * @req SWS_Det_00015 * @req SWS_Det_00014 * @req SWS_Det_00501 */ // Call static error hooks here #if ( DET_USE_STATIC_CALLBACKS == STD_ON ) SchM_Enter_Det_EA_0(); /* * @req SWS_Det_00035 * @req SWS_Det_00181 * @req SWS_Det_00018 */ for (uint32 i=0; i<DET_NUMBER_OF_STATIC_CALLBACKS; i++) { (*DetStaticHooks[i])(ModuleId, InstanceId, ApiId, ErrorId); } SchM_Exit_Det_EA_0(); #endif /* @req SWS_Det_00034 */ #if (DET_FORWARD_TO_DLT == STD_ON) Dlt_DetForwardErrorTrace(ModuleId, InstanceId, ApiId, ErrorId); #endif #if ( DET_ENABLE_CALLBACKS == STD_ON ) /*lint -e534 MISRA:CONFIGURATION:ignoring return value:[MISRA 2012 Rule 17.7, required] */ SchM_Enter_Det_EA_0(); for (uint32 i=0; i<DET_NUMBER_OF_CALLBACKS; i++) { if (NULL!=detCbk_List[i]) { (*detCbk_List[i])(ModuleId, InstanceId, ApiId, ErrorId); } } SchM_Exit_Det_EA_0(); #endif #if ( DET_USE_RAMLOG == STD_ON ) /*lint -e534 MISRA:CONFIGURATION:ignoring return value:[MISRA 2012 Rule 17.7, required] */ SchM_Enter_Det_EA_0(); if (Det_RamlogIndex < DET_RAMLOG_SIZE) { Det_RamLog[Det_RamlogIndex].moduleId = ModuleId; Det_RamLog[Det_RamlogIndex].instanceId = InstanceId; Det_RamLog[Det_RamlogIndex].apiId = ApiId; Det_RamLog[Det_RamlogIndex].errorId = ErrorId; Det_RamlogIndex++; #if ( DET_WRAP_RAMLOG == STD_ON ) if (Det_RamlogIndex == DET_RAMLOG_SIZE){ Det_RamlogIndex = 0; } #endif } SchM_Exit_Det_EA_0(); #endif #if (DET_SAFETYMONITOR_API == STD_ON) error.moduleId = ModuleId; error.instanceId = InstanceId; error.apiId = ApiId; error.errorId = ErrorId; rVal = Safety_Queue_Add(&Det_SafetyMonitorQueue, &error); if (rVal == E_OK) { /* @req ARC_SWS_DET_00002 */ rVal = SYS_CALL_SetEvent(DET_SAFETYMONITOR_TASK, DET_SAFETYMONITOR_EVENT); } #endif #if ( DET_USE_STDERR == STD_ON ) printf("Det Error: ModuleId=%d, InstanceId=%d, ApiId=%d, ErrorId=%d\n", ModuleId, InstanceId, ApiId, ErrorId); /*lint !e586, OK deprecated */ #endif } return rVal; } void Det_Start(void) { detState = DET_STARTED; } /* @req ARC_SWS_DET_00001*/ #if (DET_SAFETYMONITOR_API == STD_ON) Det_ReturnType Det_GetNextError(Det_EntryType* entry) { Std_ReturnType err; Det_ReturnType rVal; /* @req SWS_BSW_00049 Parameter checking*/ /* @req SWS_BSW_00212 NULL pointer check */ if (entry != NULL_PTR) { SchM_Enter_Det_EA_0(); err = Safety_Queue_Next(&Det_SafetyMonitorQueue, entry); SchM_Exit_Det_EA_0(); switch (err) { case QUEUE_E_OK: rVal = DET_OK; break; case QUEUE_E_NO_DATA: rVal = DET_EMPTY; break; default: rVal = DET_ERROR; break; } } else { rVal = DET_ERROR; } return rVal; } #endif /* @req SWS_BSW_00064 GetVersionInfo shall execute synchonously */ /* @req SWS_BSW_00052 GetVersion info shall only have one parameter */ /* @req SWS_BSW_00164 No restriction on calling context */ #if (DET_VERSIONINFO_API == STD_ON) void Det_GetVersionInfo(Std_VersionInfoType* vi) { /* @req SWS_BSW_00049 Parameter checking*/ /* @req SWS_BSW_00212 NULL pointer check */ if(vi != NULL) { vi->vendorID = DET_VENDOR_ID; vi->moduleID = DET_MODULE_ID; vi->sw_major_version = DET_SW_MAJOR_VERSION; vi->sw_minor_version = DET_SW_MINOR_VERSION; vi->sw_patch_version = DET_SW_PATCH_VERSION; } else { /* @req SWS_Det_00301 */ /* @req SWS_Det_00052 */ (void)Det_ReportError(DET_MODULE_ID, 0, DET_GETVERSIONINFO_SERVICE_ID, DET_E_PARAM_POINTER); } } #endif
2301_81045437/classic-platform
diagnostic/Det/src/Det.c
C
unknown
10,763
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ /*lint -save -e9019 MISRA:OTHER:suppressed to be able to get the memap work:[MISRA 2012 Rule 20.1, advisory] */ /*lint -save -e9021 MISRA:OTHER:suppressed to be able to get the memap work:[MISRA 2012 Rule 20.5, advisory]*/ #define DET_MEMMAP_ERROR #ifdef DET_STATE_START_SEC_VAR_CLEARED_UNSPECIFIED #include "MemMap.h" #undef DET_MEMMAP_ERROR #undef DET_STATE_START_SEC_VAR_CLEARED_UNSPECIFIED #endif #ifdef DET_STATE_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "MemMap.h" #undef DET_MEMMAP_ERROR #undef DET_STATE_STOP_SEC_VAR_CLEARED_UNSPECIFIED #endif #ifdef DET_MONITOR_START_SEC_VAR_CLEARED_UNSPECIFIED #include "MemMap.h" #undef DET_MEMMAP_ERROR #undef DET_MONITOR_START_SEC_VAR_CLEARED_UNSPECIFIED #endif #ifdef DET_MONITOR_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "MemMap.h" #undef DET_MEMMAP_ERROR #undef DET_MONITOR_STOP_SEC_VAR_CLEARED_UNSPECIFIED #endif #ifdef DET_MEMMAP_ERROR #error "DET error, section not mapped" #endif /*lint -restore */
2301_81045437/classic-platform
diagnostic/Det/src/Det_BswMemMap.h
C
unknown
1,809
# Dlt obj-$(USE_DLT) += Dlt.o obj-$(USE_DLT) += Dlt_cfg.o ifeq ($(filter Dlt_Callout_Stubs.o,$(obj-y)),) obj-$(USE_DLT) += Dlt_Callout_Stubs.o endif vpath-$(USE_DLT) += $(ROOTDIR)/diagnostic/Dlt/src inc-$(USE_DLT) += $(ROOTDIR)/diagnostic/Dlt/inc
2301_81045437/classic-platform
diagnostic/Dlt/Dlt.mod.mk
Makefile
unknown
255
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* * Diagnostic Log & Trace module * */ /* * General requirements */ #ifndef DLT_H #define DLT_H #include "Std_Types.h" /** @req SWS_Dlt_00482 */ #include "Rte_Dlt_Type.h" #if defined(USE_DEM) #include "Dem.h" #endif #define DLT_MODULE_ID 55u #define DLT_VENDOR_ID 60u /* Implementation version */ #define DLT_SW_MAJOR_VERSION 1u #define DLT_SW_MINOR_VERSION 0u #define DLT_SW_PATCH_VERSION 0u /* AUTOSAR specification document version */ #define DLT_AR_MAJOR_VERSION 4u #define DLT_AR_MINOR_VERSION 0u #define DLT_AR_RELEASE_REVISION_VERSION 3u /* Error Codes */ /* @req SWS_Dlt_00447 */ #define DLT_E_WRONG_PARAMETERS 0x01u #define DLT_E_ERROR_IN_PROV_SERVICE 0x02u #define DLT_E_COM_FAILURE 0x03u #define DLT_E_ERROR_TO_MANY_CONTEXT 0x04u #define DLT_E_MSG_LOOSE 0x05u #define DLT_E_PARAM_POINTER 0x06u /** Service id's */ #define DLT_INIT_SERVICE_ID 0x01u /* @req SWS_Dlt_00239 */ #define DLT_GETVERSIONINFO_SERVICE_ID 0x02u /* @req SWS_Dlt_00271 */ #define DLT_DETFORWARDERRORTRACE_SERVICE_ID 0x07u /* @req SWS_Dlt_00432 */ #define DLT_DEMTRIGGERONEVENTSTATUS_SERVICE_ID 0x15u /* @req SWS_Dlt_00470 */ #define DLT_SENDLOGMESSAGE_SERVICE_ID 0x03u /* @req SWS_Dlt_00241 */ /* @req SWS_Dlt_00238 */ #define DLT_E_OK 0U #define DLT_E_MSG_TOO_LARGE 1U #define DLT_E_CONTEXT_ALREADY_REG 2U #define DLT_E_UNKNOWN_SESSION_ID 3U #define DLT_E_IF_NOT_AVAILABLE 4U #define DLT_E_IF_BUSY 5U #define DLT_E_ERROR_UNKNOWN 6U #define DLT_E_PENDING 7U #define DLT_E_NOT_IN_VERBOSE_MOD 8U /* @req SWS_Dlt_00437 */ typedef struct { const char *EcuId; } Dlt_ConfigType; typedef enum { DLT_TYPE_LOG, DLT_TYPE_APP_TRACE, DLT_TYPE_NW_TRACE, DLT_TYPE_CONTROL, } Dlt_MessageType; /* @req SWS_Dlt_00458 */ /* @req SWS_Dlt_00094 */ /* @req SWS_Dlt_00319 */ /* @req SWS_Dlt_00320 */ typedef struct { uint8 HeaderType; uint8 MessageCounter; uint16 Length; } Dlt_StandardHeaderType; #define DLT_UEH (1u<<0u) #define DLT_MSBF (1u<<1u) #define DLT_WEID (1u<<2u) #define DLT_WSID (1u<<3u) #define DLT_WTMS (1u<<4u) #define DLT_VERS (1u<<5u) typedef struct { uint8 MSIN; uint8 NOAR; uint8 APID[4]; uint8 CTID[4]; } Dlt_ExtendedHeaderType; #include "Dlt_cfg.h" #include "Dlt_PBcfg.h" /* * Implemented functions ****************************/ #if ( DLT_VERSION_INFO_API == STD_ON) /** * Gets the version info * @param versioninfo - struct holding the version info */ /* @req SWS_Dlt_00271 */ #if ( DLT_VERSION_INFO_API == STD_ON ) #define Dlt_GetVersionInfo(_vi) STD_GET_VERSION_INFO(_vi,DLT) #endif /* DLT_VERSION_INFO_API */ #endif void Dlt_Init(const Dlt_ConfigType* ConfigPtr); Dlt_ReturnType Dlt_SendLogMessage(Dlt_SessionIDType session_id, const Dlt_MessageLogInfoType* log_info, const uint8* log_data, uint16 log_data_length); Dlt_ReturnType Dlt_SendTraceMessage(Dlt_SessionIDType session_id, const Dlt_MessageTraceInfoType* trace_info, const uint8* trace_data, uint16 trace_data_length); Dlt_ReturnType Dlt_RegisterContext(Dlt_SessionIDType session_id, Dlt_ApplicationIDType app_id, Dlt_ContextIDType context_id, const uint8* app_description, uint8 len_app_description, const uint8* context_description, uint8 len_context_description); #if defined(USE_DEM) void Dlt_DemTriggerOnEventStatus(Dem_EventIdType EventId, Dem_EventStatusExtendedType EventStatusByteOld, Dem_EventStatusExtendedType EventStatusByteNew); #endif void Dlt_DetForwardErrorTrace(uint16 ModuleId, uint8 InstanceId, uint8 ApiId, uint8 ErrorId); #include "ComStack_Types.h" /* Interfaces provided by Dlt core module for internal use with Dlt communication module */ /* @req SWS_Dlt_00272 */ void Dlt_ComRxIndication(PduIdType DltRxPduId, Std_ReturnType Result); /* @req SWS_Dlt_00273 */ void Dlt_ComTxConfirmation(PduIdType DltTxPduId, Std_ReturnType Result); /* @req SWS_Dlt_00515 */ BufReq_ReturnType DltCom_CopyRxData(PduIdType id, const PduInfoType* pduInfoPtr, PduLengthType* bufferSizePtr); /* @req SWS_Dlt_00516 */ BufReq_ReturnType DltCom_CopyTxData(PduIdType id, const PduInfoType* pduInfoPtr, RetryInfoType* retryInfoPtr, PduLengthType* availableDataPtr); /* @req SWS_Dlt_00517 */ BufReq_ReturnType DltCom_StartOfReception(PduIdType id, const PduInfoType* infoPtr, PduLengthType tpSduLength, PduLengthType* bufferSizePtr); /* @req SWS_Dlt_00263 */ Std_ReturnType DltCom_Transmit(PduIdType DltTxPduId, const PduInfoType* PduInfoPtr); /* !req SWS_Dlt_00264 */ BufReq_ReturnType DltCom_CancelTransmitRequest(PduIdType id); /* !req SWS_Dlt_00265 */ Dlt_ReturnType DltCom_SetInterfaceStatus(uint8 com_interface[4], uint8 new_status); Std_ReturnType DltCom_ReceiveIndication(PduIdType DltRxPduId, const PduInfoType* PduInfoPtr); void DltCom_Init(void); #define DLT_RESP_OK 0U #define DLT_RESP_NOT_SUPPORTED 1U #define DLT_RESP_ERROR 2U #define DLT_ARC_MAGIC_CONTROL_NUMBER 0xCCCC #define DLT_DEM_MESSAGE_ID 0x00000001u #define DLT_DET_MESSAGE_ID 0x00000002u void Dlt_ArcProcessIncomingMessage(const Dlt_StandardHeaderType *header, const uint8 *payload); boolean Dlt_ArcIsDltConnected(void); #endif /* DLT_H */
2301_81045437/classic-platform
diagnostic/Dlt/inc/Dlt.h
C
unknown
6,216
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* * Diagnostic Log & Trace module * */ /* Requirements implemented */ /* @req SWS_Dlt_00464 */ /* @req SWS_Dlt_00466 */ /* @req SWS_Dlt_00482 */ /* @req SWS_Dlt_00005 */ /* @req SWS_Dlt_00007 */ /* @req SWS_Dlt_00009 */ /* @req SWS_Dlt_00010 */ /* @req SWS_Dlt_00011 */ /* @req SWS_Dlt_00014 */ /* @req SWS_Dlt_00474 */ /* @req SWS_Dlt_00475 */ /* @req SWS_Dlt_00377 */ /* @req SWS_Dlt_00477 */ /* @req SWS_Dlt_00478 */ /* @req SWS_Dlt_00479 */ /* @req SWS_Dlt_00430 */ /* @req SWS_Dlt_00431 */ /* @req SWS_Dlt_00376 */ /* @req SWS_Dlt_00480 */ /* @req SWS_Dlt_00031 */ /* @req SWS_Dlt_00040 */ /* @req SWS_Dlt_00042 */ /* @req SWS_Dlt_00043 */ /* @req SWS_Dlt_00044 */ /* @req SWS_Dlt_00052 */ /* @req SWS_Dlt_00341 */ /* @req SWS_Dlt_00342 */ /* @req SWS_Dlt_00053 */ /* @req SWS_Dlt_00461 */ /* @req SWS_Dlt_00462 */ /* @req SWS_Dlt_00463 */ /* @req SWS_Dlt_00450 */ /* 7.6.7 Processing of control messages */ /* @req SWS_Dlt_00079 */ /* @req SWS_Dlt_00351 */ /* @req SWS_Dlt_00456 */ /* 7.6.8 Message Handling */ /* @req SWS_Dlt_00080 */ /* @req SWS_Dlt_00298 */ /* @req SWS_Dlt_00081 */ /* 7.6.8.1 Filling the Header */ /* @req SWS_Dlt_00082 */ /* @req SWS_Dlt_00083 */ /* @req SWS_Dlt_00084 */ /* @req SWS_Dlt_00085 */ /* 7.6.8.2 Filling the extended Header */ /* @req SWS_Dlt_00086 */ /* @req SWS_Dlt_00087 */ /* @req SWS_Dlt_00088 */ /* 7.6.8.3 Switch between Verbose and Non Verbose Mode */ /* @req SWS_Dlt_00089 */ /* @req SWS_Dlt_00090 */ /* @req SWS_Dlt_00300 */ /* 7.7.1&2 Message format */ /* @req SWS_Dlt_00301 */ /* @req SWS_Dlt_00467 */ /* @req SWS_Dlt_00091 */ /* 7.7.3 Standard header */ /* @req SWS_Dlt_00302 */ /* @req SWS_Dlt_00458 */ /* @req SWS_Dlt_00094 */ /* @req SWS_Dlt_00406 */ /* @req SWS_Dlt_00095 */ /* @req SWS_Dlt_00303 */ /* @req SWS_Dlt_00096 */ /* @req SWS_Dlt_00098 */ /* @req SWS_Dlt_00305 */ /* @req SWS_Dlt_00407 */ /* @req SWS_Dlt_00101 */ /* @req SWS_Dlt_00306 */ /* @req SWS_Dlt_00408 */ /* @req SWS_Dlt_00102 */ /* @req SWS_Dlt_00307 */ /* @req SWS_Dlt_00318 */ /* @req SWS_Dlt_00103 */ /* @req SWS_Dlt_00104 */ /* @req SWS_Dlt_00299 */ /* @req SWS_Dlt_00319 */ /* @req SWS_Dlt_00105 */ /* @req SWS_Dlt_00106 */ /* @req SWS_Dlt_00320 */ /* @req SWS_Dlt_00107 */ /* @req SWS_Dlt_00321 */ /* @req SWS_Dlt_00108 */ /* @req SWS_Dlt_00308 */ /* @req SWS_Dlt_00322 */ /* @req SWS_Dlt_00323 */ /* @req SWS_Dlt_00112 */ /* @req SWS_Dlt_00309 */ /* @req SWS_Dlt_00113 */ /* 7.7.4 Dlt Extended Header */ /* @req SWS_Dlt_00116 */ /* @req SWS_Dlt_00117 */ /* @req SWS_Dlt_00457 */ /* @req SWS_Dlt_00118 */ /* @req SWS_Dlt_00119 */ /* @req SWS_Dlt_00310 */ /* @req SWS_Dlt_00324 */ /* @req SWS_Dlt_00120 */ /* @req SWS_Dlt_00325 */ /* @req SWS_Dlt_00121 */ /* @req SWS_Dlt_00122 */ /* @req SWS_Dlt_00123 */ /* @req SWS_Dlt_00124 */ /* @req SWS_Dlt_00125 */ /* @req SWS_Dlt_00326 */ /* @req SWS_Dlt_00126 */ /* @req SWS_Dlt_00127 */ /* @req SWS_Dlt_00312 */ /* @req SWS_Dlt_00128 */ /* @req SWS_Dlt_00313 */ /* @req SWS_Dlt_00314 */ /* @req SWS_Dlt_00315 */ /* 7.7 Protocol Specification (for transmitting to a external client and saving on the client) */ /* @req SWS_Dlt_00460 */ /* @req SWS_Dlt_00129 */ /* @req SWS_Dlt_00329 */ /* @req SWS_Dlt_00352 */ /* @req SWS_Dlt_00353 */ /* @req SWS_Dlt_00134 */ /* @req SWS_Dlt_00459 */ /* @req SWS_Dlt_00409 */ /* @req SWS_Dlt_00378 */ /* @req SWS_Dlt_00186 */ /* @req SWS_Dlt_00187 */ /* @req SWS_Dlt_00188 */ /* @req SWS_Dlt_00189 */ /* @req SWS_Dlt_00190 */ /* @req SWS_Dlt_00191 */ /* @req SWS_Dlt_00417 */ /* @req SWS_Dlt_00416 */ /* @req SWS_Dlt_00192 */ /* @req SWS_Dlt_00193 */ /* 7.7.7.1 Control messages */ /* @req SWS_Dlt_00380 */ /* @req SWS_Dlt_00205 */ /* @req SWS_Dlt_00206 */ /* @req SWS_Dlt_00393 */ /* @req SWS_Dlt_00447 */ /* @req SWS_Dlt_00468 */ /* 8.2 Service interfaces */ /* @req SWS_Dlt_00495 */ /* @req SWS_Dlt_00499 */ /* 8.3 Type definitions */ /* @req SWS_Dlt_00437 */ /* @req SWS_Dlt_00224 */ /* @req SWS_Dlt_00225 */ /* @req SWS_Dlt_00226 */ /* @req SWS_Dlt_00227 */ /* @req SWS_Dlt_00228 */ /* @req SWS_Dlt_00229 */ /* @req SWS_Dlt_00230 */ /* @req SWS_Dlt_00231 */ /* @req SWS_Dlt_00232 */ /* @req SWS_Dlt_00235 */ /* @req SWS_Dlt_00236 */ /* @req SWS_Dlt_00237 */ /* @req SWS_Dlt_00238 */ /* 8.4 Functions */ /* @req SWS_Dlt_00239 */ /* @req SWS_Dlt_00271 */ /* @req SWS_Dlt_00241 */ /* @req SWS_Dlt_00242 */ /* @req SWS_Dlt_00470 */ /* @req SWS_Dlt_00432 */ /* @req SWS_Dlt_00272 */ /* @req SWS_Dlt_00273 */ /* @req SWS_Dlt_00262 */ /* @req SWS_Dlt_00515 */ /* @req SWS_Dlt_00516 */ /* @req SWS_Dlt_00517 */ /* @req SWS_Dlt_00263 */ /* * Requirements NOT implemented */ /* !req SWS_Dlt_00490 */ /* !req SWS_Dlt_00003 */ /* !req SWS_Dlt_00004 */ /* !req SWS_Dlt_00333 */ /* !req SWS_Dlt_00295 */ /* !req SWS_Dlt_00434 */ /* !req SWS_Dlt_00039 */ /* !req SWS_Dlt_00483 */ /* !req SWS_Dlt_00296 */ /* !req SWS_Dlt_00012 */ /* !req SWS_Dlt_00330 */ /* !req SWS_Dlt_00331 */ /* !req SWS_Dlt_00015 */ /* !req SWS_Dlt_00016 */ /* !req SWS_Dlt_00017 */ /* !req SWS_Dlt_00018 */ /* !req SWS_Dlt_00019 */ /* !req SWS_Dlt_00021 */ /* !req SWS_Dlt_00022 */ /* !req SWS_Dlt_00023 */ /* !req SWS_Dlt_00024 */ /* !req SWS_Dlt_00332 */ /* !req SWS_Dlt_00334 */ /* !req SWS_Dlt_00025 */ /* !req SWS_Dlt_00284 */ /* !req SWS_Dlt_00276 */ /* !req SWS_Dlt_00026 */ /* !req SWS_Dlt_00027 */ /* !req SWS_Dlt_00335 */ /* !req SWS_Dlt_00285 */ /* !req SWS_Dlt_00277 */ /* !req SWS_Dlt_00278 */ /* !req SWS_Dlt_00336 */ /* !req SWS_Dlt_00279 */ /* !req SWS_Dlt_00337 */ /* !req SWS_Dlt_00484 */ /* !req SWS_Dlt_00280 */ /* !req SWS_Dlt_00281 */ /* !req SWS_Dlt_00283 */ /* !req SWS_Dlt_00339 */ /* !req SWS_Dlt_00435 */ /* !req SWS_Dlt_00469 */ /* !req SWS_Dlt_00037 */ /* !req SWS_Dlt_00340 */ /* !req SWS_Dlt_00434 */ /* !req SWS_Dlt_00039 */ /* !req SWS_Dlt_00465 */ /* !req SWS_Dlt_00290 */ /* !req SWS_Dlt_00046 */ /* !req SWS_Dlt_00048 */ /* !req SWS_Dlt_00049 */ /* !req SWS_Dlt_00050 */ /* !req SWS_Dlt_00051 */ /* !req SWS_Dlt_00054 */ /* !req SWS_Dlt_00055 */ /* !req SWS_Dlt_00056 */ /* !req SWS_Dlt_00344 */ /* !req SWS_Dlt_00057 */ /* !req SWS_Dlt_00058 */ /* !req SWS_Dlt_00059 */ /* !req SWS_Dlt_00289 */ /* !req SWS_Dlt_00060 */ /* !req SWS_Dlt_00345 */ /* !req SWS_Dlt_00426 */ /* !req SWS_Dlt_00471 */ /* !req SWS_Dlt_00472 */ /* !req SWS_Dlt_00061 */ /* !req SWS_Dlt_00064 */ /* !req SWS_Dlt_00065 */ /* !req SWS_Dlt_00066 */ /* !req SWS_Dlt_00067 */ /* !req SWS_Dlt_00068 */ /* !req SWS_Dlt_00347 */ /* !req SWS_Dlt_00069 */ /* !req SWS_Dlt_00070 */ /* !req SWS_Dlt_00071 */ /* !req SWS_Dlt_00072 */ /* !req SWS_Dlt_00493 */ /* 7.6.6 Storing Configuration in NVRAM */ /* !req SWS_Dlt_00287 */ /* !req SWS_Dlt_00073 */ /* !req SWS_Dlt_00074 */ /* !req SWS_Dlt_00076 */ /* !req SWS_Dlt_00077 */ /* !req SWS_Dlt_00451 */ /* !req SWS_Dlt_00078 */ /* !req SWS_Dlt_00452 */ /* !req SWS_Dlt_00453 */ /* !req SWS_Dlt_00491 */ /* !req SWS_Dlt_00288 */ /* !req SWS_Dlt_00348 */ /* 7.7.3.1.2 Most Significant Byte First (MSBF) */ /* !req SWS_Dlt_00097 */ /* !req SWS_Dlt_00304 */ /* gpt timer */ /* !req SWS_Dlt_00481 */ /* 7.7.5.1.2 Assembly of Non-Static Data(xml and fibex related non driver specific) */ /* !req SWS_Dlt_00338 */ /* !req SWS_Dlt_00402 */ /* !req SWS_Dlt_00403 */ /* !req SWS_Dlt_00418 */ /* !req SWS_Dlt_00396 */ /* !req SWS_Dlt_00397 */ /* !req SWS_Dlt_00398 */ /* !req SWS_Dlt_00399 */ /* !req SWS_Dlt_00400 */ /* !req SWS_Dlt_00401 */ /* 7.7.5.2.2 Type info(VERBOSE MODE not supported */ /* !req SWS_Dlt_00421 */ /* !req SWS_Dlt_00135 */ /* !req SWS_Dlt_00354 */ /* !req SWS_Dlt_00410 */ /* !req SWS_Dlt_00411 */ /* !req SWS_Dlt_00389 */ /* !req SWS_Dlt_00169 */ /* !req SWS_Dlt_00182 */ /* !req SWS_Dlt_00366 */ /* !req SWS_Dlt_00182 */ /* !req SWS_Dlt_00366 */ /* !req SWS_Dlt_00183 */ /* !req SWS_Dlt_00367 */ /* !req SWS_Dlt_00422 */ /* !req SWS_Dlt_00423 */ /* !req SWS_Dlt_00139 */ /* !req SWS_Dlt_00355 */ /* !req SWS_Dlt_00369 */ /* !req SWS_Dlt_00385 */ /* !req SWS_Dlt_00386 */ /* !req SWS_Dlt_00356 */ /* !req SWS_Dlt_00357 */ /* !req SWS_Dlt_00412 */ /* !req SWS_Dlt_00388 */ /* !req SWS_Dlt_00387 */ /* !req SWS_Dlt_00358 */ /* !req SWS_Dlt_00370 */ /* !req SWS_Dlt_00390 */ /* !req SWS_Dlt_00145 */ /* !req SWS_Dlt_00362 */ /* !req SWS_Dlt_00363 */ /* !req SWS_Dlt_00371 */ /* !req SWS_Dlt_00420 */ /* !req SWS_Dlt_00155 */ /* !req SWS_Dlt_00392 */ /* !req SWS_Dlt_00156 */ /* !req SWS_Dlt_00157 */ /* !req SWS_Dlt_00373 */ /* !req SWS_Dlt_00147 */ /* !req SWS_Dlt_00148 */ /* !req SWS_Dlt_00149 */ /* !req SWS_Dlt_00150 */ /* !req SWS_Dlt_00152 */ /* !req SWS_Dlt_00153 */ /* !req SWS_Dlt_00372 */ /* !req SWS_Dlt_00175 */ /* !req SWS_Dlt_00176 */ /* !req SWS_Dlt_00177 */ /* !req SWS_Dlt_00414 */ /* !req SWS_Dlt_00364 */ /* !req SWS_Dlt_00160 */ /* !req SWS_Dlt_00161 */ /* !req SWS_Dlt_00374 */ /* !req SWS_Dlt_00170 */ /* !req SWS_Dlt_00172 */ /* !req SWS_Dlt_00173 */ /* !req SWS_Dlt_00171 */ /* !req SWS_Dlt_00375 */ /* !req SWS_Dlt_00424 */ /* !req SWS_Dlt_00425 */ /* !req SWS_Dlt_00405 */ /* !req SWS_Dlt_00427 */ /* !req SWS_Dlt_00404 */ /* !req SWS_Dlt_00292 */ /* !req SWS_Dlt_00415 */ /* 7.7.7.1 Control messages */ /* !req SWS_Dlt_00194 */ /* !req SWS_Dlt_00196 */ /* !req SWS_Dlt_00383 */ /* !req SWS_Dlt_00381 */ /* !req SWS_Dlt_00382 */ /* !req SWS_Dlt_00197 */ /* !req SWS_Dlt_00198 */ /* !req SWS_Dlt_00494 */ /* !req SWS_Dlt_00199 */ /* !req SWS_Dlt_00200 */ /* !req SWS_Dlt_00201 */ /* !req SWS_Dlt_00501 */ /* !req SWS_Dlt_00502 */ /* !req SWS_Dlt_00202 */ /* !req SWS_Dlt_00503 */ /* !req SWS_Dlt_00489 */ /* !req SWS_Dlt_00203 */ /* !req SWS_Dlt_00204 */ /* !req SWS_Dlt_00504 */ /* !req SWS_Dlt_00505 */ /* !req SWS_Dlt_00207 */ /* !req SWS_Dlt_00208 */ /* !req SWS_Dlt_00209 */ /* !req SWS_Dlt_00210 */ /* !req SWS_Dlt_00506 */ /* !req SWS_Dlt_00211 */ /* !req SWS_Dlt_00212 */ /* !req SWS_Dlt_00507 */ /* !req SWS_Dlt_00213 */ /* !req SWS_Dlt_00214 */ /* !req SWS_Dlt_00508 */ /* !req SWS_Dlt_00215 */ /* !req SWS_Dlt_00216 */ /* !req SWS_Dlt_00509 */ /* !req SWS_Dlt_00217 */ /* !req SWS_Dlt_00218 */ /* !req SWS_Dlt_00219 */ /* !req SWS_Dlt_00220 */ /* !req SWS_Dlt_00487 */ /* 7.7.7.2 Timing messages */ /* !req SWS_Dlt_00221 */ /* !req SWS_Dlt_00222 */ /* !req SWS_Dlt_00394 */ /* !req SWS_Dlt_00395 */ /* !req SWS_Dlt_00492 */ /* !req SWS_Dlt_00492 */ /* 8.2 Service Interfaces */ /* !req SWS_Dlt_00498 */ /* !req SWS_Dlt_00496 */ /* !req SWS_Dlt_00497 */ /* 8.3 Types */ /* !req SWS_Dlt_00233*/ /* 8.4 Function interfaces */ /* !req SWS_Dlt_00243 */ /* !req SWS_Dlt_00244 */ /* !req SWS_Dlt_00245 */ /* 8.4.4 Provided interfaces for Dcm */ /* !req SWS_Dlt_00488 */ /* !req SWS_Dlt_00247 */ /* !req SWS_Dlt_00248 */ /* !req SWS_Dlt_00249 */ /* !req SWS_Dlt_00428 */ /* 8.5.1 Expected Interfaces from SW-Cs */ /* !req SWS_Dlt_00252 */ /* !req SWS_Dlt_00253 */ /* !req SWS_Dlt_00254 */ /* !req SWS_Dlt_00255 */ /* !req SWS_Dlt_00256 */ /* !req SWS_Dlt_00257 */ /* !req SWS_Dlt_00258 */ /* !req SWS_Dlt_00259 */ /* !req SWS_Dlt_00260 */ /* !req SWS_Dlt_00261 */ /* 8.6.2 Expected Interfaces from Dlt communication module */ /* !req SWS_Dlt_00265 */ /* !req SWS_Dlt_00264 */ /* !req SWS_Dlt_00485 */ /* !req SWS_Dlt_00250 */ /* !req SWS_Dlt_00251 */ /* 8.6.3 Expected Interfaces from Gpt */ /* !req SWS_Dlt_00513 */ /* !req SWS_Dlt_00514 */ /* @req SWS_Dlt_00445 */ /* @req SWS_Dlt_00440 */ /* @req SWS_Dlt_00441 */ /* @req SWS_Dlt_00442 */ /* @req SWS_Dlt_00443 */ /* @req SWS_Dlt_00511 */ /* @req SWS_Dlt_00500 */ /*lint -emacro(904,VALIDATE_NO_RV,VALIDATE_RV) *//*904 PC-Lint exception to MISRA 14.7 (validate DET macros).*/ #include "Platform_Types.h" #include "Dlt.h" #include "MemMap.h" #include "string.h" #include "SchM_Dlt.h" //#if defined(USE_NVM) //#include "NvM.h" //#endif #if defined(USE_DEM) #include "Dem.h" #endif #if ( DLT_DEV_ERROR_DETECT == STD_ON ) #include "Det.h" #endif #if (DLT_HEADER_USE_TIMESTAMP==STD_ON) #include "timer.h" #endif #include "cirq_buffer.h" /* @req SWS_Dlt_00444 */ /* @req SWS_Dlt_00439 */ #if ( DLT_DEV_ERROR_DETECT == STD_ON ) #define VALIDATE_NO_RV(_exp,_api,_err ) \ if( !(_exp) ) { \ (void)Det_ReportError(DLT_MODULE_ID,0,_api,_err); \ return; \ } #define VALIDATE_RV(_exp,_api,_err, _rv ) \ if( !(_exp) ) { \ (void)Det_ReportError(DLT_MODULE_ID,0,_api,_err); \ return _rv; \ } #else #define VALIDATE(_exp,_api,_err ) #define VALIDATE_RV(_exp,_api,_err,_rv ) #endif /* @req SWS_Dlt_00229 */ #define DLT_VERBOSE_FLAG 0x08u /* @req SWS_Dlt_00482 */ /* ----------------------------[Version check]------------------------------*/ #if !(((DLT_SW_MAJOR_VERSION == 1) && (DLT_SW_MINOR_VERSION == 0)) ) #error Dlt: Expected BSW module version to be 1.0.* #endif #if !(((DLT_AR_MAJOR_VERSION == 4) && (DLT_AR_MINOR_VERSION == 0)) ) #error Dlt: Expected AUTOSAR version to be 4.0.* #endif #define DLT_NOF_MESSAGES (DLT_MESSAGE_BUFFERSIZE / DLT_MAX_MESSAGE_LENGTH) typedef enum { DLT_NOT_INITIALIZED, DLT_INITIALIZED, DLT_CONNECTED, } Dlt_InternalStateType; /* Static module specific variables */ static CirqBufferType cirqBuf; static const Dlt_ConfigType *ptrConfig; /* Variable used to hold the current message filtering status */ static uint8 filterMessages = 1u;/* Default on */ static uint8 defaultLogLevel = DLT_DEFAULT_MAX_LOG_LEVEL; /*lint -esym(9003,messageCounter) Misra violation. Used by tests and cannot be defined at block scope */ #if (DLT_UNIT_TEST == STD_ON) uint8 messageCounter = 0u; #else static uint8 messageCounter = 0u; #endif static Dlt_InternalStateType DltState = DLT_NOT_INITIALIZED; boolean Dlt_ArcIsDltConnected(void) { return (DltState == DLT_CONNECTED); } /** * Initializes the module * @param ConfigPtr - a pointer to the configuration */ void Dlt_Init(const Dlt_ConfigType *ConfigPtr) { /* @req SWS_Dlt_00239 */ VALIDATE_NO_RV((NULL != ConfigPtr), DLT_INIT_SERVICE_ID, DLT_E_PARAM_POINTER); static uint8 Dlt_SendRingBuffer[DLT_NOF_MESSAGES][DLT_MAX_MESSAGE_LENGTH]; ptrConfig = ConfigPtr; #if (DLT_HEADER_USE_TIMESTAMP==STD_ON) Timer_Init(); #endif /* init circular buffer */ CirqBuff_Init(&cirqBuf, Dlt_SendRingBuffer, DLT_NOF_MESSAGES, DLT_MAX_MESSAGE_LENGTH); messageCounter = 0u; defaultLogLevel = DLT_DEFAULT_MAX_LOG_LEVEL; filterMessages = 1u; DltCom_Init(); DltState = DLT_INITIALIZED; } /** * Maybe change endianess for an uint32 * @param value - parameter to change endianess on */ #if 0 static uint32 CheckAndAdaptEndianess32(uint32 value) { uint32 result; #if (CPU_BYTE_ORDER != HIGH_BYTE_FIRST) result = (((value & 0x000000FFu) << 24u) | ((value & 0x0000FF00u) << 8u ) | ((value & 0x00FF0000u) >> 8u ) | ((value & 0xFF000000u) >> 24u) ); #else result = value; #endif return result; } /** * Change endianess for an uint16 * @param value - parameter to change endianess on */ static uint16 CheckAndAdaptEndianess16(uint16 value) { uint16 result; #if (CPU_BYTE_ORDER != HIGH_BYTE_FIRST) result = ( ((value & 0x00FFu) << 8u) | ((value & 0xFF00u) >> 8u) ); #else result = value; #endif return result; } #endif /** * Confirmation on sent messages * @param DltTxPduId - Pdu Id * @param Result - Result of the transmit */ void Dlt_ComTxConfirmation(PduIdType DltTxPduId, Std_ReturnType Result) { /* @req SWS_Dlt_00273 */ (void) DltTxPduId; (void) Result; /* dont care about result, just free buffer */ SchM_Enter_Dlt_EA_0(); if (NULL != CirqBuff_PopLock(&cirqBuf)) { CirqBuff_PopRelease(&cirqBuf); } SchM_Exit_Dlt_EA_0(); } /** * Create message and send * @param payload - a pointer to the payload buffer * @param len - length of the payload * @param session_id - session id */ static Dlt_ReturnType Dlt_CreateLogMessageAndSend(const uint8 *payload, uint16 len, Dlt_SessionIDType session_id, const Dlt_ExtendedHeaderType *extHeader) { /* @req SWS_Dlt_00301 */ /* @req SWS_Dlt_00302 */ /* @req SWS_Dlt_00458 */ uint16 totlen = 4; /* Add place for mandatory parameters directly */ uint8 *sendbuffer; Dlt_ReturnType result = DLT_E_OK; /* Since this function can be called by different context we need to protect the ring buffer * from being PushLock/PushRelease'd in the wrong order */ SchM_Enter_Dlt_EA_0(); sendbuffer = CirqBuff_PushLock(&cirqBuf); if (NULL == sendbuffer) { /* No buffer available, remove oldest message */ /* @req SWS_Dlt_00297 */ if (NULL != CirqBuff_PopLock(&cirqBuf)) { CirqBuff_PopRelease(&cirqBuf); /* Try push again */ sendbuffer = CirqBuff_PushLock(&cirqBuf); if (NULL == sendbuffer) { /* Buffer is corrupted */ SchM_Exit_Dlt_EA_0(); /*lint -e{904} Return statement is necessary to avoid multiple if loops(limit cyclomatic complexity) and hence increase readability */ return DLT_E_IF_NOT_AVAILABLE; } } else { /* Buffer is corrupted */ SchM_Exit_Dlt_EA_0(); /*lint -e{904} Return statement is necessary to avoid multiple if loops(limit cyclomatic complexity) and hence increase readability */ return DLT_E_IF_NOT_AVAILABLE; } } /* Insert header */ /* @req SWS_Dlt_00377 */ /* @req SWS_Dlt_00318 *//* @req SWS_Dlt_00103 *//* @req SWS_Dlt_00104 *//* @req SWS_Dlt_00299 */ sendbuffer[0] = DLT_VERS; /*header type *//* @req SWS_Dlt_00094 */ #if (DLT_HEADER_USE_MSBF==STD_ON) sendbuffer[0] |= DLT_MSBF; /* header type *//* @req SWS_Dlt_00094 *//* @req SWS_Dlt_00458 */ #endif sendbuffer[1] = messageCounter; /* mcnt */ #if (DLT_HEADER_USE_ECU_ID==STD_ON) sendbuffer[0] |= DLT_WEID; /*lint --e{9033} inhibit lint warning to avoid false Misra violation */ sendbuffer[totlen] = (uint8)ptrConfig->EcuId[0]; sendbuffer[totlen+1] = (uint8)ptrConfig->EcuId[1]; sendbuffer[totlen+2] = (uint8)ptrConfig->EcuId[2]; sendbuffer[totlen+3] = (uint8)ptrConfig->EcuId[3]; totlen += 4; #endif #if (DLT_HEADER_USE_SESSION_ID==STD_ON) sendbuffer[0] |= DLT_WSID; sendbuffer[totlen] = (uint8)(session_id >> 24u); sendbuffer[totlen+1] = (uint8)(session_id >> 16u); sendbuffer[totlen+2] = (uint8)(session_id >> 8u); sendbuffer[totlen+3] = (uint8)session_id; totlen += 4; #endif #if (DLT_HEADER_USE_TIMESTAMP==STD_ON) sendbuffer[0] |= DLT_WTMS; /* use timer as solution */ uint32 timeStamp = Timer_GetTicks(); sendbuffer[totlen] = (uint8)(timeStamp >> 24u); sendbuffer[totlen+1] = (uint8)(timeStamp >> 16u); sendbuffer[totlen+2] = (uint8)(timeStamp >> 8u); sendbuffer[totlen+3] = (uint8)timeStamp; totlen += 4; #endif #if (DLT_HEADER_USE_EXTENDED_HEADER==STD_ON) sendbuffer[0] |= DLT_UEH; sendbuffer[totlen] = extHeader->MSIN; sendbuffer[totlen+1] = extHeader->NOAR; sendbuffer[totlen+2] = extHeader->APID[0]; sendbuffer[totlen+3] = extHeader->APID[1]; sendbuffer[totlen+4] = extHeader->APID[2]; sendbuffer[totlen+5] = extHeader->APID[3]; sendbuffer[totlen+6] = extHeader->CTID[0]; sendbuffer[totlen+7] = extHeader->CTID[1]; sendbuffer[totlen+8] = extHeader->CTID[2]; sendbuffer[totlen+9] = extHeader->CTID[3]; totlen += 10; #endif //#if (DLT_HEADER_USE_MSBF==STD_ON) /* standard payload just copy to buffer and send */ /* @req SWS_Dlt_00080 */ if (len > 0) { memcpy(&sendbuffer[totlen], payload, len); totlen += len; } sendbuffer[2] = (uint8) (totlen >> 8u); /* len *//* @req SWS_Dlt_00320 *//* SWS_Dlt_00107 */ sendbuffer[3] = (uint8) (totlen); /* len *//* @req SWS_Dlt_00320 *//* SWS_Dlt_00107 */ /* Message Counter */ /* @req SWS_Dlt_00319 *//* @req SWS_Dlt_00105*//* @req SWS_Dlt_00106*/ messageCounter++; CirqBuff_PushRelease(&cirqBuf); SchM_Exit_Dlt_EA_0(); /* Send using DltCom */ Std_ReturnType res; PduInfoType pduInfo; pduInfo.SduDataPtr = sendbuffer; pduInfo.SduLength = totlen; res = DltCom_Transmit(messageCounter/*pdu id not really needed, use mcnt for id*/, &pduInfo); if (res != E_OK) { result = DLT_E_IF_NOT_AVAILABLE; } return result; } /** * The service represents the interface to be used by basic software modules or by * software component to send log messages. * @param session_id * @param log_info * @param log_data * @param log_data_length */ Dlt_ReturnType Dlt_SendLogMessage(Dlt_SessionIDType session_id, const Dlt_MessageLogInfoType* log_info, const uint8* log_data, uint16 log_data_length) { boolean status; status = TRUE; /* @req SWS_Dlt_00241 */ /* @req SWS_Dlt_00107 */ /* @req SWS_Dlt_00110 */ Dlt_ReturnType ret = DLT_E_OK; Dlt_ExtendedHeaderType extHeader; VALIDATE_RV( (NULL != log_data), DLT_SENDLOGMESSAGE_SERVICE_ID, DLT_E_PARAM_POINTER, DLT_E_ERROR_UNKNOWN); #if (DLT_IMPLEMENT_FILTER_MESSAGES == STD_ON) if((defaultLogLevel == 0) || (log_info->log_level > defaultLogLevel) || (filterMessages == 0u)) { status = FALSE; ret = DLT_E_OK; } #endif if (status == TRUE) { extHeader.MSIN = ((uint8) DLT_TYPE_LOG << 1u) | (uint8) (log_info->log_level << 4u); if (0u != (log_info->options & DLT_VERBOSE_FLAG)) { extHeader.NOAR = (uint8) log_info->arg_count; extHeader.MSIN |= 0x01u; // set VERB flag } else { extHeader.NOAR = 0u; } extHeader.APID[0] = log_info->app_id[0]; extHeader.APID[1] = log_info->app_id[1]; extHeader.APID[2] = log_info->app_id[2]; extHeader.APID[3] = log_info->app_id[3]; extHeader.CTID[0] = log_info->context_id[0]; extHeader.CTID[1] = log_info->context_id[1]; extHeader.CTID[2] = log_info->context_id[2]; extHeader.CTID[3] = log_info->context_id[3]; /* @req SWS_Dlt_00014 *//* @req SWS_Dlt_00096 */ if ((0u != (log_info->options & DLT_VERBOSE_FLAG)) && (0u != (log_info->options & DLT_UEH))) { #if ((DLT_USE_VERBOSE_MODE == STD_ON) && (DLT_HEADER_USE_EXTENDED_HEADER == STD_ON)) /* verbose handling */ if ((log_data_length <= DLT_MAX_MESSAGE_LENGTH)) { ret = Dlt_CreateLogMessageAndSend(log_data, log_data_length, session_id, &extHeader); } else { /* @req SWS_Dlt_00081 */ ret = DLT_E_MSG_TOO_LARGE; } #else /* @req SWS_Dlt_00090 */ ret = DLT_E_NOT_IN_VERBOSE_MOD; #endif } else { /* @req SWS_Dlt_00460 *//* @req SWS_Dlt_00329*//* Non verbose handling */ /* @req SWS_Dlt_00031 *//* Message IDs used for Dem (0x00000001) and Det (0x00000002)are reserved and not usable for SW-Cs.. */ /*lint --e{9007} inhibit lint warning to avoid false Misra violation */ if ((0 != memcmp(log_info->app_id, "DEM", 3)) && (0 != memcmp(log_info->app_id, "DET", 3))) { /*lint --e{9033} inhibit lint warning to avoid false Misra violation */ uint32 messageId = ((uint32) (log_data[0]) << 24u) | ((uint32) (log_data[1]) << 16u) | ((uint32) (log_data[2]) << 8u) | (uint32) (log_data[3]); VALIDATE_RV( (messageId != DLT_DEM_MESSAGE_ID) && (messageId != DLT_DET_MESSAGE_ID), DLT_SENDLOGMESSAGE_SERVICE_ID, DLT_E_PARAM_POINTER, DLT_E_ERROR_UNKNOWN); } if ((log_data_length <= DLT_MAX_MESSAGE_LENGTH)) { ret = Dlt_CreateLogMessageAndSend(log_data, log_data_length, session_id, &extHeader); } else { /* @req SWS_Dlt_00081 */ ret = DLT_E_MSG_TOO_LARGE; } } } else { /* return DLT_E_OK */ } return ret; } /** * The service represents the interface to be used by basic software modules or by * software component to send trace messages. * @param session_id * @param trace_info * @param trace_data * @param trace_data_length */ Dlt_ReturnType Dlt_SendTraceMessage(Dlt_SessionIDType session_id, const Dlt_MessageTraceInfoType* trace_info, const uint8* trace_data, uint16 trace_data_length) { /* @req !SWS_Dlt_00243 */ /* @req !SWS_Dlt_00333 */ /* @req !SWS_Dlt_00011 */ /* Not implemented yet */ (void) session_id; (void) trace_info; /*lint !e920 Cast to void allowed here since not used */ (void) trace_data; /*lint !e920 Cast to void allowed here since not used */ (void) trace_data_length; return DLT_E_OK; } #if defined(USE_DEM) /** * This service is provided by the Dem in order to call Dlt upon status changes. * @param EventId * @param EventStatusByteOld * @param EventStatusByteNew */ void Dlt_DemTriggerOnEventStatus(Dem_EventIdType EventId, Dem_EventStatusExtendedType EventStatusByteOld, Dem_EventStatusExtendedType EventStatusByteNew) { uint16 totlen = 0; uint32 eventId_u32 = (uint32)EventId; uint32 messageId = DLT_DEM_MESSAGE_ID; static uint8 Dlt_TempBuffer[DLT_MAX_MESSAGE_LENGTH]; /* ApplicationID = “DEM” * ContextID = “STD0” * MessageID = 0x00000001 */ /* @req SWS_Dlt_00377 */ const Dlt_MessageLogInfoType log_info = { .app_id = {'D','E','M',0u}, .context_id = {'S','T','D',0u}, .arg_count = 2u, .options = 0u, .log_level = DLT_LOG_WARN, }; /* @req SWS_Dlt_00470 */ /* @req SWS_Dlt_00475 */ if((EventStatusByteOld != EventStatusByteNew) && (EventId != 0)) { /* @req SWS_Dlt_00476*/ uint32 dtc = 0; uint8 bufsize; /* We need to protect the tempbuffer from being overwritten */ SchM_Enter_Dlt_EA_0(); Dlt_TempBuffer[totlen] = (uint8)(messageId >> 24u); Dlt_TempBuffer[totlen+1] = (uint8)(messageId >> 16u); Dlt_TempBuffer[totlen+2] = (uint8)(messageId >> 8u); Dlt_TempBuffer[totlen+3] = (uint8)(messageId); totlen += 4; Dlt_TempBuffer[totlen] = (uint8)(eventId_u32 >> 24u); Dlt_TempBuffer[totlen+1] = (uint8)(eventId_u32 >> 16u); Dlt_TempBuffer[totlen+2] = (uint8)(eventId_u32 >> 8u); Dlt_TempBuffer[totlen+3] = (uint8)(eventId_u32); totlen += 4; /* @req SWS_Dlt_00477 */ (void)Dem_GetDTCOfEvent(EventId, DEM_DTC_FORMAT_UDS, &dtc); Dlt_TempBuffer[totlen] = (uint8)(dtc >> 24u); Dlt_TempBuffer[totlen+1] = (uint8)(dtc >> 16u); Dlt_TempBuffer[totlen+2] = (uint8)(dtc >> 8u); Dlt_TempBuffer[totlen+3] = (uint8)(dtc); totlen += 4; /* @req SWS_Dlt_00478 */ bufsize = 255u; if(E_OK == Dem_DltGetAllExtendedDataRecords(EventId, &Dlt_TempBuffer[totlen], &bufsize)) { totlen += bufsize; } else { /* Operation failed */ } /* @req SWS_Dlt_00479 */ bufsize = 255; if(E_OK == Dem_DltGetMostRecentFreezeFrameRecordData(EventId, &Dlt_TempBuffer[totlen], &bufsize)) { totlen += bufsize; } else { /* Operation failed */ } (void)Dlt_SendLogMessage(messageId, &log_info, Dlt_TempBuffer, totlen); SchM_Exit_Dlt_EA_0(); } } #endif /** * Service to forward error reports from Det to Dlt. * @param ModuleId * @param InstanceId * @param ApiId * @param ErrorId */ void Dlt_DetForwardErrorTrace(uint16 ModuleId, uint8 InstanceId, uint8 ApiId, uint8 ErrorId) { /* @req SWS_Dlt_00432 */ /* @req SWS_Dlt_00430 */ /* @req SWS_Dlt_00480 */ /* @req SWS_Dlt_00376 */ /* The ApplicationID, ContextID and MessageID of the send log message shall have the following values: ApplicationID = “DET” ContextID = “STD” MessageID = 0x00000002 */ const Dlt_MessageLogInfoType log_info = { .app_id = { 'D', 'E', 'T', 0u }, .context_id = { 'S', 'T', 'D', 0u }, .arg_count = 1u, .options = 0u, .log_level = DLT_LOG_ERROR, }; uint32 messageId = DLT_DET_MESSAGE_ID; uint8 payload[9]; uint16 totlen = 0; payload[totlen] = (uint8) (messageId >> 24u); payload[totlen + 1] = (uint8) (messageId >> 16u); payload[totlen + 2] = (uint8) (messageId >> 8u); payload[totlen + 3] = (uint8) (messageId); totlen += 4u; payload[totlen] = (uint8) (ModuleId >> 8u); payload[totlen + 1] = (uint8) ModuleId; payload[totlen + 2] = (uint8) InstanceId; payload[totlen + 3] = (uint8) ApiId; payload[totlen + 4] = (uint8) ErrorId; totlen += 5u; /* SWS_Dlt_00431 */ (void) Dlt_SendLogMessage(messageId, &log_info, payload, totlen); } /** * The service has to be called when a software module wants to use services * offered by DLT software component for a specific context. If a context id is being * registered for an already registered application id then app_description can be * NULL and len_app_description zero. * @param session_id * @param app_id * @param context_id * @param app_description * @param len_app_description * @param context_description * @param len_context_description */ Dlt_ReturnType Dlt_RegisterContext(Dlt_SessionIDType session_id, Dlt_ApplicationIDType app_id, Dlt_ContextIDType context_id, const uint8* app_description, uint8 len_app_description, const uint8* context_description, uint8 len_context_description) { /* !req SWS_Dlt_00245 */ /* Not implemented yet */ (void) session_id; (void) app_id;/*lint !e920 Cast to void allowed here since not used */ (void) context_id;/*lint !e920 Cast to void allowed here since not used */ (void) app_description;/*lint !e920 Cast to void allowed here since not used */ (void) len_app_description; (void) context_description;/*lint !e920 Cast to void allowed here since not used */ (void) len_context_description; return DLT_E_OK; } /** * Create control message and send * @param payload - a pointer to the payload buffer * @param len - length of the payload * @param session_id - session id */ static Dlt_ReturnType Dlt_CreateControlMessageAndSend(uint8 *buffer, uint16 len, Dlt_SessionIDType session_id, const Dlt_ExtendedHeaderType *extHeader) { uint16 indx = 4; /* Add place for mandatory parameters directly */ Dlt_ReturnType result = DLT_E_OK; /* Insert header */ /* @req SWS_Dlt_00377 */ /* @req SWS_Dlt_00318 *//* @req SWS_Dlt_00103 *//* @req SWS_Dlt_00104 *//* @req SWS_Dlt_00299 */ buffer[0] = DLT_VERS | DLT_MSBF; /*header type *//* @req SWS_Dlt_00094 */ buffer[1] = 0; /* mcnt not used for control messages */ buffer[2] = (uint8) (len >> 8u); /* len *//* @req SWS_Dlt_00320 *//* SWS_Dlt_00107 */ buffer[3] = (uint8) (len); /* len *//* @req SWS_Dlt_00320 *//* SWS_Dlt_00107 */ #if (DLT_HEADER_USE_ECU_ID==STD_ON) buffer[0] |= DLT_WEID; /*lint --e{9033} inhibit lint warning to avoid false Misra violation */ buffer[indx] = (uint8)ptrConfig->EcuId[0]; buffer[indx+1] = (uint8)ptrConfig->EcuId[1]; buffer[indx+2] = (uint8)ptrConfig->EcuId[2]; buffer[indx+3] = (uint8)ptrConfig->EcuId[3]; indx += 4; #endif #if (DLT_HEADER_USE_SESSION_ID==STD_ON) buffer[0] |= DLT_WSID; buffer[indx] = (uint8)(session_id >> 24u); buffer[indx+1] = (uint8)(session_id >> 16u); buffer[indx+2] = (uint8)(session_id >> 8u); buffer[indx+3] = (uint8)session_id; indx += 4; #endif #if (DLT_HEADER_USE_TIMESTAMP==STD_ON) buffer[0] |= DLT_WTMS; /* use timer as solution */ uint32 timeStamp = Timer_GetTicks(); buffer[indx] = (uint8)(timeStamp >> 24u); buffer[indx+1] = (uint8)(timeStamp >> 16u); buffer[indx+2] = (uint8)(timeStamp >> 8u); buffer[indx+3] = (uint8)timeStamp; indx += 4; #endif #if (DLT_HEADER_USE_EXTENDED_HEADER==STD_ON) buffer[0] |= DLT_UEH; buffer[indx] = extHeader->MSIN; buffer[indx+1] = extHeader->NOAR; buffer[indx+2] = extHeader->APID[0]; buffer[indx+3] = extHeader->APID[1]; buffer[indx+4] = extHeader->APID[2]; buffer[indx+5] = extHeader->APID[3]; buffer[indx+6] = extHeader->CTID[0]; buffer[indx+7] = extHeader->CTID[1]; buffer[indx+8] = extHeader->CTID[2]; buffer[indx+9] = extHeader->CTID[3]; #endif /* Send using DltCom */ Std_ReturnType res; PduInfoType pduInfo; pduInfo.SduDataPtr = buffer; pduInfo.SduLength = len; res = DltCom_Transmit(DLT_ARC_MAGIC_CONTROL_NUMBER, &pduInfo); if (res != E_OK) { result = DLT_E_IF_NOT_AVAILABLE; } return result; } void Dlt_ArcProcessIncomingMessage(const Dlt_StandardHeaderType *header, const uint8 *payload) { uint32 serviceId; uint16 inIndex = 0u; uint16 outIndex = 0u; Dlt_SessionIDType sessionId = 0u; uint8 Dlt_RespBuffer[60]; Dlt_ExtendedHeaderType extHeader; static boolean busy_processing = FALSE; /* Make room for inserting fields in header */ /* Add room for standard header */ outIndex += 4u; /* SWS_Dlt_00188] *//* In the Standard Header the Application ID, Context ID, Session ID and Timestamp may be left blank */ if ((header->HeaderType & DLT_WEID) != 0) { /* Ecu Id */ inIndex += 4u; } if ((header->HeaderType & DLT_WSID) != 0) { /* Session Id */ inIndex += 4u; } if ((header->HeaderType & DLT_WTMS) != 0) { /* Time stamp */ inIndex += 4u; } /* Use Extended Header */ if ((header->HeaderType & DLT_UEH) != 0) { inIndex += 10u; } #if (DLT_HEADER_USE_ECU_ID==STD_ON) outIndex += 4u; #endif #if (DLT_HEADER_USE_SESSION_ID==STD_ON) outIndex += 4u; #endif #if (DLT_HEADER_USE_TIMESTAMP==STD_ON) outIndex += 4u; #endif #if (DLT_HEADER_USE_EXTENDED_HEADER==STD_ON) outIndex += 10u; #endif extHeader.MSIN = ((uint8) DLT_TYPE_CONTROL << 1u) | (2u << 4u); extHeader.NOAR = 0u; extHeader.APID[0] = 0; extHeader.APID[1] = 0; extHeader.APID[2] = 0; extHeader.APID[3] = 0; extHeader.CTID[0] = 0; extHeader.CTID[1] = 0; extHeader.CTID[2] = 0; extHeader.CTID[3] = 0; /*lint --e{9033} inhibit lint warning to avoid false Misra violation */ serviceId = ((uint32) (payload[inIndex]) << 24u) | ((uint32) (payload[inIndex + 1]) << 16u) | ((uint32) (payload[inIndex + 2]) << 8u) | (uint32) (payload[inIndex + 3]); if ((header->HeaderType & DLT_MSBF) == 0) { /* little endian payload */ serviceId = (((serviceId & 0x000000FFu) << 24u) | ((serviceId & 0x0000FF00u) << 8u) | ((serviceId & 0x00FF0000u) >> 8u) | ((serviceId & 0xFF000000u) >> 24u)); } /* @req SWS_Dlt_00191 */ Dlt_RespBuffer[outIndex] = (uint8) (serviceId >> 24u); Dlt_RespBuffer[outIndex + 1] = (uint8) (serviceId >> 16u); Dlt_RespBuffer[outIndex + 2] = (uint8) (serviceId >> 8u); Dlt_RespBuffer[outIndex + 3] = (uint8) (serviceId); outIndex += 4u; inIndex += 4u; if (TRUE == busy_processing) { Dlt_RespBuffer[outIndex] = DLT_RESP_ERROR; outIndex += 1u; (void) Dlt_CreateControlMessageAndSend(Dlt_RespBuffer, outIndex, sessionId, &extHeader); } else { busy_processing = TRUE; switch (serviceId) { /* Get software version */ case 0x00000013u: { uint16 lenver = 7u; Dlt_RespBuffer[outIndex] = DLT_RESP_OK; Dlt_RespBuffer[outIndex + 1] = 0u; Dlt_RespBuffer[outIndex + 2] = 0u; Dlt_RespBuffer[outIndex + 3] = (uint8) (lenver >> 8u); Dlt_RespBuffer[outIndex + 4] = (uint8) (lenver); memcpy(&Dlt_RespBuffer[outIndex + 5], "1234567", lenver); outIndex += 5u + lenver; if (DltState != DLT_CONNECTED) { DltState = DLT_CONNECTED; } } break; /* Set_DefaulLogLevel */ case 0x00000011u: { defaultLogLevel = payload[inIndex]; Dlt_RespBuffer[outIndex] = DLT_RESP_OK; outIndex += 1u; } break; /* Get_DefaulLogLevel */ case 0x00000004u: { Dlt_RespBuffer[outIndex + 1] = defaultLogLevel; Dlt_RespBuffer[outIndex] = DLT_RESP_OK; outIndex += 2u; } break; /* FilterMessages */ case 0x0000000Au: { #if DLT_IMPLEMENT_FILTER_MESSAGES == STD_ON filterMessages = payload[inIndex]; Dlt_RespBuffer[outIndex] = DLT_RESP_OK; #else Dlt_RespBuffer[outIndex] = DLT_RESP_NOT_SUPPORTED; #endif outIndex += 1u; } break; default: Dlt_RespBuffer[outIndex] = DLT_RESP_NOT_SUPPORTED; outIndex += 1u; break; } (void) Dlt_CreateControlMessageAndSend(Dlt_RespBuffer, outIndex, sessionId, &extHeader); busy_processing = FALSE; } }
2301_81045437/classic-platform
diagnostic/Dlt/src/Dlt.c
C
unknown
39,182
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Std_Types.h" #include "Dlt.h" #define CFG_COMLOG_SIZE 500u #if defined(USE_CDDPDUR) #include "CddPduR.h" static uint8 dltcombuffer[CFG_COMLOG_SIZE]; #elif defined(USE_DLTUARTCOM) #include "DltUartCom.h" static uint8 dltUartcom_rx_buffer[DLTUARTCOM_BUFSIZE]; static uint16 bufIdx; static uint16 msgLen; #else /*lint -esym(9003,comlog) Misra violation. This log can be accessed from other modules and is used */ uint8 comlog[CFG_COMLOG_SIZE]; /*lint -esym(9003,comlog_curr) Misra violation. This log can be accessed from other modules and is used */ uint32 comlog_curr = 0; /** * Print a char to the buf * @param c */ static void comlog_chr( uint8 c ) { comlog[comlog_curr] = c; comlog_curr++; if( comlog_curr >= CFG_COMLOG_SIZE ) { comlog_curr = 0; } } #endif void DltCom_Init(void){ #if defined(USE_CDDPDUR) CddPduR_ProvideBuffer(CDDPDUR_PDU_ID_DLT_RX , dltcombuffer, sizeof(dltcombuffer)); #elif defined(USE_DLTUARTCOM) DltUartCom_Init(); #endif } #if defined(USE_CDDPDUR) || defined(USE_DLTUARTCOM) static void DltCom_HandleRx(const uint8 *buffPtr, uint16 length){ Dlt_StandardHeaderType header; #if defined(USE_CDDPDUR) uint16 lenLeft = length; uint16 index = 0; while(lenLeft >= sizeof(Dlt_StandardHeaderType)){ header.HeaderType = buffPtr[index]; header.MessageCounter = buffPtr[index+1]; /*lint --e{9033} inhibit lint warning to avoid false Misra violation */ header.Length = ((uint16)(buffPtr[index+2]) << 8u) | (uint16)buffPtr[index+3]; if(lenLeft >= header.Length){ /* we have at least one Dlt message in length */ Dlt_ArcProcessIncomingMessage(&header, &buffPtr[index + sizeof(Dlt_StandardHeaderType)]); lenLeft -= header.Length; index += header.Length; }else{ /* Invalid message, just sink */ lenLeft = 0; } } #else if (msgLen > DLTUARTCOM_BUFSIZE) { /* can't receive/process message; just read and skip it */ bufIdx++; if (bufIdx == msgLen) { /* end of message */ bufIdx = 0; msgLen = 0; } } dltUartcom_rx_buffer[bufIdx++] = *buffPtr; if (bufIdx == sizeof(Dlt_StandardHeaderType)) { header.HeaderType = dltUartcom_rx_buffer[0U]; header.MessageCounter = dltUartcom_rx_buffer[1U]; header.Length = ((uint16)(dltUartcom_rx_buffer[2U]) << 8U) | (uint16)dltUartcom_rx_buffer[3U]; msgLen = header.Length; } if (bufIdx == msgLen) { /* complete message received -> relay it to DLT */ /* if it is time critical to call Dlt from this ISR callback, we need to establish a cyclic dltcom function */ Dlt_ArcProcessIncomingMessage(&header, &dltUartcom_rx_buffer[sizeof(Dlt_StandardHeaderType)]); bufIdx = 0U; msgLen = 0U; } #endif } Std_ReturnType DltCom_ReceiveIndication(PduIdType DltRxPduId, const PduInfoType* PduInfoPtr){ #if defined(USE_CDDPDUR) Std_ReturnType rv; void *buffPtr; uint16 length = 0; rv = CddPduR_Receive( CDDPDUR_PDU_ID_DLT_RX, &buffPtr, &length); if(rv == E_OK){ // Handling of received DLT frame DltCom_HandleRx((uint8 *)buffPtr, length); } /* Mark that you are done with the data */ CddPduR_UnlockBuffer( CDDPDUR_PDU_ID_DLT_RX ); /* Provide a new buffer */ CddPduR_ProvideBuffer(CDDPDUR_PDU_ID_DLT_RX , dltcombuffer, sizeof(dltcombuffer)); #else // Handling of received DLT frame DltCom_HandleRx((uint8 *)PduInfoPtr->SduDataPtr, PduInfoPtr->SduLength); #endif return E_OK; } #endif Std_ReturnType DltCom_Transmit(PduIdType DltTxPduId, const PduInfoType* PduInfoPtr){ Std_ReturnType res; #if defined(USE_CDDPDUR) const uint8 *data = PduInfoPtr->SduDataPtr; if(TRUE == Dlt_ArcIsDltConnected()){ res = CddPduR_Send(CDDPDUR_PDU_ID_DLT_TX,data,PduInfoPtr->SduLength); /* No TxConfirmation required for Control messages */ if(DLT_ARC_MAGIC_CONTROL_NUMBER != DltTxPduId){ Dlt_ComTxConfirmation(DltTxPduId, res); } }else{ res = E_NOT_OK; } #elif defined(USE_DLTUARTCOM) res = DltUartCom_Transmit(DltTxPduId, PduInfoPtr); Dlt_ComTxConfirmation(DltTxPduId, res); #else const uint8 *data = PduInfoPtr->SduDataPtr; res = E_OK; for (uint32 i = 0; i < PduInfoPtr->SduLength; i++) { comlog_chr(*data); data++; } Dlt_ComTxConfirmation(DltTxPduId, res); #endif return res; }
2301_81045437/classic-platform
diagnostic/Dlt/src/Dlt_Callout_Stubs.c
C
unknown
5,503
# FiM FIM_PB ?= y obj-$(USE_FIM) += FiM.o ifeq (${FIM_PB},y) pb-obj-$(USE_FIM) += FiM_PBCfg.o pb-pc-file-$(USE_FIM) += FiM_Cfg.h else obj-$(USE_FIM) += FiM_PBCfg.o endif vpath-$(USE_FIM) += $(ROOTDIR)/diagnostic/FiM/src inc-$(USE_FIM) += $(ROOTDIR)/diagnostic/FiM/inc
2301_81045437/classic-platform
diagnostic/FiM/FiM.mod.mk
Makefile
unknown
281
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ #ifndef FIM_H_ #define FIM_H_ #define FIM_AR_RELEASE_MAJOR_VERSION 4u #define FIM_AR_RELEASE_MINOR_VERSION 3u #define FIM_AR_RELEASE_REVISION_VERSION 0u #define FIM_MODULE_ID 11u #define FIM_VENDOR_ID 60u #define FIM_SW_MAJOR_VERSION 1u #define FIM_SW_MINOR_VERSION 1u #define FIM_SW_PATCH_VERSION 0u #define FIM_AR_MAJOR_VERSION FIM_AR_RELEASE_MAJOR_VERSION #define FIM_AR_MINOR_VERSION FIM_AR_RELEASE_MINOR_VERSION #define FIM_AR_PATCH_VERSION FIM_AR_RELEASE_REVISION_VERSION #include "Dem.h" #include "FiM_Types.h" #include "FiM_Cfg.h" #if (FIM_DEV_ERROR_DETECT == STD_ON) /* @req SWS_Fim_00076 *//* Error codes reported by this module defined by AUTOSAR */ #define FIM_E_UNINIT 0x01u #define FIM_E_FID_OUT_OF_RANGE 0x02u #define FIM_E_EVENTID_OUT_OF_RANGE 0x03u #define FIM_E_PARAM_POINTER 0x04u #define FIM_E_INIT_FAILED 0x05u /* ARCCORE extra errors */ #define FIM_E_REINIT 0x10u #endif /* API IDs */ #define FIM_INIT_ID 0x00u #define FIM_GETFUNCTIONPERMISSION_ID 0x01u #define FIM_SETFUNCTIONAVAILABLE_ID 0x07u #define FIM_DEMTRIGGERONMONITORSTATUS_ID 0x02u #define FIM_DEMINIT_ID 0x03u #define FIM_GETVERSIONINFO_ID 0x04 #define FIM_MAINFUNCTION_ID 0x05u /* Interface ECUState Manager <-> FiM */ void FiM_Init(const FiM_ConfigType* FiMConfigPtr);/* @req SWS_Fim_00077 */ /* Interface SW-Components <-> FiM */ Std_ReturnType FiM_GetFunctionPermission(FiM_FunctionIdType FID, boolean* Permission);/* @req SWS_Fim_00011 */ Std_ReturnType FiM_SetFunctionAvailable(FiM_FunctionIdType FID, boolean Availability);/* @req SWS_Fim_00106 */ /* Interface Dem <-> FiM */ void FiM_DemTriggerOnMonitorStatus(Dem_EventIdType EventId);/* @req SWS_Fim_00021 */ void FiM_DemInit(void);/* @req SWS_Fim_00006 */ #if (FIM_VERSION_INFO_API == STD_ON) /* @req SWS_Fim_00078 */ void FiM_GetVersionInfo(Std_VersionInfoType* versioninfo); #endif void FiM_MainFunction(void);/* @req SWS_Fim_00060 */ void FiM_Shutdown(void); #endif /* FIM_H_ */
2301_81045437/classic-platform
diagnostic/FiM/inc/FiM.h
C
unknown
2,951
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ #ifndef FIM_TYPES_H_ #define FIM_TYPES_H_ #include "Std_Types.h" #include "Rte_FiM_Type.h" /* @req SWS_Fim_00096 */ #include "Dem_Types.h" #define FIM_LAST_FAILED 0u #define FIM_NOT_TESTED 1u #define FIM_TESTED 2u #define FIM_TESTED_AND_FAILED 3u typedef struct { const uint16 *EventIndexList; uint16 Index; }FiM_SummaryEventCfgType; typedef struct { const uint16 *EventIndexList; const uint16 *InhSumIndexList; const uint8 *InhibitionMask; FiM_FunctionIdType FID; }FiM_InhibitionConfigurationType; typedef struct { const uint16 *InhCfgIndexList; FiM_FunctionIdType FID; }Fim_FIDCfgType; typedef struct { const uint16 *AffectedInhCfgIndexList; Dem_EventIdType EventId; }FiM_EventInhCfgType; /* @req SWS_Fim_00092 */ typedef struct { const FiM_InhibitionConfigurationType *InhibitConfig; const Fim_FIDCfgType *FIDConfig; const FiM_EventInhCfgType *EventInhCfg; const FiM_SummaryEventCfgType *SummeryEventCfg; uint16 EventInhCfg_Size; }FiM_ConfigType; #endif /* FIM_TYPES_H_ */
2301_81045437/classic-platform
diagnostic/FiM/inc/FiM_Types.h
C
unknown
1,908
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.3.0 */ /* * General requirements */ /* !req SWS_Fim_00029 *//* IMPROVEMENT: Check file structure */ /* @req SWS_Fim_00044 *//* Dependency to other modules */ /* @req SWS_Fim_00081 *//* Imported types */ /* !req SWS_Fim_00079 *//* Interfaces not used */ #include "FiM.h" #include <string.h> /*lint -emacro(904, VALIDATE_RV,VALIDATE_NO_RV) MISRA:OTHER::[MISRA 2012 Rule 14.5, advisory] */ #if (FIM_DEV_ERROR_DETECT == STD_ON) /* @req SWS_Fim_00080 */ #include "Det.h" #define VALIDATE_RV(_exp,_api,_err,_rv ) \ if( !(_exp) ) { \ (void)Det_ReportError(FIM_MODULE_ID, 0, _api, _err); \ return _rv; \ } #define VALIDATE_NO_RV(_exp,_api,_err ) \ if( !(_exp) ) { \ (void)Det_ReportError(FIM_MODULE_ID, 0, _api, _err); \ return; \ } #else #define VALIDATE_RV(_exp,_api,_err,_rv ) #define VALIDATE_NO_RV(_exp,_api,_err ) #endif /* FIM_DEV_ERROR_DETECT */ #define IS_VALID_SUMMARY_EVENT(_x) ((_x) < FIM_NOF_SUMMARY_EVENTS) #define IS_VALID_EVENT_ID(_x) ((_x) < FIM_NOF_DEM_EVENTS) /* Local types */ typedef enum { FIM_UNINIT = 0u, FIM_INIT, FIM_DEMINIT }FiMStateType; typedef struct { Dem_MonitorStatusType MonitorStatus; #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_ON) boolean RefreshNeeded; #endif boolean StatusValid; }FiMMonitorStatusType; /* Local variables */ #define FiM_START_SEC_VAR_INIT_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static FiMStateType FiM_InitState = FIM_UNINIT; /* @req SWS_Fim_00059 */ #define FiM_STOP_SEC_VAR_INIT_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static const FiM_ConfigType *FiM_CfgPtr = NULL; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #if (FIM_AVAILABILITY_SUPPORT == STD_ON) #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static boolean FiMFunctionAvailable[FIM_NUM_FIDS]; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #endif #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static boolean FiMFunctionPermissionStatus[FIM_NUM_FIDS]; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static boolean FiMInhibitConfigStatus[FIM_MAX_FIM_INHIBIT_CONFIGURATIONS]; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static FiMMonitorStatusType FiMMonitorStatus[FIM_NOF_DEM_EVENTS]; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_ON) #define FiM_START_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ static boolean FiMRecalculateInhibitConfig[FIM_NOF_INH_CFGS]; #define FiM_STOP_SEC_VAR_CLEARED_UNSPECIFIED #include "FiM_MemMap.h" /*lint !e9019 MISRA:STANDARDIZED_INTERFACE::[MISRA 2012 Rule 20.1, advisory] */ #endif /* Local functions */ /** * Compares monitor status to inhibition mask * @param monitorStatus * @param inhibitionMask * @return TRUE: status and mask match, FALSE: status and mask does NOT match */ static boolean compareStatusToMask(Dem_MonitorStatusType monitorStatus, uint8 inhibitionMask) { boolean match = FALSE; switch(inhibitionMask) { case FIM_LAST_FAILED: match = (0u != (monitorStatus & DEM_MONITOR_STATUS_TF)); break; case FIM_NOT_TESTED: match = (0u != (monitorStatus & DEM_MONITOR_STATUS_TNCTOC)); break; case FIM_TESTED: match = (0u == (monitorStatus & DEM_MONITOR_STATUS_TNCTOC)); break; case FIM_TESTED_AND_FAILED: match = (DEM_MONITOR_STATUS_TF == (monitorStatus & (DEM_MONITOR_STATUS_TF | DEM_MONITOR_STATUS_TNCTOC))); break; default: break; } return match; } /** * Updates all function permissions based on calculated status of inhibit configurations */ static void UpdateFunctionPermissions(void) { const Fim_FIDCfgType *fidCfg; uint16 inhCfgIdx = 0; for( uint16 i = 0; i < FIM_NUM_FIDS; i++ ) { fidCfg = &FiM_CfgPtr->FIDConfig[i]; /* @req SWS_Fim_00015 */ FiMFunctionPermissionStatus[fidCfg->FID] = TRUE; inhCfgIdx = 0; while( (inhCfgIdx < FIM_NOF_INH_CFGS) && (FIM_NO_INH_CFG != fidCfg->InhCfgIndexList[inhCfgIdx]) ) { if( TRUE == FiMInhibitConfigStatus[fidCfg->InhCfgIndexList[inhCfgIdx]] ) { FiMFunctionPermissionStatus[fidCfg->FID] = FALSE; } inhCfgIdx++; } } } /** * Re-calculates the status of inhibit configuration * @param inhCfg * @return TRUE: Inhibit config inhibits the function, FALSE: Inhibit config does NOT inhibit the function */ static boolean RecalculateInhibitConfig(const FiM_InhibitionConfigurationType *inhCfg) { boolean inhibited = FALSE; #if (FIM_USE_SUMMARY_EVENT == STD_ON) const FiM_SummaryEventCfgType *summaryEvent; /* Re-calculate the summary events */ /* @req SWS_Fim_00064 */ for( uint16 summaryEvtIndex = 0u; (summaryEvtIndex < FIM_MAX_SUM_EVENTS_PER_FID_INHIBITION_CONFIGURATION) && (FALSE == inhibited); summaryEvtIndex++ ) { if( IS_VALID_SUMMARY_EVENT(inhCfg->InhSumIndexList[summaryEvtIndex]) ) { summaryEvent = &FiM_CfgPtr->SummeryEventCfg[inhCfg->InhSumIndexList[summaryEvtIndex]]; for( uint16 evtIndex = 0; evtIndex < FIM_MAX_INPUT_EVENTS_PER_SUMMARY_EVENTS; evtIndex++ ) { if( (FIM_NO_DEM_EVENT_ID != summaryEvent->EventIndexList[evtIndex]) && (TRUE == FiMMonitorStatus[summaryEvent->EventIndexList[evtIndex]].StatusValid) && (TRUE == compareStatusToMask(FiMMonitorStatus[summaryEvent->EventIndexList[evtIndex]].MonitorStatus, *inhCfg->InhibitionMask)) ) { inhibited = TRUE; } } } } #endif /* Re-calculate the events */ for( uint16 evtIndex = 0u; (evtIndex < FIM_MAX_EVENTS_PER_FID_INHIBIT_CONFIGURATION) && (FALSE == inhibited); evtIndex++ ) { if( IS_VALID_EVENT_ID(inhCfg->EventIndexList[evtIndex]) && (TRUE == FiMMonitorStatus[inhCfg->EventIndexList[evtIndex]].StatusValid) ) { /* Compare to mask */ /* @req SWS_Fim_00004 */ if( TRUE == compareStatusToMask(FiMMonitorStatus[inhCfg->EventIndexList[evtIndex]].MonitorStatus, *inhCfg->InhibitionMask) ) { inhibited = TRUE; } } } return inhibited; } /** * Re-calculates all inhibit conditions */ static void RecalculateAllInhibitConditions(void) { /* Refresh monitor status if needed */ for( uint16 i = 0; i < FIM_NOF_DEM_EVENTS; i++ ) { /* @req SWS_Fim_00097 */ /* @req SWS_Fim_00067 */ /* @req SWS_Fim_00072 */ FiMMonitorStatus[i].StatusValid = (E_OK == Dem_GetMonitorStatus(FiM_CfgPtr->EventInhCfg[i].EventId, &FiMMonitorStatus[i].MonitorStatus)); #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_ON) #if defined(CFG_FIM_REFRESH_INVALID_EVENTS) FiMMonitorStatus[i].RefreshNeeded = (FALSE == FiMMonitorStatus[i].StatusValid); #else FiMMonitorStatus[i].RefreshNeeded = FALSE; #endif #endif } /* Re-calculate inhibit configuration */ for(uint16 inhCfgIdx = 0u; inhCfgIdx < FIM_MAX_FIM_INHIBIT_CONFIGURATIONS; inhCfgIdx++) { FiMInhibitConfigStatus[inhCfgIdx] = RecalculateInhibitConfig(&FiM_CfgPtr->InhibitConfig[inhCfgIdx]); } /* Now set the permission per function */ UpdateFunctionPermissions(); } /* Exported functions */ /** * This service initializes the FIM. * @param FiMConfigPtr */ /* @req SWS_Fim_00077 */ void FiM_Init(const FiM_ConfigType* FiMConfigPtr) { /* @req SWS_Fim_00045 */ VALIDATE_NO_RV((NULL != FiMConfigPtr), FIM_INIT_ID, FIM_E_PARAM_POINTER); VALIDATE_NO_RV((FIM_UNINIT == FiM_InitState), FIM_INIT_ID, FIM_E_REINIT) if( FIM_UNINIT == FiM_InitState ) { FiM_CfgPtr = FiMConfigPtr; memset(FiMFunctionPermissionStatus, TRUE, FIM_NUM_FIDS); #if (FIM_AVAILABILITY_SUPPORT == STD_ON) memset(FiMFunctionAvailable, TRUE, FIM_NUM_FIDS); #endif #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_ON) memset(FiMMonitorStatus, 0u, sizeof(FiMMonitorStatus)); #endif FiM_InitState = FIM_INIT; } } /** * This service reports the permission state to the functionality. * @param FID * @param Permission * @return */ /* @req SWS_Fim_00011 */ Std_ReturnType FiM_GetFunctionPermission(FiM_FunctionIdType FID, boolean* Permission) { /* @req SWS_Fim_00020 */ /* @req SWS_Fim_00056 */ if( NULL != Permission ) { *Permission = FALSE; } VALIDATE_RV((FIM_DEMINIT == FiM_InitState), FIM_GETFUNCTIONPERMISSION_ID, FIM_E_UNINIT, E_NOT_OK); /* @req SWS_Fim_00055 */ VALIDATE_RV((FID < FIM_NUM_FIDS), FIM_GETFUNCTIONPERMISSION_ID, FIM_E_FID_OUT_OF_RANGE, E_NOT_OK); VALIDATE_RV((NULL != Permission), FIM_GETFUNCTIONPERMISSION_ID, FIM_E_PARAM_POINTER, E_NOT_OK); /* @req SWS_Fim_00003 */ /* @req SWS_Fim_00025 */ #if (FIM_AVAILABILITY_SUPPORT == STD_ON) /* @req SWS_Fim_00105 */ *Permission = (TRUE == FiMFunctionPermissionStatus[FID]) && (TRUE == FiMFunctionAvailable[FID]); #else *Permission = FiMFunctionPermissionStatus[FID]; #endif return E_OK; } /** * This service sets the availability of a function. The function is only available if FiMAvailabilitySupport is configured as True * @param FID * @param Availability * @return */ /* @req SWS_Fim_00106 */ #if (FIM_AVAILABILITY_SUPPORT == STD_ON) Std_ReturnType FiM_SetFunctionAvailable(FiM_FunctionIdType FID, boolean Availability) { VALIDATE_RV((FIM_DEMINIT == FiM_InitState), FIM_SETFUNCTIONAVAILABLE_ID, FIM_E_UNINIT, E_NOT_OK); VALIDATE_RV((FID < FIM_NUM_FIDS), FIM_SETFUNCTIONAVAILABLE_ID, FIM_E_FID_OUT_OF_RANGE, E_NOT_OK); /* @req SWS_Fim_00003 */ FiMFunctionAvailable[FID] = Availability; return E_OK; } #endif /* FIM_AVAILABILITY_SUPPORT */ /** * This service is provided to be called by the Dem in order to inform the Fim about monitor status changes. * @param EventId */ /* @req SWS_Fim_00021 */ void FiM_DemTriggerOnMonitorStatus(Dem_EventIdType EventId) { /* !req SWS_Fim_00057 */ /* @req SWS_Fim_00058 */ VALIDATE_NO_RV((FIM_DEMINIT == FiM_InitState), FIM_DEMTRIGGERONMONITORSTATUS_ID, FIM_E_UNINIT); /* @req SWS_Fim_00010 */ /* @req SWS_Fim_00043 */ #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_ON) boolean done = FALSE; uint16 inhCfgIdx = 0; const FiM_EventInhCfgType *evtInhCfg; /* Find the config */ for( uint16 i = 0; (i < FiM_CfgPtr->EventInhCfg_Size) && (FALSE == done); i++ ) { evtInhCfg = &FiM_CfgPtr->EventInhCfg[i]; if( EventId == evtInhCfg->EventId ) { while( (inhCfgIdx < FIM_NOF_INH_CFGS) && (FIM_NO_INH_CFG != evtInhCfg->AffectedInhCfgIndexList[inhCfgIdx]) ) { FiMRecalculateInhibitConfig[evtInhCfg->AffectedInhCfgIndexList[inhCfgIdx]] = TRUE; inhCfgIdx++; } FiMMonitorStatus[i].RefreshNeeded = TRUE; done = TRUE; } } #else (void)EventId; #endif } /** * This service re-initializes the FIM. */ /* @req SWS_Fim_00006 */ void FiM_DemInit(void) { VALIDATE_NO_RV((FIM_DEMINIT != FiM_InitState), FIM_DEMINIT_ID, FIM_E_REINIT); VALIDATE_NO_RV((FIM_INIT == FiM_InitState), FIM_DEMINIT_ID, FIM_E_UNINIT); /* @req SWS_Fim_00069 */ /* @req SWS_Fim_00082 */ if( FIM_INIT == FiM_InitState ) { /* @req SWS_Fim_00018 */ RecalculateAllInhibitConditions(); FiM_InitState = FIM_DEMINIT; } } /** * */ /* @req SWS_Fim_00060 */ void FiM_MainFunction(void) { /* @req SWS_Fim_00043 */ /* @req SWS_Fim_00065 */ /* @req SWS_Fim_00022 */ /* @req SWS_Fim_00012 */ VALIDATE_NO_RV((FIM_DEMINIT == FiM_InitState), FIM_MAINFUNCTION_ID, FIM_E_UNINIT); #if (FIM_EVENT_UPDATE_TRIGGERED_BY_DEM == STD_OFF) /* @req SWS_Fim_00070 */ /* Now set the permission per function */ RecalculateAllInhibitConditions(); #else /* Refresh monitor status if needed */ for( uint16 i = 0; i < FIM_NOF_DEM_EVENTS; i++ ) { if( TRUE == FiMMonitorStatus[i].RefreshNeeded ) { /* @req SWS_Fim_00097 */ /* @req SWS_Fim_00067 */ /* @req SWS_Fim_00072 */ FiMMonitorStatus[i].StatusValid = (E_OK == Dem_GetMonitorStatus(FiM_CfgPtr->EventInhCfg[i].EventId, &FiMMonitorStatus[i].MonitorStatus)); } #if defined(CFG_FIM_REFRESH_INVALID_EVENTS) FiMMonitorStatus[i].RefreshNeeded = (FALSE == FiMMonitorStatus[i].StatusValid); #else FiMMonitorStatus[i].RefreshNeeded = FALSE; #endif } /* Re-calculate according to what has been reported by Dem */ for(uint16 inhCfgIdx = 0u; inhCfgIdx < FIM_MAX_FIM_INHIBIT_CONFIGURATIONS; inhCfgIdx++) { if( TRUE == FiMRecalculateInhibitConfig[inhCfgIdx] ) { FiMInhibitConfigStatus[inhCfgIdx] = RecalculateInhibitConfig(&FiM_CfgPtr->InhibitConfig[inhCfgIdx]); FiMRecalculateInhibitConfig[inhCfgIdx] = FALSE; } } /* Now set the permission per function */ UpdateFunctionPermissions(); #endif /* FIM_EVENT_UPDATE_TRIGGERED_BY_DEM */ } #if (FIM_VERSION_INFO_API == STD_ON) /** * This service returns the version information of this module. * @param versioninfo */ void FiM_GetVersionInfo(Std_VersionInfoType* versioninfo) { VALIDATE_NO_RV((NULL != versioninfo), FIM_GETVERSIONINFO_ID, FIM_E_PARAM_POINTER); versioninfo->moduleID = FIM_MODULE_ID; versioninfo->sw_major_version = FIM_SW_MAJOR_VERSION; versioninfo->sw_minor_version = FIM_SW_MINOR_VERSION; versioninfo->sw_patch_version = FIM_SW_PATCH_VERSION; versioninfo->vendorID = 60; } #endif /* FIM_VERSION_INFO_API */ /** * Shuts down FiM */ void FiM_Shutdown(void) { FiM_InitState = FIM_UNINIT; }
2301_81045437/classic-platform
diagnostic/FiM/src/FiM.c
C
unknown
16,226
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.1.2 */ /* * General requirements * */ /* ----------------------------[includes]------------------------------------*/ #include "Cpu.h" #include "Mcu.h" #include "Can.h" #include "isr.h" #include "irq.h" #include "Dio.h" #include "Spi.h" /* @req SWS_CanTrcv_00067 */ #include "CanTrcv.h" #include "CanTrcv_Internal.h" #if defined(CANTRCV_DEVICE_TYPE) && defined(TJA1145) #if (CANTRCV_DEVICE_TYPE != TJA1145) #error CANTRCV: CanTrcvDevice is not properly configured #endif #endif #include "CanTrcv_TJA1145.h" #if (CAN_DEV_ERROR_DETECT == STD_ON) #include "Det.h" #endif #include "EcuM.h" #include "CanIf.h" /* ----------------------------[private define]------------------------------*/ /* ----------------------------[private typedef]-----------------------------*/ /* ----------------------------[private function prototypes]-----------------*/ /* ----------------------------[private variables]---------------------------*/ Spi_SeqResultType SeqResult; Std_ReturnType ApiReturn; static CanTrcv_InternalType CanTrcv_Internal; const CanTrcv_ConfigType * CanTrcv_ConfigPtr; /* ----------------------------[private macro]-------------------------------*/ #if ( CANTRCV_DEV_ERROR_DETECT == STD_ON ) #define DET_REPORT_ERROR(_api,_err) Det_ReportError(CANTRCV_MODULE_ID, 0, _api, _err) #define VALIDATE(_exp,_api,_err,...) \ if( !(_exp) ) { \ (void)DET_REPORT_ERROR(_api, _err); \ return __VA_ARGS__; \ } #else #define DET_REPORT_ERROR(_api,_err) #define VALIDATE(_exp,_api,_err,...) \ if( !(_exp) ) { \ return __VA_ARGS__; \ } #endif /* ----------------------------[private functions]---------------------------*/ static Std_ReturnType initializeTransceiver(uint8 trcv,CanTrcv_TrcvWakeupReasonType* wakeupReason); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) static Std_ReturnType initializeSelectiveWakeup(uint8 trcv,CanTrcv_TrcvWakeupReasonType* wakeupReason,uint8 apiId); #endif static Std_ReturnType canTrcvSetMode(uint8 trcv,CanTrcv_TrcvModeType currMode,const CanTrcv_SpiSequenceConfigType *spiSeq,CanTrcv_TrcvModeType OpMode); /* Initialization sequence for transceivers */ static Std_ReturnType initializeTransceiver(uint8 trcv,CanTrcv_TrcvWakeupReasonType* wakeupReason) { const CanTrcv_SpiSequenceConfigType *spiSeq; CanTrcv_TrcvModeType mode; Std_ReturnType ret; ret = E_OK; spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSpiSequenceConfig; #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupByBus) { /* Selective wakeup - Partial networking */ if (E_NOT_OK == initializeSelectiveWakeup(trcv,wakeupReason,CANTRCV_INIT_ID)) { ret = E_NOT_OK; } else { /* Do nothing */ } if (E_OK == ret) { /* @req SWS_CanTrcv_00113 */ /* Clear all wake up events otherwise subsequent mode transition to sleep is impossible */ VALIDATE((E_OK == CanTrcv_Hw_ClearWakeUpEventStatus(spiSeq)),CANTRCV_INIT_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_CurWakeupFlag = FALSE; /* @req SWS_CanTrcv_00113 */ /* Enable selective or standard ISO 11898 -2 wakeup pattern based on PN support*/ VALIDATE((E_OK == CanTrcv_Hw_EnableWakeUpEvent(spiSeq)), CANTRCV_INIT_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_CurWakeupMode = CANTRCV_WUMODE_ENABLE; } } #endif if (E_OK == ret) { /* Set Initial mode */ /* @req SWS_CanTrcv_00100 */ /* @req SWS_CanTrcv_00113 */ mode =CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvInitState; VALIDATE((E_OK == CanTrcv_Hw_SetupMode(mode,spiSeq)), CANTRCV_INIT_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_TrcvCurMode = mode; } return ret; } #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) /* Initialization for selective wakeup */ static Std_ReturnType initializeSelectiveWakeup(uint8 trcv,CanTrcv_TrcvWakeupReasonType* wakeupReason,uint8 apiId) { const CanTrcv_SpiSequenceConfigType *spiSeq; boolean reset; boolean failSts; boolean configErrSts; boolean wakeupFlag; reset = FALSE; failSts = FALSE; configErrSts = FALSE; spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSpiSequenceConfig; if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPnSupport) { /* @req SWS_CanTrcv_00181 */ /* Read Power on state */ /* @req SWS_CanTrcv_00113 */ VALIDATE((E_OK == CanTrcv_Hw_ReadWakeupEventStatus(wakeupReason,&wakeupFlag,spiSeq)), apiId, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); if (CANTRCV_WU_POWER_ON == * wakeupReason) { reset =TRUE; } else if (CANTRCV_WU_BY_SYSERR == * wakeupReason) { failSts = TRUE; } else { /* Do nothing */ } /* Read PN configuration status if PN is supported*/ /* @req SWS_CanTrcv_00113 */ VALIDATE((E_OK == CanTrcv_Hw_ReadPNConfigurationStatus(&configErrSts,spiSeq)), apiId, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); /* In case of reset or error, run initialization of hardware */ /* @req SWS_CanTrcv_00182 */ if ((TRUE == reset) || (TRUE == configErrSts) || (TRUE == failSts)) { /* Setup Baud rate */ /* @req SWS_CanTrcv_00168 */ VALIDATE((E_OK == CanTrcv_Hw_SetBaudRate(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPartialNetworkConfig->CanTrcvBaudRate,spiSeq)), apiId, CANTRCV_E_BAUDRATE_NOT_SUPPORTED,E_NOT_OK); /* Setup Partial networking registers for selective wakeup ISO 11898 -6 */ /* @req SWS_CanTrcv_00113 */ VALIDATE((E_OK == CanTrcv_Hw_SetupPN(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPartialNetworkConfig,spiSeq)), apiId, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); if (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPartialNetworkConfig->CanTrcvPnEnabled) { /* @req SWS_CanTrcv_00113 */ VALIDATE((E_OK == CanTrcv_Hw_EnablePN(spiSeq)),apiId, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); } else { /* Do nothing */ } } else { /* Do nothing */ } } return E_OK; } #endif /* Set transceiver mode */ static Std_ReturnType canTrcvSetMode(uint8 trcv,CanTrcv_TrcvModeType currMode,const CanTrcv_SpiSequenceConfigType *spiSeq,CanTrcv_TrcvModeType OpMode) { Std_ReturnType ret; ret = E_OK; switch (currMode){ /* @req SWS_CanTrcv_00103 */ case CANTRCV_TRCVMODE_NORMAL: if (OpMode == CANTRCV_TRCVMODE_STANDBY){ /* Transition from Normal mode to Standby Mode */ /* @req SWS_CanTrcv_00114 */ VALIDATE((E_OK == CanTrcv_Hw_SetupMode(OpMode,spiSeq)), CANTRCV_SET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); } else if (OpMode == CANTRCV_TRCVMODE_SLEEP){ /* Transition from Normal mode to Sleep Mode is invalid*/ ret =E_NOT_OK; } else if (OpMode == CANTRCV_TRCVMODE_NORMAL){ /* Do nothing */ } else { /* Do nothing */ } break; /* @req SWS_CanTrcv_00104 */ case CANTRCV_TRCVMODE_STANDBY: if (OpMode == CANTRCV_TRCVMODE_NORMAL){ /* Transition from Standby mode to Normal Mode */ /* @req SWS_CanTrcv_00114 */ VALIDATE((E_OK == CanTrcv_Hw_SetupMode(OpMode,spiSeq)), CANTRCV_SET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); } else if (OpMode == CANTRCV_TRCVMODE_SLEEP){ #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupByBus) { /* Transition from Standby mode to Sleep Mode */ /* clear event flags otherwise sleep mode is not entered successfully*/ VALIDATE((E_OK == CanTrcv_Hw_ClearWakeUpEventStatus(spiSeq)), CANTRCV_SET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_CurWakeupFlag = FALSE; } #else (void)trcv; #endif /* @req SWS_CanTrcv_00114 */ VALIDATE((E_OK == CanTrcv_Hw_SetupMode(OpMode,spiSeq)), CANTRCV_SET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); } else if (OpMode == CANTRCV_TRCVMODE_STANDBY){ /* Do nothing */ } else { /* Do nothing */ } break; case CANTRCV_TRCVMODE_SLEEP: if (OpMode == CANTRCV_TRCVMODE_NORMAL){ /* Transition from Sleep mode to Normal Mode */ /* @req SWS_CanTrcv_00114 */ VALIDATE((E_OK == CanTrcv_Hw_SetupMode(OpMode,spiSeq)), CANTRCV_SET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL,E_NOT_OK); } else if (OpMode == CANTRCV_TRCVMODE_STANDBY){ /* Transition from Sleep mode to Standby Mode is invalid*/ ret =E_NOT_OK; } else if (OpMode == CANTRCV_TRCVMODE_SLEEP){ /* Do nothing */ } else { /* Do nothing */ } break; default: ret = E_NOT_OK; break; } return ret; } /* ----------------------------[API]---------------------------*/ /** @req SWS_CanTrcv_00001 */ /** Initializes the CanTrcv module. **/ void CanTrcv_Init(const CanTrcv_ConfigType *ConfigPtr) { CanTrcv_TrcvWakeupReasonType wakeUpReason; CanTrcv_Internal.initRun = FALSE; /* @req SWS_CanTrcv_00185 */ VALIDATE(( NULL != ConfigPtr ), CANTRCV_INIT_ID, CANTRCV_E_PARAM_POINTER); CanTrcv_ConfigPtr = ConfigPtr; for(uint8 trcv=0;trcv<CANTRCV_CHANNEL_COUNT ;trcv++) { // CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_TrcvCurMode = CANTRCV_TRCVMODE_UNITIALIZED; if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvEnableStatus) { wakeUpReason = CANTRCV_WU_NOT_SUPPORTED; /* @req SWS_CanTrcv_00180 */ if (E_OK == initializeTransceiver(trcv,&wakeUpReason)){ #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) /* Clear wake up flags as there is no requirement to remember power on or error wake up events */ CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_CurWakeupFlag = FALSE; CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_TrcvWakeupReason = CANTRCV_WU_NOT_SUPPORTED; if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupByBus) { /* @req SWS_CanTrcv_00167 */ if (CANTRCV_WU_POWER_ON == wakeUpReason) { /* @req SWS_CanTrcv_00183 */ EcuM_SetWakeupEvent(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPorWakeupSourceRef); } else if ((CANTRCV_WU_BY_SYSERR == wakeUpReason) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSyserrWakeupSourceRef !=CANTRCV_INVALID_WAKEUP_SOURCE)) { /* @req SWS_CanTrcv_00184 */ EcuM_SetWakeupEvent(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSyserrWakeupSourceRef); } else { /* Do nothing */ } } #endif } } /* Initialization done,Set the flag */ CanTrcv_Internal.initRun = TRUE; } } /* End of CanTrcv_Init function */ /* @req SWS_CanTrcv_00002 **/ /** Sets the mode of the Transceiver to the value OpMode. */ Std_ReturnType CanTrcv_SetOpMode(uint8 Transceiver, CanTrcv_TrcvModeType OpMode) { const CanTrcv_SpiSequenceConfigType *spiSeq; CanTrcv_TrcvModeType currMode; CanTrcv_TrcvWakeupReasonType wakeUpReason; Std_ReturnType ret; boolean validSts; ret = E_OK; wakeUpReason = CANTRCV_WU_NOT_SUPPORTED; /* @req SWS_CanTrcv_00122 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_SET_OPMODE_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00123 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_SET_OPMODE_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); currMode = CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvCurMode; /* @req SWS_CanTrcv_00102 */ /* @req SWS_CanTrcv_00087 */ /* @req SWS_CanTrcv_00105 */ validSts = ((CANTRCV_TRCVMODE_NORMAL == OpMode) || (CANTRCV_TRCVMODE_STANDBY == OpMode) || (CANTRCV_TRCVMODE_SLEEP == OpMode)); VALIDATE(validSts, CANTRCV_SET_OPMODE_ID, CANTRCV_E_PARAM_TRCV_OPMODE, E_NOT_OK); /* @req SWS_CanTrcv_00120 */ validSts = !((currMode == CANTRCV_TRCVMODE_SLEEP) && (CANTRCV_TRCVMODE_STANDBY == OpMode)); VALIDATE(validSts, CANTRCV_SET_OPMODE_ID, CANTRCV_E_TRCV_NOT_NORMAL, E_NOT_OK); /*@req SWS_CanTrcv_00121 */ validSts = !((CANTRCV_TRCVMODE_SLEEP == OpMode) && (currMode == CANTRCV_TRCVMODE_NORMAL)); VALIDATE(validSts, CANTRCV_SET_OPMODE_ID, CANTRCV_E_TRCV_NOT_STANDBY, E_NOT_OK); if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { ret = E_NOT_OK; } else { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) if (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvWakeupByBus) { /* @req SWS_CanTrcv_00186 */ /* @req SWS_CanTrcv_00187 */ /* Errors in configuration or bus errors lead to initialization */ ret = initializeSelectiveWakeup(Transceiver,&wakeUpReason,CANTRCV_SET_OPMODE_ID); } #else (void)wakeUpReason; #endif if (E_OK == ret){ if (E_OK == canTrcvSetMode(Transceiver,currMode,spiSeq,OpMode)) { CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvCurMode = OpMode; #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) /* We check if wake up & partial networking is supported before we indicate PN availability */ if ((CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvCurMode == CANTRCV_TRCVMODE_NORMAL) || (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPnSupport) || (TRUE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvWakeupByBus)) { /* @req SWS_CanTrcv_00188 */ CanIf_ConfirmPnAvailability(Transceiver); } #endif } else{ ret = E_NOT_OK; } } } (void)wakeUpReason; return ret; } /** Gets the mode of the Transceiver and returns it in OpMode. */ /* @req SWS_CanTrcv_00005 */ Std_ReturnType CanTrcv_GetOpMode(uint8 Transceiver, CanTrcv_TrcvModeType* OpMode) { const CanTrcv_SpiSequenceConfigType *spiSeq; Std_ReturnType ret; ret = E_OK; /* @req SWS_CanTrcv_00124 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_GET_OPMODE_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00129 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_GET_OPMODE_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00132 */ VALIDATE((OpMode != NULL), CANTRCV_GET_OPMODE_ID, CANTRCV_E_PARAM_POINTER, E_NOT_OK); if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { //QQ *OpMode= CANTRCV_TRCVMODE_UNITIALIZED; ret = E_NOT_OK; } else{ spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; /* @req SWS_CanTrcv_00115 */ /* @req SWS_CanTrcv_00106 */ VALIDATE((E_OK == CanTrcv_Hw_ReadCurrMode(OpMode,spiSeq)), CANTRCV_GET_OPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); } return ret; } /** Gets the wakeup reason for the Transceiver and returns it in parameter Reason. */ /* @req SWS_CanTrcv_00007 **/ Std_ReturnType CanTrcv_GetBusWuReason(uint8 Transceiver, CanTrcv_TrcvWakeupReasonType* reason) { Std_ReturnType ret; ret = E_OK; /* @req SWS_CanTrcv_00125 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_GET_BUSWUREASON_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00130 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_GET_BUSWUREASON_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00133 */ VALIDATE((reason != NULL), CANTRCV_GET_BUSWUREASON_ID, CANTRCV_E_PARAM_POINTER, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) if ((FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) || ((FALSE == CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag))){ ret = E_NOT_OK; /* If there is no wake up detected return E_NOT_OK */ } else { *reason = CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvWakeupReason ; } #else ret = E_NOT_OK; #endif return ret; } /** Gets the version of the module and returns it in VersionInfo. */ /* @req SWS_CanTrcv_00008 **/ #if ( CANTRCV_GET_VERSION_INFO == STD_ON ) #define CanTrcv_GetVersionInfo(_vi) STD_GET_VERSION_INFO(_vi,CANTRCV) #endif /** Enables, disables or clears wake-up events of the Transceiver according to TrcvWakeupMode. */ /* @req SWS_CanTrcv_00009 **/ Std_ReturnType CanTrcv_SetWakeupMode(uint8 Transceiver, CanTrcv_TrcvWakeupModeType TrcvWakeupMode) { Std_ReturnType ret; boolean validSts; ret = E_OK; /* @req SWS_CanTrcv_00127 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00131 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00089 */ validSts = ((TrcvWakeupMode == CANTRCV_WUMODE_ENABLE) || (TrcvWakeupMode == CANTRCV_WUMODE_CLEAR) || (TrcvWakeupMode == CANTRCV_WUMODE_DISABLE)); VALIDATE(validSts, CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_PARAM_TRCV_WAKEUP_MODE, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) const CanTrcv_SpiSequenceConfigType *spiSeq; if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { ret = E_NOT_OK; } else if (TrcvWakeupMode != CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode) { /* New mode is requested */ spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; /* @req SWS_CanTrcv_00111 */ if (TrcvWakeupMode == CANTRCV_WUMODE_ENABLE) { /* @req SWS_CanTrcv_00117 */ VALIDATE((E_OK == CanTrcv_Hw_EnableWakeUpEvent(spiSeq)), CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode = CANTRCV_WUMODE_ENABLE; } /* @req SWS_CanTrcv_00093 */ else if (TrcvWakeupMode == CANTRCV_WUMODE_DISABLE) { /* @req SWS_CanTrcv_00095 */ /* @req SWS_CanTrcv_00117 */ /* Wake up is detected by the device but notification is disabled */ CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode = CANTRCV_WUMODE_DISABLE; /* @req SWS_CanTrcv_00150 */ /* @req SWS_CanTrcv_00117 */ VALIDATE((E_OK == CanTrcv_Hw_ClearWakeUpEventStatus(spiSeq)), CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag = FALSE; CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode = CANTRCV_WUMODE_CLEAR; } /* @req SWS_CanTrcv_00094 */ else if (TrcvWakeupMode == CANTRCV_WUMODE_CLEAR) { /* @req SWS_CanTrcv_00117 */ VALIDATE((E_OK == CanTrcv_Hw_ClearWakeUpEventStatus(spiSeq)), CANTRCV_SET_WAKEUPMODE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag = FALSE; CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode = CANTRCV_WUMODE_CLEAR; } else { ret = E_NOT_OK; } } else { /* Do nothing */ } #else ret = E_NOT_OK; #endif return ret; } /** Reads the transceiver configuration/status data and returns it through para */ /* !req SWS_CanTrcv_00213 **/ Std_ReturnType CanTrcv_GetTrcvSystemData(uint8 Transceiver,uint32* TrcvSysData) { Std_ReturnType ret = E_NOT_OK; ret = E_NOT_OK; /* SPI related local declaration */ /* @req SWS_CanTrcv_00191 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_GET_TRCVSYSTEMDATA_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00192 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_GET_TRCVSYSTEMDATA_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00193 */ VALIDATE((TrcvSysData != NULL), CANTRCV_GET_TRCVSYSTEMDATA_ID, CANTRCV_E_PARAM_POINTER, E_NOT_OK); if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { ret = E_NOT_OK; } else { /* Do nothing */ } /* !req SWS_CanTrcv_00190 */ return ret; } /** Clears the WUF flag in the transceiver hardware. This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* @req SWS_CanTrcv_00214 **/ Std_ReturnType CanTrcv_ClearTrcvWufFlag(uint8 Transceiver) { Std_ReturnType ret; ret = E_OK; /* @req SWS_CanTrcv_00197 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_CLEAR_TRCVWUFFLAG_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00198 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_CLEAR_TRCVWUFFLAG_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) const CanTrcv_SpiSequenceConfigType *spiSeq; if ((FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus)|| (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPnSupport)) { ret = E_NOT_OK; } else { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; /* @req SWS_CanTrcv_00196 */ /* @req SWS_CanTrcv_00194 */ VALIDATE((E_OK == CanTrcv_Hw_ClearWakeUpEventStatus(spiSeq)), CANTRCV_CLEAR_TRCVWUFFLAG_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); /* @req SWS_CanTrcv_00196 */ /* @req SWS_CanTrcv_00195 */ CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag = FALSE; CanIf_ClearTrcvWufFlagIndication(Transceiver); /* Transition to standby mode happens later by CanIf_SetTrcvMode(). Ref flow diagram Deinitialization (SPI synchronous) */ } #else ret = E_NOT_OK; #endif return ret; } /** Reads the status of the timeout flag from the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* !req SWS_CanTrcv_00215 **/ Std_ReturnType CanTrcv_ReadTrcvTimeoutFlag(uint8 Transceiver, CanTrcv_TrcvFlagStateType* FlagState) { Std_ReturnType ret; ret = E_OK; VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_READ_TRCVTIMEOUTFLAG_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00199 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_READ_TRCVTIMEOUTFLAG_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00200 */ VALIDATE((FlagState != NULL), CANTRCV_READ_TRCVTIMEOUTFLAG_ID, CANTRCV_E_PARAM_POINTER, E_NOT_OK); if ((FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus)|| (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPnSupport)) { ret = E_NOT_OK; } else { /* Do nothing */ } return ret; } /** Clears the status of the timeout flag in the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* !req SWS_CanTrcv_00216 **/ Std_ReturnType CanTrcv_ClearTrcvTimeoutFlag(uint8 Transceiver) { Std_ReturnType ret; ret = E_OK; VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_CLEAR_TRCVTIMEOUTFLAG_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00201 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_CLEAR_TRCVTIMEOUTFLAG_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); if ((FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus)|| (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPnSupport)) { ret = E_NOT_OK; } else { /* Do nothing */ } return ret; } /** Reads the status of the silence flag from the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* @req SWS_CanTrcv_00217 **/ Std_ReturnType CanTrcv_ReadTrcvSilenceFlag(uint8 Transceiver, CanTrcv_TrcvFlagStateType* FlagState) { const CanTrcv_SpiSequenceConfigType *spiSeq; Std_ReturnType ret; ret = E_OK; /* Without initialization it is not possible to read the status of silence flag */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_READ_TRCVSILENCEFLAG_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00202 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_READ_TRCVSILENCEFLAG_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); /* @req SWS_CanTrcv_00203 */ VALIDATE((FlagState != NULL), CANTRCV_READ_TRCVSILENCEFLAG_ID, CANTRCV_E_PARAM_POINTER, E_NOT_OK); if ((FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus)|| (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPnSupport)) { ret = E_NOT_OK; } else { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; VALIDATE((E_OK == CanTrcv_Hw_ReadSilenceFlag(FlagState,spiSeq)), CANTRCV_READ_TRCVSILENCEFLAG_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); } return ret; } /** Service is called by underlying CANIF in case a wake up interrupt is detected. */ /* @req SWS_CanTrcv_00143 **/ Std_ReturnType CanTrcv_CheckWakeup(uint8 Transceiver) { CanTrcv_TrcvWakeupReasonType reason; Std_ReturnType ret; boolean wakeupFlag; ret = E_OK; wakeupFlag = FALSE; reason = CANTRCV_WU_NOT_SUPPORTED; /* @req SWS_CanTrcv_00144 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_CHECK_WAKEUP_ID, CANTRCV_E_UNINIT, E_NOT_OK); /* @req SWS_CanTrcv_00145 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_CHECK_WAKEUP_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) const CanTrcv_SpiSequenceConfigType *spiSeq; if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { ret = E_NOT_OK; } else { /* @req SWS_CanTrcv_00091 */ spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; /* @req SWS_CanTrcv_00146 */ VALIDATE((E_OK == CanTrcv_Hw_ReadWakeupEventStatus(&reason,&wakeupFlag,spiSeq)), CANTRCV_CHECK_WAKEUP_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); if (wakeupFlag){ /* Transceiver should be brought to normal mode after sleep (wake up leads to transition to Standby in TJA1145) */ VALIDATE((E_OK == canTrcvSetMode(Transceiver,CANTRCV_TRCVMODE_SLEEP,spiSeq, CANTRCV_TRCVMODE_NORMAL)), CANTRCV_CHECK_WAKEUP_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvCurMode = CANTRCV_TRCVMODE_NORMAL; CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag = TRUE; CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvWakeupReason = reason; /* The following requirements are derived from EcuM fixed sequence dig 9.2.3 in ASR 4.0.3 */ if (CANTRCV_WUMODE_ENABLE == CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupMode) { if ((CANTRCV_WU_BY_BUS == reason) && (CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvWakeupSourceRef != CANTRCV_INVALID_WAKEUP_SOURCE)) { EcuM_SetWakeupEvent(CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvWakeupSourceRef); } else if ((CANTRCV_WU_BY_SYSERR == reason) && (CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSyserrWakeupSourceRef != CANTRCV_INVALID_WAKEUP_SOURCE)) { EcuM_SetWakeupEvent(CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSyserrWakeupSourceRef); } else if ((CANTRCV_WU_BY_PIN == reason)|| (CANTRCV_WU_POWER_ON == reason)) { EcuM_SetWakeupEvent(CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvPorWakeupSourceRef); } else { /* Do nothing */ } } } else { ret = E_NOT_OK; } } #else (void)wakeupFlag; (void)reason; ret = E_NOT_OK; #endif return ret; } /** The API configures the wake-up of the transceiver for Standby and Sleep Mode: * Either the CAN transceiver is woken up by a remote wake-up pattern * (standard CAN wake-up) or by the configured remote wake-up frame. */ /* @req SWS_CanTrcv_00219 **/ Std_ReturnType CanTrcv_SetPNActivationState(CanTrcv_PNActivationType ActivationState) { Std_ReturnType ret; ret = E_OK; /* @req SWS_CanTrcv_00220 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_SET_PNACTIVATIONSTATE_ID, CANTRCV_E_UNINIT, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) const CanTrcv_SpiSequenceConfigType *spiSeq; uint8 trcv;/*Transceiver count */ boolean stsValid; /* @req SWS_CanTrcv_00222 */ if (PN_DISABLED == ActivationState) { for(trcv=0;trcv<CANTRCV_CHANNEL_COUNT ;trcv++) { stsValid = (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvEnableStatus) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupByBus) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPnSupport) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPartialNetworkConfig->CanTrcvPnEnabled) ; if (TRUE == stsValid) { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSpiSequenceConfig; VALIDATE((E_OK == CanTrcv_Hw_DisablePN(spiSeq)), CANTRCV_SET_PNACTIVATIONSTATE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); } else { ret = E_NOT_OK; } } } /* @req SWS_CanTrcv_00221 */ else if (PN_ENABLED == ActivationState) { for(uint8 trcv_index=0;trcv_index<CANTRCV_CHANNEL_COUNT ;trcv_index++) { stsValid = (CanTrcv_ConfigPtr->CanTrcvChannel[trcv_index].CanTrcvEnableStatus) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv_index].CanTrcvWakeupByBus) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv_index].CanTrcvPnSupport) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv_index].CanTrcvPartialNetworkConfig->CanTrcvPnEnabled) ; if (TRUE == stsValid) { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[trcv_index].CanTrcvSpiSequenceConfig; VALIDATE((E_OK == CanTrcv_Hw_EnablePN(spiSeq)), CANTRCV_SET_PNACTIVATIONSTATE_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); } else { ret = E_NOT_OK; } } } #else ret = E_NOT_OK; #endif return ret; } /** Requests to check the status of the wakeup flag from the transceiver hardware. */ /* @req SWS_CanTrcv_00223 **/ Std_ReturnType CanTrcv_CheckWakeFlag(uint8 Transceiver) { CanTrcv_TrcvWakeupReasonType reason; Std_ReturnType ret; boolean wakeupFlag; ret = E_OK; reason = CANTRCV_WU_NOT_SUPPORTED; wakeupFlag = FALSE; /* @req SWS_CanTrcv_00225 */ VALIDATE((Transceiver < CANTRCV_CHANNEL_COUNT), CANTRCV_CHECK_WAKEFLAG_ID, CANTRCV_E_INVALID_TRANSCEIVER, E_NOT_OK); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) const CanTrcv_SpiSequenceConfigType *spiSeq; if (FALSE == CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvEnableStatus) { ret = E_NOT_OK; } else { spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[Transceiver].CanTrcvSpiSequenceConfig; VALIDATE((E_OK == CanTrcv_Hw_ReadWakeupEventStatus(&reason,&wakeupFlag,spiSeq)), CANTRCV_CHECK_WAKEFLAG_ID, CANTRCV_E_NO_TRCV_CONTROL, E_NOT_OK); /* @req SWS_CanTrcv_00224 */ if (TRUE == wakeupFlag) { CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_CurWakeupFlag = TRUE; CanTrcv_Internal.CanTrcv_RuntimeData[Transceiver].CanTrcv_TrcvWakeupReason = reason; CanIf_CheckTrcvWakeFlagIndication(Transceiver); } } #else (void)reason; (void)wakeupFlag; ret = E_NOT_OK; #endif return ret; } /** Service to scan all busses for wake up events and perform these event. */ /* Note: If Can Transceiver controls the power supply stage then there is no need * of scheduling CanTrcv_MainFunction as the ECU enters low power mode when transceiver * is switched to sleep. */ /* @req SWS_CanTrcv_00013 **/ void CanTrcv_MainFunction(void) { /* @req SWS_CanTrcv_00128 */ VALIDATE((CanTrcv_Internal.initRun != FALSE), CANTRCV_MAINFUNCTION_ID, CANTRCV_E_UNINIT); #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) /* @req SWS_CanTrcv_00091 */ const CanTrcv_SpiSequenceConfigType *spiSeq; boolean wakeupFlag; CanTrcv_TrcvWakeupReasonType reason; CanTrcv_TrcvModeType mode; /* @req SWS_CanTrcv_00112 */ for(uint8 trcv = 0; trcv < CANTRCV_CHANNEL_COUNT; trcv++) { if ((CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupByBus) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvEnableStatus)) { mode = CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_TrcvCurMode; if ((CANTRCV_TRCVMODE_STANDBY == mode) || (CANTRCV_TRCVMODE_SLEEP == mode) || (CANTRCV_WUMODE_ENABLE == CanTrcv_Internal.CanTrcv_RuntimeData[trcv].CanTrcv_CurWakeupMode)) { wakeupFlag = FALSE; reason = CANTRCV_WU_NOT_SUPPORTED; spiSeq = CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSpiSequenceConfig; /* Check for wake up and report EcuM */ /* The following requirements are derived from EcuM fixed sequence dig 9.2.3 in ASR 4.0.3 */ (void)CanTrcv_Hw_ReadWakeupEventStatus(&reason,&wakeupFlag,spiSeq); if (wakeupFlag){ if ((CANTRCV_WU_BY_BUS == reason) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupSourceRef != CANTRCV_INVALID_WAKEUP_SOURCE)) { EcuM_CheckWakeup(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvWakeupSourceRef); } else if ((CANTRCV_WU_BY_SYSERR == reason) && (CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSyserrWakeupSourceRef != CANTRCV_INVALID_WAKEUP_SOURCE)) { EcuM_CheckWakeup(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvSyserrWakeupSourceRef); } else if ((CANTRCV_WU_BY_PIN == reason)|| (CANTRCV_WU_POWER_ON == reason)) { EcuM_CheckWakeup(CanTrcv_ConfigPtr->CanTrcvChannel[trcv].CanTrcvPorWakeupSourceRef); } else { /* Do nothing */ } } } } } /* end of for loop */ #endif } /** Reads the transceiver diagnostic status periodically and sets product/development accordingly. */ /* @req SWS_CanTrcv_00218 */ void CanTrcv_MainFunctionDiagnostics(void) { /* !req SWS_CanTrcv_00204 */ /* !req SWS_CanTrcv_00205 */ /* !req SWS_CanTrcv_00206 */ /* !req SWS_CanTrcv_00207 */ }
2301_81045437/classic-platform
drivers/CanTrcv/CanTrcv.c
C
unknown
38,333
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.1.2 */ /** @tagSettings DEFAULT_ARCHITECTURE=PPC*/ #ifndef CANTRCV_H_ #define CANTRCV_H_ #define CANTRCV_AR_RELEASE_MAJOR_VERSION 4 #define CANTRCV_AR_RELEASE_MINOR_VERSION 1 #define CANTRCV_AR_RELEASE_REVISION_VERSION 2 #define CANTRCV_VENDOR_ID 60 #define CANTRCV_MODULE_ID 70u #define CANTRCV_AR_MAJOR_VERSION CANTRCV_AR_RELEASE_MAJOR_VERSION #define CANTRCV_AR_MINOR_VERSION CANTRCV_AR_RELEASE_MINOR_VERSION #define CANTRCV_AR_PATCH_VERSION CANTRCV_AR_RELEASE_REVISION_VERSION #define CANTRCV_SW_MAJOR_VERSION 1 #define CANTRCV_SW_MINOR_VERSION 0 #define CANTRCV_SW_PATCH_VERSION 0 // API service with wrong parameterS /** @name Error Codes */ //@{ #define CANTRCV_E_INVALID_TRANSCEIVER 0x01 #define CANTRCV_E_PARAM_POINTER 0x02 #define CANTRCV_E_UNINIT 0x11 #define CANTRCV_E_TRCV_NOT_STANDBY 0x21 #define CANTRCV_E_TRCV_NOT_NORMAL 0x22 #define CANTRCV_E_PARAM_TRCV_WAKEUP_MODE 0x23 #define CANTRCV_E_PARAM_TRCV_OPMODE 0x24 #define CANTRCV_E_BAUDRATE_NOT_SUPPORTED 0x25 #define CANTRCV_E_NO_TRCV_CONTROL 0x26 //@} // Service IDs //@{ #define CANTRCV_INIT_ID 0x00 #define CANTRCV_SET_OPMODE_ID 0x01 #define CANTRCV_GET_OPMODE_ID 0x02 #define CANTRCV_GET_BUSWUREASON_ID 0x03 #define CANTRCV_GET_VERSIONINFO_ID 0x04 #define CANTRCV_SET_WAKEUPMODE_ID 0x05 #define CANTRCV_GET_TRCVSYSTEMDATA_ID 0x09 #define CANTRCV_CLEAR_TRCVWUFFLAG_ID 0x0a #define CANTRCV_READ_TRCVTIMEOUTFLAG_ID 0x0b #define CANTRCV_CLEAR_TRCVTIMEOUTFLAG_ID 0x0c #define CANTRCV_READ_TRCVSILENCEFLAG_ID 0x0d #define CANTRCV_CHECK_WAKEUP_ID 0x07 #define CANTRCV_SET_PNACTIVATIONSTATE_ID 0x0f #define CANTRCV_CHECK_WAKEFLAG_ID 0x0e #define CANTRCV_MAINFUNCTION_ID 0x06 #define CANTRCV_MAINFUNCTION_DIAGNOSTICS_ID 0x08 //@} /***** INCLUDES **************************************************************/ /* @req SWS_CanTrcv_00147 **/ #include "ComStack_Types.h" #include "Can_GeneralTypes.h" /* @req SWS_CanTrcv_00162 */ #include "Std_Types.h" #include "CanTrcv_ConfigTypes.h" #include "CanTrcv_Cfg.h" #include "CanTrcv_PBcfg.h" /***** PUBLIC TYPES **********************************************************/ /** Datatype used for describing whether PN wakeup functionality in * CanTrcv is enabled or disabled. */ typedef enum { /** PN wakeup functionality in CanTrcv is enabled. */ PN_ENABLED = 0, /** PN wakeup functionality in CanTrcv is disabled. */ PN_DISABLED } CanTrcv_PNActivationType; /** Provides the state of a flag in the transceiver hardware. */ typedef enum { /** The flag is set in the transceiver hardware. */ CANTRCV_FLAG_SET = 0, /** The flag is cleared in the transceiver hardware. */ CANTRCV_FLAG_CLEARED } CanTrcv_TrcvFlagStateType; /***** PUBLIC FUNCTIONS ******************************************************/ /** Initializes the CanTrcv module. */ /* @req SWS_CanTrcv_00001 **/ void CanTrcv_Init(const CanTrcv_ConfigType *ConfigPtr); /** Sets the mode of the Transceiver to the value OpMode. */ /* @req SWS_CanTrcv_00002 **/ Std_ReturnType CanTrcv_SetOpMode(uint8 Transceiver, CanTrcv_TrcvModeType OpMode); /** Gets the mode of the Transceiver and returns it in OpMode. */ /* @req SWS_CanTrcv_00005 **/ Std_ReturnType CanTrcv_GetOpMode(uint8 Transceiver, CanTrcv_TrcvModeType* OpMode); /** Gets the wakeup reason for the Transceiver and returns it in parameter Reason. */ /* @req SWS_CanTrcv_00007 **/ Std_ReturnType CanTrcv_GetBusWuReason(uint8 Transceiver, CanTrcv_TrcvWakeupReasonType* reason); /** Gets the version of the module and returns it in VersionInfo. */ /* @req SWS_CanTrcv_00008 **/ #if ( CANTRCV_GET_VERSION_INFO == STD_ON ) #define CanTrcv_GetVersionInfo(_vi) STD_GET_VERSION_INFO(_vi,CANTRCV) #endif /** Enables, disables or clears wake-up events of the Transceiver according to TrcvWakeupMode. */ /* @req SWS_CanTrcv_00009 */ Std_ReturnType CanTrcv_SetWakeupMode(uint8 Transceiver, CanTrcv_TrcvWakeupModeType TrcvWakeupMode); /** Reads the transceiver configuration/status data and returns it through para */ /* !req SWS_CanTrcv_00213 **/ Std_ReturnType CanTrcv_GetTrcvSystemData(uint8 Transceiver, uint32* TrcvSysData); /** Clears the WUF flag in the transceiver hardware. This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* @req SWS_CanTrcv_00214 **/ Std_ReturnType CanTrcv_ClearTrcvWufFlag(uint8 Transceiver); /** Reads the status of the timeout flag from the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* !req SWS_CanTrcv_00215 **/ Std_ReturnType CanTrcv_ReadTrcvTimeoutFlag(uint8 Transceiver, CanTrcv_TrcvFlagStateType* FlagState); /** Clears the status of the timeout flag in the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* !req . SWS_CanTrcv_00216 **/ Std_ReturnType CanTrcv_ClearTrcvTimeoutFlag(uint8 Transceiver); /** Reads the status of the silence flag from the transceiver hardware. * This API shall exist only if CanTrcvHwPnSupport = TRUE. */ /* @req SWS_CanTrcv_00217 **/ Std_ReturnType CanTrcv_ReadTrcvSilenceFlag(uint8 Transceiver, CanTrcv_TrcvFlagStateType* FlagState); /** Requests to check the status of the wakeup flag from the transceiver hardware. */ /* @req SWS_CanTrcv_00223 **/ Std_ReturnType CanTrcv_CheckWakeFlag(uint8 Transceiver); /** Service is called by underlying CANIF in case a wake up interrupt is detected. */ /* @req SWS_CanTrcv_00143 **/ Std_ReturnType CanTrcv_CheckWakeup(uint8 Transceiver); /** The API configures the wake-up of the transceiver for Standby and Sleep Mode: * Either the CAN transceiver is woken up by a remote wake-up pattern * (standard CAN wake-up) or by the configured remote wake-up frame. */ /* @req SWS_CanTrcv_00219 **/ Std_ReturnType CanTrcv_SetPNActivationState(CanTrcv_PNActivationType ActivationState); /** Service to scan all busses for wake up events and perform these event. */ /* @req SWS_CanTrcv_00013 **/ void CanTrcv_MainFunction(void); /** Reads the transceiver diagnostic status periodically and sets product/development accordingly. */ /* !req SWS_CanTrcv_00218 **/ void CanTrcv_MainFunctionDiagnostics(void); #endif /*CANTRCV_H_*/
2301_81045437/classic-platform
drivers/CanTrcv/CanTrcv.h
C
unknown
7,360
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef CANTRCV_CONFIGTYPES_H_ #define CANTRCV_CONFIGTYPES_H_ #include "EcuM_Types.h" /* * Defines use to identify the chosen device. * Parameter: CanTrcvGeneral/ArcCanTrcvDevice * * Values must be unique. */ #define TJA1145 0x1145 /** PnFrame Data Mask and Byte index for WUF */ typedef struct { uint8 CanTrcvPnFrameDataMask; uint8 CanTrcvPnFrameDataMaskIndex; }CanTrcv_PnFrameDataMaskConfigType; /** SpiSequence config type */ typedef struct { uint8 CanTrcvSpiSequenceName; uint8 CanTrcvSpiCmdChannel; uint8 CanTrcvSpiDataChannel; }CanTrcv_SpiSequenceConfigType; /** Config structure for Partial network frame */ typedef struct { const CanTrcv_PnFrameDataMaskConfigType* CanTrcvPnFrameDataMaskConfig; /* Mask for payload data & byte index in PN WUF */ uint32 CanTrcvPnFrameCanIdMask; /* Mask for CAN Ids, if multiple WUFs possible */ uint32 CanTrcvPnFrameCanId; /* CAN Id of PN WUF */ uint16 CanTrcvBaudRate; /* Baud rate value */ uint8 CanTrcvPnFrameDlc; /* DLC of PN WUF */ uint8 CanTrcvPnFrameDataMaskSize; boolean CanTrcvPnEnabled; /* PN Enable status */ boolean CanTrcvPnCanIdIsExtended; /* Whether channel uses extended CAN Id */ boolean CanTrcv_Arc_EOL; /* End of Line Indication */ } CanTrcv_PartialNetworkConfigType; /** Config structure for a CanTrcv Channel */ typedef struct { const CanTrcv_PartialNetworkConfigType* CanTrcvPartialNetworkConfig; /* Reference to PN struct */ const CanTrcv_SpiSequenceConfigType* CanTrcvSpiSequenceConfig; /* Reference to SPI config struct */ CanTrcv_TrcvModeType CanTrcvInitState; /* Initial mode of CanTrcv */ EcuM_WakeupSourceType CanTrcvWakeupSourceRef; /* Wake up source reference */ EcuM_WakeupSourceType CanTrcvPorWakeupSourceRef; /* wake up source reference for Power on */ EcuM_WakeupSourceType CanTrcvSyserrWakeupSourceRef; /* wake up source reference for trcv errors */ uint8 CanTrcvChannelId; /* Symbolic name of the channel */ boolean CanTrcvEnableStatus; /* Channel Enable/Disable */ boolean CanTrcvPnSupport; /* Hw supports selective wakeup by PN WUF */ boolean CanTrcvWakeupByBus; /* Hw supports wakeup on bus (wakeup patterns) */ boolean CanTrcv_Arc_EOL; /* End of Line Indication */ } Can_TrcvChannelType; typedef struct { const Can_TrcvChannelType* CanTrcvChannel; } CanTrcv_ConfigType; #endif /* CANTRCV_CONFIGTYPES_H_ */
2301_81045437/classic-platform
drivers/CanTrcv/CanTrcv_ConfigTypes.h
C
unknown
3,689
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "Spi.h" #include "CanTrcv.h" #define CAN_FRAME_MAX_DLC 8u #define SPI_GET_RESULT_MAX_TRY 5000u /* Maximum SPI Async transmit tries to read Transceiver status registers */ /* Macros for baud rate configuration */ #define CANTRCV_BAUD_RATE_50KBPS 50u #define CANTRCV_BAUD_RATE_100KBPS 100u #define CANTRCV_BAUD_RATE_125KBPS 125u #define CANTRCV_BAUD_RATE_250KBPS 250u #define CANTRCV_BAUD_RATE_500KBPS 500u #define CANTRCV_BAUD_RATE_1000KBPS 1000u struct CanTrcv_Internal_FrameBufType { uint8 FrameData[CAN_FRAME_MAX_DLC]; }; typedef struct { CanTrcv_TrcvModeType CanTrcv_TrcvCurMode; /* Channel mode */ #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) CanTrcv_TrcvWakeupReasonType CanTrcv_TrcvWakeupReason; /* Wake up reason */ CanTrcv_TrcvWakeupModeType CanTrcv_CurWakeupMode; /* Wake up mode */ boolean CanTrcv_CurWakeupFlag; /* Wake up flag*/ #endif } CanTrcv_Internal_ChannelRunTimeType; typedef struct { CanTrcv_Internal_ChannelRunTimeType CanTrcv_RuntimeData[CANTRCV_CHANNEL_COUNT]; boolean initRun; /* Init status */ }CanTrcv_InternalType; /* Internal Function definition */ #if (CANTRCV_WAKE_UP_SUPPORTED == STD_ON) /* Set baud rate */ Std_ReturnType CanTrcv_Hw_SetBaudRate(uint16 BaudRate,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Enable Partial networking selective wake up */ Std_ReturnType CanTrcv_Hw_EnablePN(const CanTrcv_SpiSequenceConfigType *spiSeq); /* Disable partial networking selective wake up */ Std_ReturnType CanTrcv_Hw_DisablePN(const CanTrcv_SpiSequenceConfigType *spiSeq); /* Configure partial networking selective wake up */ Std_ReturnType CanTrcv_Hw_SetupPN(const CanTrcv_PartialNetworkConfigType* partialNwConfig,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Read status of partial network configuration = success or failure */ Std_ReturnType CanTrcv_Hw_ReadPNConfigurationStatus(boolean * errConfigSts,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Clear wake up events */ Std_ReturnType CanTrcv_Hw_ClearWakeUpEventStatus(const CanTrcv_SpiSequenceConfigType *spiSeq); /* Read wake up events and this function implicitly clears the function */ Std_ReturnType CanTrcv_Hw_ReadWakeupEventStatus(CanTrcv_TrcvWakeupReasonType* reason,boolean * wakeupDetected,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Enable transceiver wake up events */ Std_ReturnType CanTrcv_Hw_EnableWakeUpEvent(const CanTrcv_SpiSequenceConfigType *spiSeq); /* Disable transceiver wake up events */ Std_ReturnType CanTrcv_Hw_DisableWakeUpEvent(const CanTrcv_SpiSequenceConfigType *spiSeq); #endif /* Set transceiver mode */ Std_ReturnType CanTrcv_Hw_SetupMode(CanTrcv_TrcvModeType state,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Read current transceiver mode */ Std_ReturnType CanTrcv_Hw_ReadCurrMode(CanTrcv_TrcvModeType* mode,const CanTrcv_SpiSequenceConfigType *spiSeq); /* Read current transceiver bus activity status */ Std_ReturnType CanTrcv_Hw_ReadSilenceFlag(CanTrcv_TrcvFlagStateType *flag,const CanTrcv_SpiSequenceConfigType *spiSeq);
2301_81045437/classic-platform
drivers/CanTrcv/CanTrcv_Internal.h
C
unknown
3,895
#CanTrcv vpath-$(USE_CANTRCV) += $(ROOTDIR)/drivers/CanTrcv inc-$(USE_CANTRCV) += $(ROOTDIR)/drivers/Can inc-$(USE_CANTRCV) += $(ROOTDIR)/drivers/CanTrcv obj-$(USE_CANTRCV) += CanTrcv.o obj-$(USE_CANTRCV) += CanTrcv_Cfg.o pb-obj-$(USE_CANTRCV) += CanTrcv_PBcfg.o pb-pc-file-$(USE_CANTRCV) += CanTrcv_Cfg.h CanTrcv_Cfg.c vpath-$(USE_CANTRCV)-$(CFG_TJA1145) += $(ROOTDIR)/arch/transceivers/tja1145 inc-$(USE_CANTRCV)-$(CFG_TJA1145) += $(ROOTDIR)/arch/transceivers/tja1145 obj-$(USE_CANTRCV)-$(CFG_TJA1145) += CanTrcv_TJA1145.o
2301_81045437/classic-platform
drivers/CanTrcv/cantrcv.mod.mk
Makefile
unknown
534
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @tagSettings DEFAULT_ARCHITECTURE=PPC|MPC5645S|MPC5607B */ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.1.2 */ //lint -save -e731 -e9033 // PC-Lint Exception : Lint + GHS compiler give strange warnings on the asserts. /* * IMPLEMENTATION NOTES * - The SPI implementation only supports 64 bytes in one go so this is * a limitation for the EEP driver also. * - The specification if SPI functions should be blocking or not. For now * the driver uses blocking SPI communication. * * CONFIG NOTES * Look at the 10.4 example in the 4.0 specs, quite good. * Normally the SPI E2 have a number of instructions: READ, WRITE, WRDI, WREN, etc * These instructions have can different sequences. For example WREN can be just * the instruction while WRIE consist of the WRITE instruction, an address and the * data to write. * * 1. Identify the channels. Best way to do that is to have a look at the E2 instruction * set and its sequences. Example: * READ : READ| ADDRESS | DATA | * bits 8 16 upto 32*8 * * WRITE: WRITE | ADDRESS | DATA * bits 8 16 upto 32*8 * * WREN: WREN * bits 8 * * RDSR: RDSR | DATA * 8 8 */ /* DEVICE SUPPORT * Microchip: * 25LC160 */ /* REQUIREMENTS * - EEP060 * Only EEP_WRITE_CYCLE_REDUCTION = STD_OFF is supported * * - EEP075 * MEMIF_COMPARE_UNEQUAL does not exist in the MemIf specification 1.2.1(rel 3.0 ) * So, it's not supported. It returns MEMIF_JOB_FAILED instead. * * - EEP084 * EepJobCallCycle not used * We are not using interrupts so EEP_USE_INTERRUPTS must be STD_OFF */ #include "Eep.h" #include "Spi.h" #if defined(USE_DEM) #include "Dem.h" #endif #if defined(USE_DET) #include "Det.h" #endif #include <stdlib.h> #include "arc_assert.h" #include <string.h> //#define USE_LDEBUG_PRINTF 1 #include "debug.h" #define MODULE_NAME "/driver/Eep" // Define if you to check if the E2 seems sane at init.. //#define CFG_EEP_CHECK_SANE 1 /* The width in bytes used by this eeprom */ #define ADDR_LENGTH 2 /* Helper macro for the process function */ #define PROC_SET_STATE(_done,_state) done=(_done);job->state=(_state) #define DONE TRUE #define NOT_DONE FALSE #if ( EEP_DEV_ERROR_DETECT == STD_ON ) // Report DEV errors #define VALIDATE(_exp,_api,_err ) \ if( !(_exp) ) { \ (void)Det_ReportError(EEP_MODULE_ID,0,_api,_err); \ return; \ } #define VALIDATE_W_RV(_exp,_api,_err,_rv ) \ if( !(_exp) ) { \ (void)Det_ReportError(EEP_MODULE_ID,0,_api,_err); \ return (_rv); \ } #define VALID_CHANNEL(_ch) ( Gpt_Global.configured & (1<<(_ch)) ) #else // Validate but do not report #define VALIDATE(_exp,_api,_err )\ if( !(_exp) ) { \ return; \ } #define VALIDATE_W_RV(_exp,_api,_err,_rv )\ if( !(_exp) ) { \ return (_rv); \ } #endif #if ( EEP_DEV_ERROR_DETECT == STD_ON ) #define VALIDATE_CONFIG(_x) CONFIG_ASSERT(_x) #define DET_REPORTERROR(_x,_y,_z,_q) (void)Det_ReportError(EEP_MODULE_ID, _y, _z, _q) #else #define VALIDATE_CONFIG(_x) #define DET_REPORTERROR(_x,_y,_z,_q) #endif #define EEP_JOB_END_NOTIFICATION() \ if (Eep_Global.config->Eep_JobEndNotification!=NULL) { \ Eep_Global.config->Eep_JobEndNotification(); \ } #define EEP_JOB_ERROR_NOTIFICATION() \ if (Eep_Global.config->Eep_JobErrorNotification!=NULL) { \ Eep_Global.config->Eep_JobErrorNotification(); \ } /* Job state */ typedef enum { EEP_NONE, EEP_COMPARE, EEP_ERASE, EEP_READ, EEP_WRITE, } Eep_Arc_JobType; /* Spi job state */ typedef enum { JOB_MAIN, JOB_READ_STATUS, JOB_READ_STATUS_RESULT, } Job_StateType; /* Information about a job */ typedef struct { uint8 *targetAddr; Eep_AddressType eepAddr; uint32 left; Job_StateType state; Eep_Arc_JobType mainState; Spi_SequenceType currSeq; uint32 chunkSize; uint32 pageSize; boolean initialOp; } Eep_JobInfoType; #define JOB_SET_STATE(_x,_y) job->state=(_x);job->mainState=(_y) /* * Holds all global information that is needed by the driver * */ typedef struct { // The configuration const Eep_ConfigType *config; // Status of driver MemIf_StatusType status; MemIf_JobResultType jobResultType; Eep_Arc_JobType jobType; // Data containers for EB buffers Spi_DataBufferType ebCmd; Spi_DataBufferType ebReadStatus; uint16 ebE2Addr; // What mode we are in ( normal/fast ) MemIf_ModeType mode; // Hold job information Eep_JobInfoType job; } Eep_GlobalType; #if 0 // Use SPI synchronous transmit #define SPI_TRANSMIT_FUNC(_x, _y) Spi_SyncTransmit(_x) #else // Use SPI asynchronous transmit #define SPI_TRANSMIT_FUNC(_x,_y) Eep_AsyncTransmit(_x,_y) Std_ReturnType Eep_AsyncTransmit(Spi_SequenceType Sequence, Eep_JobInfoType *job); Std_ReturnType Eep_AsyncTransmit(Spi_SequenceType Sequence, Eep_JobInfoType *job) { Std_ReturnType rv; // Null-pointer guard if (job == NULL) { DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_GLOBAL_SERVICE_ID, EEP_E_PARAM_POINTER); return E_NOT_OK; } job->currSeq = Sequence; rv = Spi_AsyncTransmit(Sequence); return rv; } #endif #define CFG_SPI_P() Eep_Global.config->externalDriver Eep_GlobalType Eep_Global; #if (EEP_VERSION_INFO_API == STD_ON) void Eep_GetVersionInfo(Std_VersionInfoType* versioninfo) { VALIDATE( !(versioninfo == NULL), EEP_GETVERSIONINFO_ID, EEP_E_PARAM_POINTER ); versioninfo->vendorID = EEP_VENDOR_ID; versioninfo->moduleID = EEP_MODULE_ID; versioninfo->sw_major_version = EEP_SW_MAJOR_VERSION; versioninfo->sw_minor_version = EEP_SW_MINOR_VERSION; versioninfo->sw_patch_version = EEP_SW_PATCH_VERSION; return; } #endif /** * Converts Eep_AddressType to one that can be read by SPI( Spi_DataBufferType ) * * @param spiAddr Pointer to an address were the result is written. * @param eepAddr The Eep address to convert */ static void convertToSpiAddr(Spi_DataBufferType *spiAddr, Eep_AddressType eepAddr) { // Null-pointer guard if (spiAddr == NULL) { DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_GLOBAL_SERVICE_ID, EEP_E_PARAM_POINTER); return; } *(uint16 *)spiAddr = (uint16)eepAddr; // spiAddr[1] = (Spi_DataBufferType)((eepAddr) & 0xffUL); // spiAddr[0] = (Spi_DataBufferType)((eepAddr >> 8) & 0xffUL); } #if defined(CFG_EEP_CHECK_SANE) static void commandWREN(void) { Eep_Global.ebCmd = E2_WREN; (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, NULL, NULL, 1); (void)Spi_SyncTransmit(CFG_SPI_P()->EepCmdSequence); } static void commandWRDI(void) { Eep_Global.ebCmd = E2_WRDI; (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, NULL, NULL, 1); (void)Spi_SyncTransmit(CFG_SPI_P()->EepCmdSequence); } static uint8 readStatusReg(void) { (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, NULL, &Eep_Global.ebReadStatus, 1); Eep_Global.ebCmd = E2_RDSR; (void)Spi_SyncTransmit(CFG_SPI_P()->EepCmd2Sequence); return Eep_Global.ebReadStatus; } #endif void Eep_Init(const Eep_ConfigType* ConfigPtr) { VALIDATE( (ConfigPtr != NULL), EEP_INIT_ID, EEP_E_PARAM_CONFIG); VALIDATE( ( Eep_Global.status != MEMIF_BUSY ), EEP_INIT_ID, EEP_E_BUSY); Eep_Global.config = ConfigPtr; (void)Spi_SetupEB(CFG_SPI_P()->EepCmdChannel, &Eep_Global.ebCmd, NULL, 1u); (void)Spi_SetupEB(CFG_SPI_P()->EepAddrChannel, (Spi_DataBufferType *)&Eep_Global.ebE2Addr, NULL, 1 ); (void)Spi_SetupEB(CFG_SPI_P()->EepWrenChannel, NULL, NULL, 1); #if defined( CFG_EEP_CHECK_SANE ) { uint8 status; // Simple check, // - write WREN, // - check if 1 by reading with RDSR, // - write WRDE // - check if 0 by reading with RDSR, commandWREN(); status = readStatusReg(); ASSERT(!((status & 0x2u) == 0)); (void)status; /* Misra compliance */ commandWRDI(); status = readStatusReg(); ASSERT(!((status & 0x2u) > 0)); (void)status; /* Misra compliance */ } #endif Eep_Global.status = MEMIF_IDLE; Eep_Global.jobResultType = MEMIF_JOB_OK; Eep_SetMode(Eep_Global.config->EepDefaultMode); } void Eep_SetMode(MemIf_ModeType Mode) { VALIDATE( ( Eep_Global.status != MEMIF_UNINIT ), EEP_SETMODE_ID, EEP_E_UNINIT); VALIDATE( ( Eep_Global.status != MEMIF_BUSY ), EEP_SETMODE_ID, EEP_E_BUSY); VALIDATE( ( (Mode == MEMIF_MODE_SLOW) || (Mode == MEMIF_MODE_FAST) ), EEP_SETMODE_ID, EEP_E_PARAM_DATA); Eep_Global.mode = Mode; } Std_ReturnType Eep_Read(Eep_AddressType EepromAddress, uint8 *DataBufferPtr, Eep_LengthType Length) { Eep_JobInfoType *job = &Eep_Global.job; VALIDATE_W_RV( ( Eep_Global.status != MEMIF_UNINIT ), EEP_READ_ID, EEP_E_UNINIT, E_NOT_OK); VALIDATE_W_RV( ( Eep_Global.status != MEMIF_BUSY ), EEP_READ_ID, EEP_E_BUSY, E_NOT_OK); /** @req SWS_Eep_00016 */ VALIDATE_W_RV( ( DataBufferPtr != NULL ), EEP_READ_ID, EEP_E_PARAM_DATA, E_NOT_OK); /** @req SWS_Eep_00017 */ VALIDATE_W_RV( ( (EepromAddress) < (Eep_Global.config->EepSize) ), EEP_READ_ID, EEP_E_PARAM_ADDRESS, E_NOT_OK); /** @req SWS_Eep_00018 */ VALIDATE_W_RV( ( (Length >= 1u) && ((Eep_Global.config->EepSize - EepromAddress) >= Length) ), EEP_READ_ID, EEP_E_PARAM_LENGTH, E_NOT_OK); Eep_Global.status = MEMIF_BUSY; Eep_Global.jobResultType = MEMIF_JOB_PENDING; Eep_Global.jobType = EEP_READ; if (Eep_Global.mode == MEMIF_MODE_FAST) { job->chunkSize = Eep_Global.config->EepFastReadBlockSize; } else { job->chunkSize = Eep_Global.config->EepNormalReadBlockSize; } job->initialOp = TRUE; job->currSeq = CFG_SPI_P()->EepReadSequence; job->eepAddr = EepromAddress + Eep_Global.config->EepBaseAddress; job->targetAddr = DataBufferPtr; job->left = Length; JOB_SET_STATE(JOB_MAIN, EEP_READ); return E_OK; } Std_ReturnType Eep_Erase(Eep_AddressType EepromAddress, Eep_LengthType Length) { VALIDATE_W_RV( ( Eep_Global.status != MEMIF_UNINIT ), EEP_ERASE_ID, EEP_E_UNINIT, E_NOT_OK); VALIDATE_W_RV( ( Eep_Global.status != MEMIF_BUSY ), EEP_ERASE_ID, EEP_E_BUSY, E_NOT_OK); /** @req SWS_Eep_00017 */ VALIDATE_W_RV( ( (EepromAddress) < (Eep_Global.config->EepSize) ), EEP_ERASE_ID, EEP_E_PARAM_ADDRESS, E_NOT_OK); /** @req SWS_Eep_00018 */ VALIDATE_W_RV( ( (Length >= 1u) && ((Eep_Global.config->EepSize - EepromAddress) >= Length) ), EEP_ERASE_ID, EEP_E_PARAM_LENGTH, E_NOT_OK); /* IMPROVEMENT : NOT IMPLEMENTED * ( Since this E2 do not have erase ) * */ Std_ReturnType rv = E_NOT_OK; Eep_Global.status = MEMIF_BUSY; Eep_Global.status = MEMIF_IDLE; return rv; } Std_ReturnType Eep_Write(Eep_AddressType EepromAddress, const uint8* DataBufferPtr, Eep_LengthType Length) { Eep_JobInfoType *job = &Eep_Global.job; VALIDATE_W_RV( ( Eep_Global.status != MEMIF_UNINIT ), EEP_WRITE_ID, EEP_E_UNINIT, E_NOT_OK); VALIDATE_W_RV( ( Eep_Global.status != MEMIF_BUSY ), EEP_WRITE_ID, EEP_E_BUSY, E_NOT_OK); /** @req SWS_Eep_00016 */ VALIDATE_W_RV( ( DataBufferPtr != NULL ), EEP_WRITE_ID, EEP_E_PARAM_DATA, E_NOT_OK); /** @req SWS_Eep_00017 */ VALIDATE_W_RV( ( (EepromAddress) < (Eep_Global.config->EepSize) ), EEP_WRITE_ID, EEP_E_PARAM_ADDRESS, E_NOT_OK); /** @req SWS_Eep_00018 */ VALIDATE_W_RV( ( (Length >= 1u) && (Length <= (Eep_Global.config->EepSize - EepromAddress)) ), EEP_WRITE_ID, EEP_E_PARAM_LENGTH, E_NOT_OK); Eep_Global.jobResultType = MEMIF_JOB_PENDING; Eep_Global.status = MEMIF_BUSY; Eep_Global.jobType = EEP_WRITE; if (Eep_Global.mode == MEMIF_MODE_FAST) { job->chunkSize = Eep_Global.config->EepFastWriteBlockSize; } else { job->chunkSize = Eep_Global.config->EepNormalWriteBlockSize; } job->initialOp = TRUE; job->currSeq = CFG_SPI_P()->EepWriteSequence; job->pageSize = Eep_Global.config->EepPageSize; job->eepAddr = EepromAddress + Eep_Global.config->EepBaseAddress; job->targetAddr = (uint8 *)DataBufferPtr; /*lint !e926 !e9005 Used for both read and write in the implementation */ job->left = Length; JOB_SET_STATE(JOB_MAIN, EEP_WRITE); return E_OK; } Std_ReturnType Eep_Compare(Eep_AddressType EepromAddress, const uint8 *DataBufferPtr, Eep_LengthType Length) { Eep_JobInfoType *job = &Eep_Global.job; VALIDATE_W_RV( ( Eep_Global.status != MEMIF_UNINIT ), EEP_COMPARE_ID, EEP_E_UNINIT, E_NOT_OK); VALIDATE_W_RV( ( Eep_Global.status != MEMIF_BUSY ), EEP_COMPARE_ID, EEP_E_BUSY, E_NOT_OK); /** @req SWS_Eep_00016 */ VALIDATE_W_RV( ( DataBufferPtr != NULL ), EEP_COMPARE_ID, EEP_E_PARAM_DATA, E_NOT_OK); /** @req SWS_Eep_00017 */ VALIDATE_W_RV( ( (EepromAddress) < (Eep_Global.config->EepSize) ), EEP_COMPARE_ID, EEP_E_PARAM_ADDRESS, E_NOT_OK); /** @req SWS_Eep_00018 */ VALIDATE_W_RV( ( (Length >= 1u) && ((Eep_Global.config->EepSize - EepromAddress) >= Length) ), EEP_COMPARE_ID, EEP_E_PARAM_LENGTH, E_NOT_OK); Eep_Global.status = MEMIF_BUSY; Eep_Global.jobResultType = MEMIF_JOB_PENDING; Eep_Global.jobType = EEP_COMPARE; /* This is a compare job but the compare jobs really issues read in portions * big enough to fit it's static buffers */ if (Eep_Global.mode == MEMIF_MODE_FAST) { job->chunkSize = Eep_Global.config->EepFastReadBlockSize; } else { job->chunkSize = Eep_Global.config->EepNormalReadBlockSize; } job->initialOp = TRUE; job->currSeq = CFG_SPI_P()->EepReadSequence; job->pageSize = Eep_Global.config->EepPageSize; // Not relevant to compare/read operations, but set anyways. job->eepAddr = EepromAddress + Eep_Global.config->EepBaseAddress; job->targetAddr = (uint8 *)DataBufferPtr; /*lint !e926 !e9005 Used for both read and write in the implementation */ job->left = Length; JOB_SET_STATE(JOB_MAIN, EEP_COMPARE); return E_OK; } void Eep_Cancel(void) { EEP_JOB_ERROR_NOTIFICATION(); if (MEMIF_JOB_PENDING == Eep_Global.jobResultType) { Eep_Global.jobResultType = MEMIF_JOB_CANCELED; } Eep_Global.status = MEMIF_IDLE; } MemIf_StatusType Eep_GetStatus(void) { return Eep_Global.status; } MemIf_JobResultType Eep_GetJobResult(void) { return Eep_Global.jobResultType; } /** * Function that process read/write/erase requests to the SPI * * @param job The present job */ static Spi_SeqResultType processJob(Eep_JobInfoType *job) { // Null-pointer guard if (job == NULL) { DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_GLOBAL_SERVICE_ID, EEP_E_PARAM_POINTER); return SPI_SEQ_FAILED; } Spi_SeqResultType rv; boolean done = 0; uint32 chunkSize = 0; uint32 sizeLeftInPage = 0; rv = Spi_GetSequenceResult(job->currSeq); if( job->initialOp ) { ASSERT( rv != SPI_SEQ_PENDING ); ASSERT( job->state == JOB_MAIN ); job->initialOp = FALSE; } else { if( rv != SPI_SEQ_OK ) { return rv; } } rv = SPI_SEQ_PENDING; do { switch (job->state) { case JOB_READ_STATUS: DEBUG(DEBUG_LOW,"%s: READ_STATUS\n",MODULE_NAME); /* Check status from erase cmd, read status from flash */ (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, NULL, &Eep_Global.ebReadStatus, 1); Eep_Global.ebCmd = E2_RDSR; if (SPI_TRANSMIT_FUNC(CFG_SPI_P()->EepCmd2Sequence,job ) == E_OK) { PROC_SET_STATE(DONE, JOB_READ_STATUS_RESULT); } else { PROC_SET_STATE(DONE, JOB_READ_STATUS); } break; case JOB_READ_STATUS_RESULT: DEBUG(DEBUG_LOW,"%s: READ_STATUS_RESULT\n",MODULE_NAME); /* Check WIP (Write in Progress) bit */ if ((Eep_Global.ebReadStatus & 1UL) > 0) { /* Still not done */ PROC_SET_STATE(NOT_DONE, JOB_READ_STATUS); } else { PROC_SET_STATE(NOT_DONE, JOB_MAIN); } break; case JOB_MAIN: if (job->left > 0) { if (job->left <= job->chunkSize) { chunkSize = job->left; } else { chunkSize = job->chunkSize; } convertToSpiAddr((Spi_DataBufferType *)&Eep_Global.ebE2Addr, job->eepAddr); boolean spiTransmitOK = FALSE; switch (job->mainState) { case EEP_ERASE: /* NOT USED */ break; case EEP_READ: case EEP_COMPARE: DEBUG(DEBUG_LOW,"%s: READ s:%04x d:%04x l:%04x\n",MODULE_NAME,job->eepAddr, job->targetAddr, job->left); Eep_Global.ebCmd = E2_READ; (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, NULL, job->targetAddr, (Spi_NumberOfDataType)chunkSize); if (SPI_TRANSMIT_FUNC(CFG_SPI_P()->EepReadSequence,job) == E_OK) { spiTransmitOK = TRUE; } break; case EEP_WRITE: DEBUG(DEBUG_LOW,"%s: WRITE d:%04x s:%04x first data:%02x\n",MODULE_NAME,job->eepAddr,job->targetAddr,*job->targetAddr); // Calculate how much space there is left in the current EEPROM page. sizeLeftInPage = job->pageSize - (job->eepAddr % job->pageSize); // Handle EEPROM page boundaries, i.e. make sure that we limit the chunk // size so we don't write over the page boundary. if (chunkSize > sizeLeftInPage) { chunkSize = sizeLeftInPage; } else { // Do nothing since the size of the chunk to write is less than the // available space left in the page. } Eep_Global.ebCmd = E2_WRITE; convertToSpiAddr((Spi_DataBufferType *)&Eep_Global.ebE2Addr, job->eepAddr); (void)Spi_SetupEB(CFG_SPI_P()->EepDataChannel, job->targetAddr, NULL, (Spi_NumberOfDataType)chunkSize); if (SPI_TRANSMIT_FUNC(CFG_SPI_P()->EepWriteSequence,job ) == E_OK) { spiTransmitOK = TRUE; } break; default: ASSERT(0); break; } if (spiTransmitOK) { job->eepAddr += chunkSize; job->targetAddr = &job->targetAddr[chunkSize]; job->left -= chunkSize; /* We have sent the data, now check for the WIP (Write In Progress) * bit to become 0 */ PROC_SET_STATE(DONE, JOB_READ_STATUS); } else { PROC_SET_STATE(DONE, JOB_MAIN); } } else { /* We are done :) */ PROC_SET_STATE(DONE, JOB_MAIN); job->mainState = EEP_NONE; rv = SPI_SEQ_OK; } break; default: ASSERT(0); break; } } while (!done); return rv; } #define CMP_BUFF_SIZE SPI_EB_MAX_LENGTH void Eep_MainFunction(void) { Spi_SeqResultType jobResult; if (Eep_Global.jobResultType == MEMIF_JOB_PENDING) { switch (Eep_Global.jobType) { case EEP_COMPARE: { static Eep_JobInfoType readJob; static uint8 Eep_CompareBuffer[SPI_EB_MAX_LENGTH]; Eep_JobInfoType *gJob = &Eep_Global.job; static boolean firstTime = TRUE; static uint32 readSize; /* Compare jobs must use a local buffer to hold one portion * of the job. Since processJob() also manipulates the * job structure we need to create a new local job each time. * The global job updates is updated for each process job. */ if (firstTime) { readJob = *gJob; if (gJob->left <= CMP_BUFF_SIZE) { readSize = gJob->left; } else { readSize = CMP_BUFF_SIZE; } readJob.left = readSize; readJob.targetAddr = Eep_CompareBuffer; firstTime = FALSE; } jobResult = processJob(&readJob); if (jobResult == SPI_SEQ_PENDING) { /* Do nothing */ } else if (jobResult == SPI_SEQ_OK) { if (memcmp(Eep_CompareBuffer, gJob->targetAddr, (size_t)readSize) != 0) { /*lint !e746 String.h is included, lint bug in combination with ghs. */ DET_REPORTERROR(EEP_MODULE_ID, 0, 0x9, (uint8)MEMIF_JOB_FAILED); EEP_JOB_ERROR_NOTIFICATION(); return; } // Update the global compare job gJob->targetAddr = &gJob->targetAddr[readSize]; gJob->eepAddr += readSize; gJob->left -= readSize; // Check if we are done if (gJob->left == 0) { Eep_Global.jobResultType = MEMIF_JOB_OK; Eep_Global.jobType = EEP_NONE; Eep_Global.status = MEMIF_IDLE; EEP_JOB_END_NOTIFICATION(); firstTime = TRUE; return; } // Calculate new readSize if (gJob->left <= CMP_BUFF_SIZE) { readSize = gJob->left; } else { readSize = CMP_BUFF_SIZE; } // Update the readjob for next session readJob = *gJob; readJob.left = readSize; readJob.targetAddr = Eep_CompareBuffer; } else { // all other cases are bad firstTime = TRUE; Eep_Global.jobResultType = MEMIF_JOB_FAILED; Eep_Global.jobType = EEP_NONE; Eep_Global.status = MEMIF_IDLE; DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_COMPARE_ID, (uint8)MEMIF_JOB_FAILED); EEP_JOB_ERROR_NOTIFICATION(); } } break; case EEP_ERASE: case EEP_READ: case EEP_WRITE: jobResult = processJob(&Eep_Global.job); if (jobResult == SPI_SEQ_OK) { Eep_Global.jobResultType = MEMIF_JOB_OK; Eep_Global.jobType = EEP_NONE; Eep_Global.status = MEMIF_IDLE; EEP_JOB_END_NOTIFICATION(); } else if (jobResult == SPI_SEQ_PENDING) { /* Busy, Do nothing */ } else { // Error Eep_Arc_JobType failedJobType = Eep_Global.jobType; Eep_Global.jobResultType = MEMIF_JOB_FAILED; Eep_Global.jobType = EEP_NONE; Eep_Global.status = MEMIF_IDLE; switch (failedJobType) { case EEP_ERASE: DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_ERASE_ID, (uint8)MEMIF_JOB_FAILED); break; case EEP_READ: DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_READ_ID, (uint8)MEMIF_JOB_FAILED); break; case EEP_WRITE: DET_REPORTERROR(EEP_MODULE_ID, 0, EEP_WRITE_ID, (uint8)MEMIF_JOB_FAILED); break; default: ASSERT(0); } EEP_JOB_ERROR_NOTIFICATION(); } break; case EEP_NONE: ASSERT(0); break; default: break; /* Misra compliance */ } } } //lint -restore
2301_81045437/classic-platform
drivers/Eep/Eep.c
C
unknown
25,598
#Eep obj-$(USE_EEP) += Eep.o obj-$(USE_EEP) += Eep_Lcfg.o inc-$(USE_EEP)-$(if $(CFG_JACINTO)$(CFG_RH850)$(CFG_MPC55XX)$(CFG_MPC56XX)$(CFG_TMS570),y) += $(ROOTDIR)/drivers/Eep vpath-$(USE_EEP)-$(if $(CFG_JACINTO)$(CFG_RH850)$(CFG_MPC55XX)$(CFG_MPC56XX)$(CFG_TMS570),y) += $(ROOTDIR)/drivers/Eep
2301_81045437/classic-platform
drivers/Eep/Eep.mod.mk
Makefile
unknown
301
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.1.2 */ /** @tagSettings DEFAULT_ARCHITECTURE=PPC|TMS570|MPC5607B|MPC5645S|ZYNQ|MPC5748G */ #ifndef FLS_H_ #define FLS_H_ /** @req SWS_Fls_00248 */ #include "Std_Types.h" #define FLS_VENDOR_ID 60u #define FLS_MODULE_ID 92u #define FLS_SW_MAJOR_VERSION 2u #define FLS_SW_MINOR_VERSION 0u #define FLS_SW_PATCH_VERSION 0u #define FLS_AR_RELEASE_MAJOR_VERSION 4u #define FLS_AR_RELEASE_MINOR_VERSION 1u #define FLS_AR_RELEASE_PATCH_VERSION 2u // Development errors /** @req SWS_Fls_00004 */ #define FLS_E_PARAM_CONFIG 0x01u #define FLS_E_PARAM_ADDRESS 0x02u #define FLS_E_PARAM_LENGTH 0x03u #define FLS_E_PARAM_DATA 0x04u #define FLS_E_UNINIT 0x05u #define FLS_E_BUSY 0x06u #define FLS_E_VERIFY_ERASE_FAILED 0x07u /** !req SWS_Fls_00314 */ #define FLS_E_VERIFY_WRITE_FAILED 0x08u #define FLS_E_TIMEOUT 0x09u #define FLS_E_PARAM_POINTER 0x0Au /* ArcCore extra errors */ #define FLS_E_INVALID_AREA 0x10u #define FLS_E_UNEXPECTED_EXECUTION 0x11u // Service id's for fls functions #define FLS_INIT_ID 0x00 #define FLS_ERASE_ID 0x01 #define FLS_WRITE_ID 0x02 #define FLS_CANCEL_ID 0x03 #define FLS_GET_STATUS_ID 0x04 #define FLS_GET_JOB_RESULT_ID 0x05 #define FLS_MAIN_FUNCTION_ID 0x06 #define FLS_READ_ID 0x07 #define FLS_COMPARE_ID 0x08 #define FLS_SET_MODE_ID 0x09 #define FLS_GET_VERSION_INFO_ID 0x10 // Used as address offset from the configured flash base address to access a certain // flash memory area. /** @req SWS_Fls_00369 */ /** @req SWS_Fls_00216 */ typedef uint32 Fls_AddressType; // Specifies the number of bytes to read/write/erase/compare // // Note! // Shall be the same type as Fls_AddressType because of // arithmetic operations. Size depends on target platform and // flash device. /** @req SWS_Fls_00370 */ typedef uint32 Fls_LengthType; /** @req SWS_Fls_00309 */ #if !defined(FLS_INCLUDE_FILE) #include "Fls_Cfg.h" /** * Initializes the Flash Driver. * * @param ConfigPtr Pointer to flash driver configuration set. */ /** @req SWS_Fls_00249 */ void Fls_Init(const Fls_ConfigType *ConfigPtr); /** * Erases flash sector(s). * * @param TargetAddress Target address in flash memory. * This address offset will be * added to the flash memory base address. * Min.: 0 * Max.: FLS_SIZE - 1 * * @param Length Number of bytes to erase * Min.: 1 * Max.: FLS_SIZE - TargetAddress * * @return E_OK: erase command has been accepted * E_NOT_OK: erase command has not been accepted */ /** @req SWS_Fls_00250 */ Std_ReturnType Fls_Erase(Fls_AddressType TargetAddress, Fls_LengthType Length); /** @req SWS_Fls_00251 */ Std_ReturnType Fls_Write(Fls_AddressType TargetAddress, const uint8 *SourceAddressPtr, Fls_LengthType Length); #if ( FLS_CANCEL_API == STD_ON ) /** @req SWS_Fls_00252 */ void Fls_Cancel( void ); #endif #if ( FLS_GET_STATUS_API == STD_ON ) /** @req SWS_Fls_00253 */ MemIf_StatusType Fls_GetStatus(void); #endif #if ( FLS_GET_JOB_RESULT_API == STD_ON ) /** @req SWS_Fls_00254 */ MemIf_JobResultType Fls_GetJobResult(void); #endif /** @req SWS_Fls_00255 */ /** @req SWS_Fls_00269 */ void Fls_MainFunction(void); /** @req SWS_Fls_00256 */ Std_ReturnType Fls_Read(Fls_AddressType SourceAddress, uint8 *TargetAddressPtr, Fls_LengthType Length); #if ( FLS_COMPARE_API == STD_ON ) /** @req SWS_Fls_00257 */ Std_ReturnType Fls_Compare(Fls_AddressType SourceAddress, const uint8 *TargetAddressPtr, Fls_LengthType Length); #endif #if ( FLS_SET_MODE_API == STD_ON ) /** @req SWS_Fls_00258 */ /** @req SWS_Fls_00187 */ void Fls_SetMode(MemIf_ModeType Mode); #endif #if ( FLS_VERSION_INFO_API == STD_ON ) /** @req SWS_Fls_00259 */ void Fls_GetVersionInfo(Std_VersionInfoType *VersioninfoPtr); #endif #if defined(CFG_ZYNQ) typedef enum { FLS_JOB_NONE, FLS_JOB_COMPARE, FLS_JOB_ERASE, FLS_JOB_READ, FLS_JOB_WRITE, }Fls_Arc_JobType; /** * Gets values of internal variables for debugging * @param modstat * @param moduleMode * @param jobResult * @param jobPending * @param jobAddr * @param jobLen * @param jobPointer */ void Fls_Arc_Internal(MemIf_StatusType *modstat, MemIf_ModeType *moduleMode, MemIf_JobResultType *jobResult,Fls_Arc_JobType *jobPending, Fls_AddressType *jobAddr,Fls_LengthType *jobLen, const uint8** jobPointer); #endif #else #include FLS_INCLUDE_FILE #endif #endif /*FLS_H_*/
2301_81045437/classic-platform
drivers/Fls/Fls.h
C
unknown
5,546
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef FLS_CONFIGTYPES_H_ #define FLS_CONFIGTYPES_H_ #if (USE_FLS_INFO==STD_ON) typedef struct Flash { uint32 size; uint32 sectCnt; uint32 bankSize; uint32 regBase; uint32 sectAddr[FLASH_MAX_SECTORS+1]; uint16 addrSpace[FLASH_MAX_SECTORS+1]; } FlashType; #else typedef struct { Fls_LengthType FlsNumberOfSectors; Fls_LengthType FlsPageSize; Fls_LengthType FlsSectorSize; Fls_AddressType FlsSectorStartaddress; } Fls_SectorType; #endif struct Flash; typedef struct { void (*FlsAcErase)(void); /* NO SUPPORT */ void (*FlsAcWrite)(void); /* NO SUPPORT */ // FlsCallCycle N/A in core. void (*FlsJobEndNotification)(void); void (*FlsJobErrorNotification)(void); uint32 FlsMaxReadFastMode; uint32 FlsMaxReadNormalMode; uint32 FlsMaxWriteFastMode; uint32 FlsMaxWriteNormalMode; uint32 FlsProtection; /* NO SUPPORT */ #if (USE_FLS_INFO==STD_ON) const struct Flash *FlsInfo; #else const Fls_SectorType *FlsSectorList; const uint32 FlsSectorListSize; /* NO SUPPORT */ #endif } Fls_ConfigSetType; typedef Fls_ConfigSetType Fls_ConfigType; extern const Fls_ConfigSetType FlsConfigSet[]; #endif /* FLS_CONFIGTYPES_H_ */
2301_81045437/classic-platform
drivers/Fls/Fls_ConfigTypes.h
C
unknown
2,028
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #if 1 /* CONFIGURATION NOTES * The configuration is simple, use the template supplied. * Changing the configuration is NOT recommended. */ /* REQUIREMENTS: * - Variant PB is supported not PC ( FLS203,FLS204 ) * - Since DEM is NOT supported all those requirements are not supported. * - AC is not supported since it makes no sense for a SPI flash. * */ /* IMPLEMENTATION NOTES * - The only SPI flash supported is the SST25VF016B although the * entire SST25XX should work through configuration changes * - Commands that are used by this module are: * WREN,WRDI,WRSR,byte write and erase 4K * - AC is not supported since the there's no use for it. * - Supports 64 bytes read, byte write and 4K erase * - The implementation very much dependent on the configuration * of the SPI( Spi_Cfg.c ) * - Calls from SPI are not checked( Only makes sense if DEM is supported ) * */ #include "MemIf.h" #define FLS_INCLUDE_FILE "Fls_SST25xx.h" #include "Fls.h" #include "Spi.h" #if defined(USE_DET) #include "Det.h" #endif #if defined(USE_DEM) #include "Dem.h" #endif #include <stdlib.h> #include "arc_assert.h" //#include <stdio.h> #include <string.h> //#define USE_LDEBUG_PRINTF #include "debug.h" #define MODULE_NAME "/driver/Fls_25" /* RDID data for S25FL040A */ #define DEVICE_RDID 0x010212 /* 0x12 - Uniform, 0x25- Top boot, 0x28-bottom boot */ #define FLASH_READ_25 0x03 #define FLASH_READ_50 0x0B #define FLASH_RDSR 0x05 #define FLASH_JEDEC_ID 0x9f #define FLASH_RDID 0x90 #define FLASH_BYTE_WRITE 0x02 #define FLASH_AI_WORD_WRITE 0xad #define FLASH_WREN 0x06 #define FLASH_WRDI 0x04 #define FLASH_WRSR 0x01 #define FLASH_ERASE_4K 0xd8 /* The width in bytes used by this flash */ #define ADDR_LENGTH 3 /* Helper macro for the process function */ #define SET_STATE(_done,_state) done=(_done);job->state=(_state) /* How many loops to wait for SPI to go back to "normal" state after * read/write/erase */ #define TIMER_BUSY_WAIT 100000 #if FLS_SST25XX_DEV_ERROR_DETECT #define FLS_VALIDATE_PARAM_ADDRESS_SECTOR_W_RV(_addr, _api, _rv)\ int sectorIndex;\ int addrOk=0;\ Fls_SectorType sector;\ for (sectorIndex=0; sectorIndex<Fls_SST25xx_Global.config->FlsSectorListSize;sectorIndex++) {\ sector = Fls_SST25xx_Global.config->FlsSectorList[sectorIndex];\ if((((uint32)_addr-sector.FlsSectorStartaddress) / sector.FlsSectorSize)<sector.FlsNumberOfSectors){\ /* Within the right adress space */\ if (!(((uint32)_addr-sector.FlsSectorStartaddress) % sector.FlsSectorSize)){\ /* Address is correctly aligned */\ addrOk=1;\ break;\ }\ }\ }\ if (1!=addrOk){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_PARAM_ADDRESS ); \ return _rv; \ } #define FLS_VALIDATE_PARAM_ADDRESS_PAGE_W_RV(_addr, _api, _rv)\ int sectorIndex;\ int addrOk=0;\ Fls_SectorType sector;\ for (sectorIndex=0; sectorIndex<Fls_SST25xx_Global.config->FlsSectorListSize;sectorIndex++) {\ sector = Fls_SST25xx_Global.config->FlsSectorList[sectorIndex];\ if((((uint32)_addr-sector.FlsSectorStartaddress) / sector.FlsSectorSize)<sector.FlsNumberOfSectors){\ /* Within the right adress space */\ if (!(((uint32)_addr-sector.FlsSectorStartaddress) % sector.FlsPageSize)){\ /* Address is correctly aligned */\ addrOk=1;\ break;\ }\ }\ }\ if (1!=addrOk){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_PARAM_ADDRESS ); \ return _rv; \ } #define FLS_VALIDATE_PARAM_LENGTH_PAGE_W_RV(_addr, _length, _api, _rv)\ int i;\ int lengthOk=0;\ const Fls_SectorType* sectorPtr= &Fls_SST25xx_Global.config->FlsSectorList[0];\ for (i=0; i<Fls_SST25xx_Global.config->FlsSectorListSize;i++) {\ if ((sectorPtr->FlsSectorStartaddress + (sectorPtr->FlsNumberOfSectors * sectorPtr->FlsSectorSize))>=(uint32_t)(_addr+(_length))){\ if ((0!=_length)&&!(_length % sectorPtr->FlsPageSize)){\ lengthOk=1;\ break;\ }\ }\ sectorPtr++;\ }\ if (!lengthOk){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_PARAM_LENGTH ); \ return _rv; \ } #define FLS_VALIDATE_PARAM_LENGTH_SECTOR_W_RV(_addr, _length, _api, _rv)\ int i;\ int lengthOk=0;\ const Fls_SectorType* sectorPtr= &Fls_SST25xx_Global.config->FlsSectorList[0];\ for (i=0; i<Fls_SST25xx_Global.config->FlsSectorListSize;i++) {\ if ((sectorPtr->FlsSectorStartaddress + (sectorPtr->FlsNumberOfSectors * sectorPtr->FlsSectorSize))>=(uint32_t)(_addr+(_length))){\ if ((0!=_length)&& !(_length % sectorPtr->FlsSectorSize)){\ lengthOk=1;\ break;\ }\ }\ sectorPtr++;\ }\ if (!lengthOk){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_PARAM_LENGTH ); \ return _rv; \ } #define FLS_VALIDATE_STATUS_UNINIT_W_RV(_status, _api, _rv)\ if (MEMIF_UNINIT == _status){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_UNINIT); \ return _rv; \ } #define FLS_VALIDATE_STATUS_BUSY(_status, _api)\ if (MEMIF_BUSY == _status){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_BUSY); \ return; \ } #define FLS_VALIDATE_STATUS_BUSY_W_RV(_status, _api, _rv)\ if (MEMIF_BUSY == _status){\ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_BUSY); \ return _rv; \ } #define FLS_VALIDATE_PARAM_DATA_W_RV(_ptr,_api, _rv) \ if( (_ptr)==((void *)0)) { \ Det_ReportError(FLS_MODULE_ID,0,_api,FLS_E_PARAM_DATA); \ return _rv; \ } #else #define FLS_VALIDATE_PARAM_ADDRESS_SECTOR_W_RV(_addr, _api, _rv) #define FLS_VALIDATE_PARAM_ADDRESS_PAGE_W_RV(_addr, _api, _rv) #define FLS_VALIDATE_PARAM_LENGTH_SECTOR_W_RV(_addr, _length, _api, _rv) #define FLS_VALIDATE_PARAM_LENGTH_PAGE_W_RV(_addr, _length, _api, _rv) #define FLS_VALIDATE_STATUS_UNINIT_W_RV(_status, _api, _rv) #define FLS_VALIDATE_STATUS_BUSY(_status, _api) #define FLS_VALIDATE_STATUS_BUSY_W_RV(_status, _api, _rv) #define FLS_VALIDATE_PARAM_DATA_W_RV(_ptr,_api,_rv) #endif #if ( FLS_DEV_ERROR_DETECT == STD_ON ) #define VALIDATE_CONFIG(_x) CONFIG_ASSERT(_x) #define DET_REPORTERROR(_x,_y,_z,_q) Det_ReportError(FLS_MODULE_ID, _y, _z, _q) #else #define VALIDATE_CONFIG(_x) #define DET_REPORTERROR(_x,_y,_z,_q) #endif #if ( FLS_GET_JOB_RESULT_API == STD_ON ) #define FEE_JOB_END_NOTIFICATION() \ if( Fls_SST25xx_Global.config->FlsJobEndNotification != NULL ) { \ Fls_SST25xx_Global.config->FlsJobEndNotification(); \ } #define FEE_JOB_ERROR_NOTIFICATION() \ if( Fls_SST25xx_Global.config->FlsJobErrorNotification != NULL ) { \ Fls_SST25xx_Global.config->FlsJobErrorNotification(); \ } #else #define FEE_JOB_END_NOTIFICATION() #define FEE_JOB_ERROR_NOTIFICATION() #endif #if ( FLS_SST25XX_DEV_ERROR_DETECT == STD_ON ) // Report DEV errors #define VALIDATE(_exp,_api,_err ) \ if( !(_exp) ) { \ Det_ReportError(FLS_MODULE_ID,0,_api,_err); \ return; \ } #endif #define VALIDATE_W_RV(_exp,_api,_err,_rv ) \ if( !(_exp) ) { \ Det_ReportError(FLS_MODULE_ID,0,_api,_err); \ return (_rv); \ } #define VALID_CHANNEL(_ch) ( Gpt_Global.configured & (1<<(_ch)) ) #else // Validate but do not report #define VALIDATE(_exp,_api,_err )\ if( !(_exp) ) { \ return; \ } #define VALIDATE_W_RV(_exp,_api,_err,_rv )\ if( !(_exp) ) { \ return (_rv); \ } #endif const Fls_ConfigType* _Fls_SST25xx_ConfigPtr; #if ( FLS_SST25XX_VERSION_INFO_API == STD_ON ) static Std_VersionInfoType Fls_SST25XX_VersionInfo = { .vendorID = (uint16)FLS_VENDOR_ID, .moduleID = (uint16) FLS_MODULE_ID, /* Vendor numbers */ .sw_major_version = (uint8)FLS_SST25XX_SW_MAJOR_VERSION, .sw_minor_version = (uint8)FLS_SST25XX_SW_MINOR_VERSION, .sw_patch_version = (uint8)FLS_SST25XX_SW_PATCH_VERSION, }; #endif /* Job state */ typedef enum { FLS_SST25XX_NONE, FLS_SST25XX_COMPARE, FLS_SST25XX_ERASE, FLS_SST25XX_READ, FLS_SST25XX_WRITE, } Fls_SST25xx_Arc_JobType; /* Spi job state */ typedef enum { JOB_MAIN, JOB_READ_STATUS, JOB_READ_STATUS_RESULT, } Job_StateType; /* Information about a job */ typedef struct { uint8 *targetAddr; Fls_AddressType flsAddr; uint32 left; Job_StateType state; Fls_SST25xx_Arc_JobType mainState; Spi_SequenceType currSeq; uint32 chunkSize; boolean initialOp; } Fls_SST25xx_JobInfoType; #define JOB_SET_STATE(_x,_y) job->state=(_x);job->mainState=(_y) typedef struct { const Fls_ConfigType *config; // Status of driver MemIf_StatusType status; MemIf_JobResultType jobResultType; Fls_SST25xx_Arc_JobType jobType; // Saved information from API calls. Fls_AddressType flsAddr; uint8 *targetAddr; Fls_LengthType length; // Data containers for EB buffers Spi_DataBufferType ebCmd; Spi_DataBufferType ebReadStatus; Spi_DataBufferType ebFlsAddr[ADDR_LENGTH]; // What mode we are in ( normal/fast ) MemIf_ModeType mode; // Hold job information Fls_SST25xx_JobInfoType job; } Fls_SST25xx_GlobalType; Fls_SST25xx_GlobalType Fls_SST25xx_Global; #if 0 #define SPI_TRANSMIT_FUNC(_x) Spi_SyncTransmit(_x) #else #define SPI_TRANSMIT_FUNC(_x,_y) Fls_SST25xx_AsyncTransmit(_x,_y) Std_ReturnType Fls_SST25xx_AsyncTransmit(Spi_SequenceType Sequence,Fls_SST25xx_JobInfoType *job) { Std_ReturnType rv; job->currSeq = Sequence; rv = Spi_AsyncTransmit(Sequence); return rv; } #endif /** * Convert Fls_AddressType to something used by SPI * * @param spiAddr Address to convert to SPI address * @param addr Pointer to the SPI address to be written * */ static void Spi_ConvertToSpiAddr(Spi_DataBufferType *spiAddr, Fls_AddressType addr ) { spiAddr[0] = (addr>>16)&0xff; // MSB first spiAddr[1] = (addr>>8)&0xff; spiAddr[2] = (addr)&0xff; } /** * Get configuration sector information from a flash address * * @param addr The address */ static const Fls_SectorType * Fls_SST25xx_GetSector( Fls_AddressType addr ) { int sectorIndex; const Fls_SectorType *sector; for (sectorIndex=0; sectorIndex<Fls_SST25xx_Global.config->FlsSectorListSize;sectorIndex++) { sector = &Fls_SST25xx_Global.config->FlsSectorList[sectorIndex]; if((((uint32)addr-sector->FlsSectorStartaddress) / sector->FlsSectorSize)<sector->FlsNumberOfSectors){ return sector; } } ASSERT(0); return NULL; } void Fls_SST25xx_Init( const Fls_ConfigType* ConfigPtr ){ FLS_VALIDATE_STATUS_BUSY(Fls_SST25xx_Global.status, FLS_INIT_ID); #if ( FLS_SST25XX_VARIANT_PB == STD_ON ) VALIDATE( (ConfigPtr != NULL) , FLS_INIT_ID, FLS_E_PARAM_CONFIG ); #endif Fls_SST25xx_Global.config = ConfigPtr; Spi_DataBufferType data = 0; int timer = 0; Std_ReturnType rv = E_OK; Spi_DataBufferType jedecId[3]; // Do some basic testing of configuration data, FLS205 VALIDATE_CONFIG(ConfigPtr->FlsMaxReadFastMode != 0 ); VALIDATE_CONFIG(ConfigPtr->FlsMaxReadNormalMode != 0 ); VALIDATE_CONFIG(ConfigPtr->FlsMaxWriteFastMode != 0 ); VALIDATE_CONFIG(ConfigPtr->FlsMaxWriteNormalMode != 0 ); VALIDATE_CONFIG(ConfigPtr->FlsAcWrite == NULL ); // NOT supported VALIDATE_CONFIG(ConfigPtr->FlsAcErase == NULL ); // NOT supported // Setup External buffers for jobs and sequences Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_CMD, &Fls_SST25xx_Global.ebCmd,NULL,sizeof(Fls_SST25xx_Global.ebCmd)/sizeof(Fls_SST25xx_Global.ebCmd)); Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_ADDR, Fls_SST25xx_Global.ebFlsAddr,NULL,sizeof(Fls_SST25xx_Global.ebFlsAddr)/sizeof(Fls_SST25xx_Global.ebFlsAddr[0])); Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_WREN, NULL,NULL,1); Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_WRDI, NULL,NULL,1); Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_WRSR, NULL,NULL,1); /* Check that the JEDEC ID can be read */ Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, NULL ,jedecId,3); Fls_SST25xx_Global.ebCmd = FLASH_JEDEC_ID; Spi_SyncTransmit(SpiConf_SpiSequence_SEQ_FLASH_CMD_DATA ); if( ((jedecId[0]<<16) + (jedecId[1]<<8) + jedecId[2]) != DEVICE_RDID ) { LDEBUG_PRINTF("JEDEC: %02x %02x %02x\n",jedecId[0],jedecId[1],jedecId[2]); } /* The flash comes locked from factory so it must be unlocked. * The unlock is done in here instead before each write to reduce overhead. * ( The flash is still protected by WREN ) */ /* Unlock flash with sync API. */ Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, &data, NULL,1); rv = Spi_SyncTransmit(SpiConf_SpiSequence_SEQ_FLASH_WRSR); // Busy wait Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, NULL, &Fls_SST25xx_Global.ebReadStatus, 1); do { Fls_SST25xx_Global.ebCmd = FLASH_RDSR; Spi_SyncTransmit(SpiConf_SpiSequence_SEQ_FLASH_CMD2); timer++; } while( (Fls_SST25xx_Global.ebReadStatus != 0) && (timer < TIMER_BUSY_WAIT )); ASSERT(timer!=TIMER_BUSY_WAIT); Fls_SST25xx_Global.status = MEMIF_IDLE; Fls_SST25xx_Global.jobResultType = MEMIF_JOB_PENDING; // Set currSeq to any sequence we use Fls_SST25xx_Global.job.currSeq = SpiConf_SpiSequence_SEQ_FLASH_WRSR; } #if ( FLS_SST25XX_SET_MODE_API == STD_ON ) void Fls_SST25xx_SetMode( MemIf_ModeType Mode ){ VALIDATE( ( Fls_SST25xx_Global.status != MEMIF_UNINIT ), FLS_SET_MODE_ID, FLS_E_UNINIT ); VALIDATE( ( Fls_SST25xx_Global.status != MEMIF_BUSY ), FLS_SET_MODE_ID, FLS_E_BUSY ); Fls_SST25xx_Global.mode = Mode; } #endif Std_ReturnType Fls_SST25xx_Read ( Fls_AddressType SourceAddress, uint8 *TargetAddressPtr, Fls_LengthType Length ) { Fls_SST25xx_JobInfoType *job = &Fls_SST25xx_Global.job; FLS_VALIDATE_STATUS_UNINIT_W_RV(Fls_SST25xx_Global.status, FLS_READ_ID, E_NOT_OK); FLS_VALIDATE_STATUS_BUSY_W_RV(Fls_SST25xx_Global.status, FLS_READ_ID, E_NOT_OK); FLS_VALIDATE_PARAM_ADDRESS_PAGE_W_RV(SourceAddress, FLS_READ_ID, E_NOT_OK); FLS_VALIDATE_PARAM_LENGTH_PAGE_W_RV(SourceAddress, Length, FLS_READ_ID, E_NOT_OK); FLS_VALIDATE_PARAM_DATA_W_RV((void*)TargetAddressPtr, FLS_READ_ID, E_NOT_OK) Fls_SST25xx_Global.status = MEMIF_BUSY; Fls_SST25xx_Global.jobResultType = MEMIF_JOB_PENDING; Fls_SST25xx_Global.jobType = FLS_SST25XX_READ; if( Fls_SST25xx_Global.mode == MEMIF_MODE_FAST ) { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxReadFastMode; } else { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxReadNormalMode; } job->initialOp = true; job->currSeq = SpiConf_SpiSequence_SEQ_FLASH_READ; job->flsAddr = SourceAddress; job->targetAddr = TargetAddressPtr; job->left = Length; JOB_SET_STATE(JOB_MAIN,FLS_SST25XX_READ); return E_OK; } Std_ReturnType Fls_SST25xx_Erase( Fls_AddressType TargetAddress, Fls_LengthType Length ){ Fls_SST25xx_JobInfoType *job = &Fls_SST25xx_Global.job; FLS_VALIDATE_STATUS_UNINIT_W_RV(Fls_SST25xx_Global.status, FLS_ERASE_ID, E_NOT_OK); FLS_VALIDATE_STATUS_BUSY_W_RV(Fls_SST25xx_Global.status, FLS_ERASE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_ADDRESS_SECTOR_W_RV(TargetAddress, FLS_ERASE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_LENGTH_SECTOR_W_RV(TargetAddress, Length, FLS_ERASE_ID, E_NOT_OK); Fls_SST25xx_Global.status = MEMIF_BUSY; Fls_SST25xx_Global.jobResultType = MEMIF_JOB_PENDING; Fls_SST25xx_Global.jobType = FLS_SST25XX_ERASE; job->initialOp = true; job->currSeq = SpiConf_SpiSequence_SEQ_FLASH_WRITE; job->flsAddr = TargetAddress; // Not used, so set to illegal value job->targetAddr = (uint8 *)0; job->left = Length; job->chunkSize = Fls_SST25xx_GetSector(TargetAddress)->FlsSectorSize; JOB_SET_STATE(JOB_MAIN,FLS_SST25XX_ERASE); return E_OK; } Std_ReturnType Fls_SST25xx_Write( Fls_AddressType TargetAddress, const uint8* SourceAddressPtr, Fls_LengthType Length ){ Fls_SST25xx_JobInfoType *job = &Fls_SST25xx_Global.job; FLS_VALIDATE_STATUS_UNINIT_W_RV(Fls_SST25xx_Global.status, FLS_WRITE_ID, E_NOT_OK); FLS_VALIDATE_STATUS_BUSY_W_RV(Fls_SST25xx_Global.status, FLS_WRITE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_ADDRESS_PAGE_W_RV(TargetAddress, FLS_WRITE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_LENGTH_PAGE_W_RV(TargetAddress, Length, FLS_WRITE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_DATA_W_RV(SourceAddressPtr, FLS_WRITE_ID, E_NOT_OK) Fls_SST25xx_Global.jobResultType = MEMIF_JOB_PENDING; Fls_SST25xx_Global.status = MEMIF_BUSY; Fls_SST25xx_Global.jobType = FLS_SST25XX_WRITE; if( Fls_SST25xx_Global.mode == MEMIF_MODE_FAST ) { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxWriteFastMode; } else { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxWriteNormalMode; } job->initialOp = true; job->currSeq = SpiConf_SpiSequence_SEQ_FLASH_WRITE; job->flsAddr = TargetAddress; job->targetAddr = (uint8 *)SourceAddressPtr; job->left = Length; JOB_SET_STATE(JOB_MAIN,FLS_SST25XX_WRITE); return E_OK; } Std_ReturnType Fls_SST25xx_Compare( Fls_AddressType SourceAddress, uint8 *TargetAddressPtr, Fls_LengthType Length ) { Fls_SST25xx_JobInfoType *job = &Fls_SST25xx_Global.job; FLS_VALIDATE_STATUS_UNINIT_W_RV(Fls_SST25xx_Global.status, FLS_COMPARE_ID, E_NOT_OK); FLS_VALIDATE_STATUS_BUSY_W_RV(Fls_SST25xx_Global.status, FLS_COMPARE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_ADDRESS_PAGE_W_RV(SourceAddress, FLS_COMPARE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_LENGTH_PAGE_W_RV(SourceAddress, Length, FLS_COMPARE_ID, E_NOT_OK); FLS_VALIDATE_PARAM_DATA_W_RV((void*)SourceAddress,FLS_COMPARE_ID, E_NOT_OK) Fls_SST25xx_Global.status = MEMIF_BUSY; Fls_SST25xx_Global.jobResultType = MEMIF_JOB_PENDING; Fls_SST25xx_Global.jobType = FLS_SST25XX_COMPARE; /* This is a compare job but the compare jobs really issues read in portions * big enough to fit it's static buffers */ if( Fls_SST25xx_Global.mode == MEMIF_MODE_FAST ) { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxReadFastMode; } else { job->chunkSize = Fls_SST25xx_Global.config->FlsMaxReadNormalMode; } job->flsAddr = SourceAddress; job->targetAddr = TargetAddressPtr; job->left = Length; JOB_SET_STATE(JOB_MAIN,FLS_SST25XX_COMPARE); return E_OK; } #if ( FLS_SST25XX_CANCEL_API == STD_ON ) /* API NOT SUPPORTED */ void Fls_SST25xx_Cancel( void ){ if (Fls_SST25xx_Global.config->FlsJobEndNotification!=NULL) Fls_SST25xx_Global.config->FlsJobEndNotification(); if (MEMIF_JOB_PENDING==Fls_SST25xx_Global.jobResultType) { Fls_SST25xx_Global.jobResultType=MEMIF_JOB_CANCELED; } Fls_SST25xx_Global.status = MEMIF_IDLE; } #endif #if ( FLS_SST25XX_GET_STATUS_API == STD_ON ) MemIf_StatusType Fls_SST25xx_GetStatus( void ){ return Fls_SST25xx_Global.status; } #endif MemIf_JobResultType Fls_SST25xx_GetJobResult( void ){ return Fls_SST25xx_Global.jobResultType; } /** * Function that process read/write/erase requests to the SPI * * @param job The present job */ static Spi_SeqResultType Fls_SST25xx_ProcessJob( Fls_SST25xx_JobInfoType *job ) { Spi_SeqResultType rv; _Bool done = 0; rv = Spi_GetSequenceResult(job->currSeq); if( job->initialOp ) { ASSERT( rv != SPI_SEQ_PENDING ); ASSERT( job->state == JOB_MAIN ); job->initialOp = false; } else { if( rv != SPI_SEQ_OK ) { return rv; } } rv = SPI_SEQ_PENDING; do { switch(job->state ) { case JOB_READ_STATUS: DEBUG(DEBUG_LOW,"%s: READ_STATUS\n",MODULE_NAME); /* Check status from erase cmd, read status from flash */ Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, NULL, &Fls_SST25xx_Global.ebReadStatus, 1); Fls_SST25xx_Global.ebCmd = FLASH_RDSR; if( SPI_TRANSMIT_FUNC(SpiConf_SpiSequence_SEQ_FLASH_CMD2,job ) != E_OK ) { ASSERT(0); } SET_STATE(1,JOB_READ_STATUS_RESULT); break; case JOB_READ_STATUS_RESULT: DEBUG(DEBUG_LOW,"%s: READ_STATUS_RESULT\n",MODULE_NAME); if( Fls_SST25xx_Global.ebReadStatus&1 ) { SET_STATE(0,JOB_READ_STATUS); } else { SET_STATE(0,JOB_MAIN); } break; case JOB_MAIN: if( job->left != 0 ) { if( job->left <= job->chunkSize ) { job->chunkSize = job->left; } Spi_ConvertToSpiAddr(Fls_SST25xx_Global.ebFlsAddr,job->flsAddr); switch(job->mainState) { case FLS_SST25XX_ERASE: DEBUG(DEBUG_LOW,"%s: Erase 4K s:%04x\n",MODULE_NAME,job->flsAddr); Fls_SST25xx_Global.ebCmd = FLASH_ERASE_4K; SPI_TRANSMIT_FUNC(SpiConf_SpiSequence_SEQ_FLASH_ERASE,job ); break; case FLS_SST25XX_READ: case FLS_SST25XX_COMPARE: DEBUG(DEBUG_LOW,"%s: READ s:%04x d:%04x l:%04x\n",MODULE_NAME,job->flsAddr, job->targetAddr, job->left); Fls_SST25xx_Global.ebCmd = FLASH_READ_25; Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, NULL ,job->targetAddr,job->chunkSize); SPI_TRANSMIT_FUNC(SpiConf_SpiSequence_SEQ_FLASH_READ,job ); break; case FLS_SST25XX_WRITE: DEBUG(DEBUG_LOW,"%s: WRITE d:%04x s:%04x first data:%02x\n",MODULE_NAME,job->flsAddr,job->targetAddr,*job->targetAddr); Fls_SST25xx_Global.ebCmd = FLASH_BYTE_WRITE; Spi_ConvertToSpiAddr(Fls_SST25xx_Global.ebFlsAddr,job->flsAddr); Spi_SetupEB( SpiConf_SpiChannel_CH_FLASH_DATA, job->targetAddr, NULL, job->chunkSize); SPI_TRANSMIT_FUNC(SpiConf_SpiSequence_SEQ_FLASH_WRITE,job ); break; default: ASSERT(0); break; } job->flsAddr += job->chunkSize; job->targetAddr += job->chunkSize; job->left -= job->chunkSize; SET_STATE(1,JOB_READ_STATUS); } else { /* We are done :) */ SET_STATE(1,JOB_MAIN); job->mainState = FLS_SST25XX_NONE; rv = SPI_SEQ_OK; } break; default: ASSERT(0); break; } } while(!done); return rv; } #define CMP_BUFF_SIZE SPI_EB_MAX_LENGTH void Fls_SST25xx_MainFunction( void ) { Spi_SeqResultType jobResult; if( Fls_SST25xx_Global.jobResultType == MEMIF_JOB_PENDING ) { switch (Fls_SST25xx_Global.jobType) { case FLS_SST25XX_COMPARE: { static Fls_SST25xx_JobInfoType readJob; static uint8 Fls_SST25xx_CompareBuffer[SPI_EB_MAX_LENGTH]; Fls_SST25xx_JobInfoType *gJob = &Fls_SST25xx_Global.job; static _Bool firstTime = 1; static uint32 readSize; /* Compare jobs must use a local buffer to hold one portion * of the job. Since Fls_SST25xx_ProcessJob() also manipulates the * job structure we need to create a new local job each time. * The global job updates is updated for each process job. */ if (firstTime == 1) { readJob = *gJob; if ( gJob->left <= CMP_BUFF_SIZE ) { readSize = gJob->left; } else { readSize = CMP_BUFF_SIZE; } readJob.left = readSize; readJob.targetAddr = Fls_SST25xx_CompareBuffer; firstTime = 0; } jobResult = Fls_SST25xx_ProcessJob(&readJob); if( jobResult == SPI_SEQ_PENDING ) { /* Do nothing */ } else if( jobResult == SPI_SEQ_OK ) { if( memcmp(Fls_SST25xx_CompareBuffer,gJob->targetAddr, readSize) != 0 ) { #if defined(USE_DEM) Dem_ReportErrorStatus(DemConf_DemEventParameter_FLS_E_COMPARE_FAILED, DEM_EVENT_STATUS_FAILED); #endif FEE_JOB_ERROR_NOTIFICATION(); return; } // Update the global comare job gJob->targetAddr += readSize; gJob->flsAddr += readSize; gJob->left -= readSize; // Check if we are done if( gJob->left == 0 ) { Fls_SST25xx_Global.jobResultType = MEMIF_JOB_OK; Fls_SST25xx_Global.jobType = FLS_SST25XX_NONE; Fls_SST25xx_Global.status = MEMIF_IDLE; FEE_JOB_END_NOTIFICATION(); firstTime = 1; return; } // Calculate new readSize if ( gJob->left <= CMP_BUFF_SIZE ) { readSize = gJob->left; } else { readSize = CMP_BUFF_SIZE; } // Update the readjob for next session readJob = *gJob; readJob.left = readSize; readJob.targetAddr = Fls_SST25xx_CompareBuffer; } else { // all other cases are bad firstTime = 1; Fls_SST25xx_Global.jobResultType = MEMIF_JOB_FAILED; Fls_SST25xx_Global.jobType = FLS_SST25XX_NONE; Fls_SST25xx_Global.status = MEMIF_IDLE; #if defined(USE_DEM) Dem_ReportErrorStatus(DemConf_DemEventParameter_FLS_E_COMPARE_FAILED, DEM_EVENT_STATUS_FAILED); #endif FEE_JOB_ERROR_NOTIFICATION(); } } break; case FLS_SST25XX_ERASE: case FLS_SST25XX_READ: case FLS_SST25XX_WRITE: jobResult = Fls_SST25xx_ProcessJob(&Fls_SST25xx_Global.job); if( jobResult == SPI_SEQ_OK ) { Fls_SST25xx_Global.jobResultType = MEMIF_JOB_OK; Fls_SST25xx_Global.jobType = FLS_SST25XX_NONE; Fls_SST25xx_Global.status = MEMIF_IDLE; FEE_JOB_END_NOTIFICATION(); } else if( jobResult == SPI_SEQ_PENDING ) { /* Busy, Do nothing */ } else { // Error Fls_SST25xx_Global.jobResultType = MEMIF_JOB_FAILED; switch(Fls_SST25xx_Global.jobType) { case FLS_SST25XX_ERASE: #if defined(USE_DEM) Dem_ReportErrorStatus(DemConf_DemEventParameter_FLS_E_ERASED_FAILED, DEM_EVENT_STATUS_FAILED); #endif break; case FLS_SST25XX_READ: #if defined(USE_DEM) Dem_ReportErrorStatus(DemConf_DemEventParameter_FLS_E_READ_FAILED, DEM_EVENT_STATUS_FAILED); #endif break; case FLS_SST25XX_WRITE: #if defined(USE_DEM) Dem_ReportErrorStatus(DemConf_DemEventParameter_FLS_E_WRITE_FAILED, DEM_EVENT_STATUS_FAILED); #endif break; default: ASSERT(0); } FEE_JOB_ERROR_NOTIFICATION(); } break; case FLS_SST25XX_NONE: ASSERT(0); break; } } } #if ( FLS_SST25XX_VERSION_INFO_API == STD_ON ) void Fls_SST25XX_GetVersionInfo( Std_VersionInfoType *VersioninfoPtr ) { memcpy(VersioninfoPtr, &Fls_SST25XX_VersionInfo, sizeof(Std_VersionInfoType)); } #endif
2301_81045437/classic-platform
drivers/Fls/Fls_SST25xx.c
C
unknown
28,809
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef FLS_SST25XX_H_ #define FLS_SST25XX_H_ // Only if external flash device //#include "Spi.h" #include "Std_Types.h" #if defined(USE_DET) #include "Det.h" #endif #include "Fls.h" #include "MemIf_Types.h" // SW ans Autosar spec versions #define FLS_SST25XX_SW_MAJOR_VERSION 1 #define FLS_SST25XX_SW_MINOR_VERSION 0 #define FLS_SST25XX_SW_PATCH_VERSION 0 #define FLS_SST25XX_AR_MAJOR_VERSION 3 #define FLS_SST25XX_AR_MINOR_VERSION 0 #define FLS_SST25XX_AR_PATCH_VERSION 2 #if 0 // Used as address offset from the configured flash base address to access a certain // flash memory area. typedef uint32 Fls_AddressType; // Specifies the number of bytes to read/write/erase/compare // // Note! // Shall be the same type as Fls_AddressType because of // arithmetic operations. Size depends on target platform and // flash device. typedef uint32 Fls_LengthType; #endif #include "Fls_SST25xx_Cfg.h" /** * Initializes the Flash Driver. * * @param ConfigPtr Pointer to flash driver configuration set. */ void Fls_SST25xx_Init( const Fls_ConfigType *ConfigPtr ); /** * Erases flash sector(s). * * @param TargetAddress Target address in flash memory. * This address offset will be * added to the flash memory base address. * Min.: 0 * Max.: FLS_SIZE - 1 * * @param Length Number of bytes to erase * Min.: 1 * Max.: FLS_SIZE - TargetAddress * * @return E_OK: erase command has been accepted * E_NOT_OK: erase command has not been accepted */ #if 0 typedef uint32 Fls_AddressType; // Specifies the number of bytes to read/write/erase/compare // // Note! // Shall be the same type as Fls_AddressType because of // arithmetic operations. Size depends on target platform and // flash device. typedef uint32 Fls_LengthType; #endif Std_ReturnType Fls_SST25xx_Erase( Fls_AddressType TargetAddress, Fls_LengthType Length ); Std_ReturnType Fls_SST25xx_Write ( Fls_AddressType TargetAddress, const uint8 *SourceAddressPtr, Fls_LengthType Length ); #if ( FLS_CANCEL_API == STD_ON ) void Fls_SST25xx_Cancel( void ); #endif MemIf_StatusType Fls_SST25xx_GetStatus( void ); MemIf_JobResultType Fls_SST25xx_GetJobResult( void ); void Fls_SST25xx_MainFunction( void ); Std_ReturnType Fls_SST25xx_Read ( Fls_AddressType SourceAddress, uint8 *TargetAddressPtr, Fls_LengthType Length ); #if ( FLS_COMPARE_API == STD_ON ) Std_ReturnType Fls_SST25xx_Compare( Fls_AddressType SourceAddress, uint8 *TargetAddressPtr, Fls_LengthType Length ); #endif #if ( FLS_SET_MODE_API == STD_ON ) void Fls_SST25xx_SetMode( MemIf_ModeType Mode ); #endif void Fls_SST25xx_GetVersionInfo( Std_VersionInfoType *VersioninfoPtr ); #endif /* FLS_SST25XX_H_ */
2301_81045437/classic-platform
drivers/Fls/Fls_SST25xx.h
C
unknown
3,793
#Flash obj-$(USE_FLS)-$(CFG_PPC) += Fls_mpc5xxx.o obj-$(USE_FLS)-$(CFG_TMS570) += Fls_tms570.o obj-$(USE_FLS)-$(CFG_STM32) += Fls_stm32.o obj-$(USE_FLS)-$(CFG_JACINTO) += Fls_jacinto.o obj-$(USE_FLS)-$(CFG_ZYNQ) += Fls_zynq.o obj-$(USE_FLS)-$(CFG_GNULINUX) += Fls_gnulinux.o obj-$(USE_FLS) += Fls_Cfg.o ifeq ($(CFG_MPC5744P)$(CFG_MPC5777M)$(CFG_MPC5777C)$(CFG_MPC5748G)$(CFG_MPC5746C),y) obj-$(USE_FLS) += flash_c55.o else obj-$(CFG_MPC56XX)-$(USE_FLS) += flash_h7f_c90.o obj-$(CFG_MPC56XX)-$(USE_FLS) += flash_ll_h7f_c90.o obj-$(CFG_MPC55XX)-$(USE_FLS) += flash_h7f_c90.o obj-$(CFG_MPC55XX)-$(USE_FLS) += flash_ll_h7f_c90.o endif vpath-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/qspips_v3_1/src inc-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/qspips_v3_1/src inc-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/qspips_v3_1 vpath-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/qspips_v3_1/QspiIf inc-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/qspips_v3_1/QspiIf inc-$(CFG_ZYNQ)-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src/contrib/drivers/qspips_v3_1 #files needed for zynq QSPI obj-$(CFG_ZYNQ)-$(USE_FLS) += QspiIf.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips_g.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips_hw.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips_options.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips_selftest.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips_sinit.o obj-$(CFG_ZYNQ)-$(USE_FLS) += xqspips.o inc-$(USE_FLS) += $(ROOTDIR)/drivers/Fls vpath-$(USE_FLS) += $(ROOTDIR)/drivers/Fls vpath-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src inc-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/inc inc-$(USE_FLS) += $(ROOTDIR)/mcal/Fls/src
2301_81045437/classic-platform
drivers/Fls/fls.mod.mk
Makefile
unknown
1,701
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ /* @req FR074 */ /* @req FR465 */ /* @req FR466 */ /* @req FR029 */ /* @req FR097 */ /* @req FR103 */ /* @req FR106 Done by hardware; is deactivated when leaving NORMAL_ACTIVE state or NORMAL_PASSIVE*/ /* @req FR115 */ /* @req FR449 */ /* @req FR075 */ /* @req FR467 */ /* @req FR344 */ /* @req FR469 */ /* @req FR005 */ /* @req FR470 */ /* @req FR471 */ /* @req FR345 */ /* @req FR473 */ /* @req FR474 */ /* @req FR477 */ /* @req FR478 */ /* @req FR438 */ /* @req FR451 */ /* !req FR452 - Will be implemented later */ /* !req FR453 */ /* @req FR454 */ /* @req FR463 */ /* Generator/Configuration requirements */ /* @req FR080 */ /* @req FR480 */ /* @req FR481 */ /* @req FR484 */ /* @req FR486 */ /* @req FR487 */ /* Buffer reconfiguration is not supported */ /* !req FR482 */ /* !req FR483 */ /* !req FR003 */ /* @req FR124 */ /* !req FR126 - If no DEM is configured its turned off */ /* End of Generator/Configuration requirements */ /* ----------------------------[includes]------------------------------------*/ #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) /* @req FR071 */ #include "Dem.h" #endif #if defined(USE_DET) /* @req FR118 */ #include "Det.h" #endif /* @req FR462 */ #include "Fr.h" #include "Fr_Internal.h" #include "debug.h" /* ----------------------------[private define]------------------------------*/ // #define _FR_DEBUG_RX_ #if defined(_FR_DEBUG_RX_) #define _debug_rx_(...) printf (__VA_ARGS__); #else #define _debug_rx_(...) #endif /* ----------------------------[private macro]-------------------------------*/ /* @req FR026 */ /* @req FR127 */ /* Development error macros. */ #if ( FR_DEV_ERROR_DETECT == STD_ON ) #define VALIDATE(_exp,_api,_err ) \ if( !(_exp) ) { \ (void)Det_ReportError(FR_MODULE_ID,0,_api,_err); \ return; \ } #define VALIDATE_W_RV(_exp,_api,_err,_rv ) \ if( !(_exp) ) { \ (void)Det_ReportError(FR_MODULE_ID,0,_api,_err); \ return (_rv); \ } #else #define VALIDATE(_exp,_api,_err ) #define VALIDATE_W_RV(_exp,_api,_err,_rv ) #endif /* @req FR390 */ #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) #define DEM_REPORT(_eventId, _status) Fr_Internal_reportDem((_eventId), (_status)) #else #define DEM_REPORT(_eventId, _status) #endif //#if defined(CFG_RH850) ////The RH850 only supports one flexray controller //#define GET_FR_HW_PTR(_unit) (*(volatile struct FLXA_reg *)0x10020004u) //#else //#error Platform not specified //#endif /* ----------------------------[private typedef]-----------------------------*/ /* ----------------------------[private function prototypes]-----------------*/ /* ----------------------------[private variables]---------------------------*/ static Fr_ContainerType Fr_Cfg = {0}; /*lint !e910 Set all members to 0*/ /* ----------------------------[private functions]---------------------------*/ /* ----------------------------[public functions]----------------------------*/ /** * Initalizes the Fr. * @param Fr_ConfigPtr */ /* @req FR032 */ void Fr_Init(const Fr_ConfigType* Fr_ConfigPtr) { uint32 n, j; /* @req FR135 */ VALIDATE( ( Fr_ConfigPtr != NULL ), FR_INIT_SERVICE_ID, FR_E_INV_POINTER); VALIDATE( ( Fr_ConfigPtr->FrClusterConfig != NULL ), FR_INIT_SERVICE_ID, FR_E_INV_POINTER); VALIDATE( ( Fr_ConfigPtr->FrCtrlParam != NULL ), FR_INIT_SERVICE_ID, FR_E_INV_POINTER); VALIDATE( ( Fr_ConfigPtr->FrTrigConfig != NULL ), FR_INIT_SERVICE_ID, FR_E_INV_POINTER); VALIDATE( ( Fr_ConfigPtr->Fr_LpduConf != NULL ), FR_INIT_SERVICE_ID, FR_E_INV_POINTER); /* @req FR137 */ /* Store the location of the configuration data. */ Fr_Cfg.Fr_ConfigPtr = Fr_ConfigPtr; //Setup pointer to base register depending on configured controller index for (n = 0; n < FR_ARC_CTRL_CONFIG_CNT; n++) { // Fr_Cfg.hwPtr[n] = &GET_FR_HW_PTR(Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[n]->FrCtrlIdx); /*lint !e923 Must assign address to hw register*/ //Set memory buffer setups to 0. for (j = 0; j < Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[n].FrNbrTrigConfiged; j++) { Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[n].FrMsgBufferCfg[j].FrDataPartitionAddr = (uint32)NULL; Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[n].FrMsgBufferCfg[j].FrMsgBufferIdx = 0; } } Fr_Cfg.Fr_HasIntiailized = TRUE; } /** * Initialze a FlexRay CC. * @param Fr_CtrlIdx * @return E_OK / E_NOT_OK */ /* @req FR017 */ Std_ReturnType Fr_ControllerInit( uint8 Fr_CtrlIdx ) { Std_ReturnType retval; /* @req FR143 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_CTRLINIT_SERVICE_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR144 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_CTRLINIT_SERVICE_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); retval = Fr_Internal_EnableCtrl(&Fr_Cfg, Fr_CtrlIdx); if (retval == E_NOT_OK) { return retval; } /* @req FR149 */ retval = Fr_Internal_ClearPendingTx(&Fr_Cfg, Fr_CtrlIdx); if (retval == E_NOT_OK) { return retval; } /* @req FR150 */ retval = Fr_Internal_ClearPendingRx(&Fr_Cfg, Fr_CtrlIdx); if (retval == E_NOT_OK) { return retval; } /* @req FR151 */ Fr_Arc_ClearPendingIsr(&Fr_Cfg, Fr_CtrlIdx); /* @req FR152 */ Fr_Internal_DisableAllTimers(&Fr_Cfg, Fr_CtrlIdx); /* @req FR153 */ Fr_Internal_DisableAllFrIsr(&Fr_Cfg, Fr_CtrlIdx); /* !req FR515 */ //Fr_Internal_DisableAllLPdu(); retval = Fr_Internal_setupAndTestCC(&Fr_Cfg, Fr_CtrlIdx); return retval; } /** * Invokes the CC CHI command 'FREEZE'. * @param Fr_CtrlIdx * @return */ /* @req FR011 */ /* @req FR191 */ Std_ReturnType Fr_AbortCommunication(uint8 Fr_CtrlIdx) { Std_ReturnType retval; /* @req FR188 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_ABORTCOMMUNICATION_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR189 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_ABORTCOMMUNICATION_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); retval = Fr_Internal_SetCtrlChiCmd(&Fr_Cfg, Fr_CtrlIdx, (uint8)FR_POC_CMD_FREEZE); // if (retval == E_OK) { // Fr_Cfg.Fr_CCPocState[Fr_CtrlIdx] = FR_POCSTATE_HALT; // } return retval; } /** * Invokes the CC CHI command 'DEFERRED_HALT'. * @param Fr_CtrlIdx * @return */ /* @req FR014 */ /* @req FR187 */ Std_ReturnType Fr_HaltCommunication(uint8 Fr_CtrlIdx) { Std_ReturnType retval; /* @req FR183 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_HALTCOMMUNICATION_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR184 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_HALTCOMMUNICATION_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR185 */ retval = Fr_Internal_IsSynchronous(&Fr_Cfg, Fr_CtrlIdx); VALIDATE_W_RV( (retval == E_OK), FR_HALTCOMMUNICATION_ID, FR_E_INV_POCSTATE, E_NOT_OK ); retval = Fr_Internal_SetCtrlChiCmd(&Fr_Cfg, Fr_CtrlIdx, (uint8)FR_POC_CMD_HALT); return retval; } /** * Invokes the CC CHI command 'ALLOW_COLDSTART * @param Fr_CtrlIdx * @return */ /* @req FR114 */ /* @req FR182 */ Std_ReturnType Fr_AllowColdstart(uint8 Fr_CtrlIdx) { Std_ReturnType retval; /* @req FR178 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_ALLOWCOLDSTART_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR179 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_ALLOWCOLDSTART_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR180 */ Fr_POCStateType state = Fr_Internal_GetProtState(&Fr_Cfg,Fr_CtrlIdx); VALIDATE_W_RV( !((state == FR_POCSTATE_DEFAULT_CONFIG) || (state == FR_POCSTATE_CONFIG) || (state == FR_POCSTATE_HALT)), FR_ALLOWCOLDSTART_ID, FR_E_INV_POCSTATE, E_NOT_OK ); retval = Fr_Internal_SetCtrlChiCmd(&Fr_Cfg, Fr_CtrlIdx, (uint8)FR_POC_CMD_ALLOW_COLDSTART); return retval; } /** * Set the CC into the startup state. * @param Fr_CtrlIdx * @return */ /* @req FR010 */ Std_ReturnType Fr_StartCommunication(uint8 Fr_CtrlIdx) { Std_ReturnType retval; /* @req FR173 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_STARTCOMMUNICATION_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR174 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_STARTCOMMUNICATION_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR175 */ Fr_POCStateType state = Fr_Internal_GetProtState(&Fr_Cfg,Fr_CtrlIdx); VALIDATE_W_RV( (state == FR_POCSTATE_READY), FR_STARTCOMMUNICATION_ID, FR_E_INV_POCSTATE, E_NOT_OK ); /* @req FR177 */ /* @req FR176 */ retval = Fr_Internal_SetCtrlChiCmd(&Fr_Cfg, Fr_CtrlIdx, (uint8)FR_POC_CMD_RUN); return retval; } /** * Read and returns the POC state of the controller * @param Fr_CtrlIdx * @param Fr_POCStatusPtr * @return */ /* @req FR012 */ Std_ReturnType Fr_GetPOCStatus(uint8 Fr_CtrlIdx, Fr_POCStatusType* Fr_POCStatusPtr) { Std_ReturnType retval; /* @req FR213 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_GETPOCSTATUS_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR214 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_GETPOCSTATUS_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR215 */ VALIDATE_W_RV( ( Fr_POCStatusPtr != NULL ), FR_GETPOCSTATUS_ID, FR_E_INV_POINTER, E_NOT_OK); /* @req FR217 */ retval = Fr_Internal_GetChiPocState(&Fr_Cfg, Fr_CtrlIdx, Fr_POCStatusPtr); return retval; } /** * Invokes the CC CHI command 'WAKEUP'. * @param Fr_CtrlIdx * @return */ /* @req FR009 */ /* @req FR196 */ Std_ReturnType Fr_SendWUP(uint8 Fr_CtrlIdx) { Std_ReturnType retval; /* @req FR192 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_SENDWUP_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR193 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_SENDWUP_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR194 */ Fr_POCStateType state = Fr_Internal_GetProtState(&Fr_Cfg,Fr_CtrlIdx); VALIDATE_W_RV( (state == FR_POCSTATE_READY), FR_SENDWUP_ID, FR_E_INV_POCSTATE, E_NOT_OK ); retval = Fr_Internal_SetCtrlChiCmd(&Fr_Cfg, Fr_CtrlIdx, (uint8)FR_POC_CMD_WAKEUP); return retval; } /** * Sets a wakeup channel. * @param Fr_CtrlIdx * @param Fr_ChnlIdx * @return */ /* @req FR091 */ /* @req FR202 */ Std_ReturnType Fr_SetWakeupChannel(uint8 Fr_CtrlIdx, Fr_ChannelType Fr_ChnlIdx) { Std_ReturnType retval; /* @req FR197 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_SETWAKEUPCHANNEL_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR198 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_SETWAKEUPCHANNEL_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR199 */ VALIDATE_W_RV( ((Fr_ChnlIdx == FR_CHANNEL_A) || (Fr_ChnlIdx == FR_CHANNEL_B)), FR_SETWAKEUPCHANNEL_ID, FR_E_INV_CHNL_IDX, E_NOT_OK ); /* @req FR200 */ Fr_POCStateType state = Fr_Internal_GetProtState(&Fr_Cfg,Fr_CtrlIdx); VALIDATE_W_RV( (state == FR_POCSTATE_READY), FR_SETWAKEUPCHANNEL_ID, FR_E_INV_POCSTATE, E_NOT_OK ); retval = Fr_Internal_SetWUPChannel(&Fr_Cfg, Fr_CtrlIdx, Fr_ChnlIdx); return retval; } /** * Transmits data on the FlexRay network. * @param Fr_CtrlIdx * @param Fr_LPduIdx * @param Fr_LSduPtr * @param Fr_LSduLength * @return */ /* @req FR092 */ /* @req FR224 */ Std_ReturnType Fr_TransmitTxLPdu(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, const uint8* Fr_LSduPtr, uint8 Fr_LSduLength) { Std_ReturnType retval = E_OK; uint32 trigIdx; uint16 msgBuffrIdx; /* @req FR218 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_TRANSMITTXLPDU_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); const Fr_FrIfCCTriggeringType *trigConfPtr = &Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[Fr_CtrlIdx]; const Fr_FrIfLPduContainerType *lpduConfPtr = &Fr_Cfg.Fr_ConfigPtr->Fr_LpduConf[Fr_CtrlIdx]; /* @req FR219 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_TRANSMITTXLPDU_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR220 */ VALIDATE_W_RV( (Fr_LPduIdx < lpduConfPtr->FrNbrLPdusConfigured), \ FR_TRANSMITTXLPDU_ID, FR_E_INV_LPDU_IDX, E_NOT_OK ); /* @req FR221 */ trigIdx = lpduConfPtr->FrLpdu[Fr_LPduIdx].FrLpdTriggIdx; VALIDATE_W_RV( (Fr_LSduLength <= (uint8)trigConfPtr->FrTrigConfPtr[trigIdx].FrTrigLSduLength), \ FR_TRANSMITTXLPDU_ID, FR_E_INV_LENGTH, E_NOT_OK ); /* @req FR222 */ VALIDATE_W_RV( ( Fr_LSduPtr != NULL ), FR_TRANSMITTXLPDU_ID, FR_E_INV_POINTER, E_NOT_OK); /* If the Fr_ControllerInit has not run then the data partitioning has not been done, return E_NOT_OK. */ VALIDATE_W_RV( (trigConfPtr->FrMsgBufferCfg[trigIdx].FrDataPartitionAddr != 0UL), \ FR_TRANSMITTXLPDU_ID, FR_E_ARC_DATA_PARTITION, E_NOT_OK); msgBuffrIdx = trigConfPtr->FrMsgBufferCfg[trigIdx].FrMsgBufferIdx; //Reconfigure header if FrIfAllowDynamicLSduLength and length is different if (trigConfPtr->FrTrigConfPtr[trigIdx].FrTrigAllowDynamicLen && (trigConfPtr->FrTrigConfPtr[trigIdx].FrTrigSlotId > Fr_Cfg.Fr_ConfigPtr->FrClusterConfig[Fr_CtrlIdx].FrClusterGNumberOfStaticSlots) && ((uint32)Fr_LSduLength != trigConfPtr->FrMsgBufferCfg[trigIdx].FrCurrentLengthSetup)) { //Update header retval = Fr_Internal_UpdateHeaderLength(&Fr_Cfg, Fr_CtrlIdx, Fr_LSduLength, msgBuffrIdx, trigIdx); } if (retval == E_OK) { retval = Fr_Internal_SetTxData(&Fr_Cfg, Fr_CtrlIdx, Fr_LSduPtr, Fr_LSduLength, msgBuffrIdx); } return retval; } /** * Receives data from the FlexRay network. * @param Fr_CtrlIdx * @param Fr_LPduIdx * @param Fr_LSduPtr * @param Fr_LPduStatusPtr * @param Fr_LSduLengthPtr * @return */ /* @req FR093 */ /* @req FR233 */ Std_ReturnType Fr_ReceiveRxLPdu( uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, uint8* Fr_LSduPtr, Fr_RxLPduStatusType* Fr_LPduStatusPtr, uint8* Fr_LSduLengthPtr ) { Std_ReturnType retval = E_OK; Std_ReturnType newData; uint16 msgBufferIdx; uint32 trigIdx; /* @req FR226 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_RECEIVERXLPDU_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); const Fr_FrIfCCTriggeringType *trigConfPtr = &Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[Fr_CtrlIdx]; const Fr_FrIfLPduContainerType *lpduConfPtr = &Fr_Cfg.Fr_ConfigPtr->Fr_LpduConf[Fr_CtrlIdx]; /* @req FR227 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_RECEIVERXLPDU_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR228 */ VALIDATE_W_RV( (Fr_LPduIdx < lpduConfPtr->FrNbrLPdusConfigured), \ FR_RECEIVERXLPDU_ID, FR_E_INV_LPDU_IDX, E_NOT_OK ); /* @req FR229 */ VALIDATE_W_RV( ( Fr_LSduPtr != NULL ), FR_RECEIVERXLPDU_ID, FR_E_INV_POINTER, E_NOT_OK); /* @req FR230 */ VALIDATE_W_RV( ( Fr_LPduStatusPtr != NULL ), FR_RECEIVERXLPDU_ID, FR_E_INV_POINTER, E_NOT_OK); /* @req FR231 */ VALIDATE_W_RV( ( Fr_LSduLengthPtr != NULL ), FR_RECEIVERXLPDU_ID, FR_E_INV_POINTER, E_NOT_OK); trigIdx = lpduConfPtr->FrLpdu[Fr_LPduIdx].FrLpdTriggIdx; /* If the Fr_ControllerInit has not run then the data partitioning has not been done, return E_NOT_OK. */ VALIDATE_W_RV( (trigConfPtr->FrMsgBufferCfg[trigIdx].FrDataPartitionAddr != 0UL), \ FR_TRANSMITTXLPDU_ID, FR_E_ARC_DATA_PARTITION, E_NOT_OK); /* @req FR603 Partly */ /* @req FR604 Partly */ //Set this as default. *Fr_LSduLengthPtr = 0; *Fr_LPduStatusPtr = FR_NOT_RECEIVED; msgBufferIdx = trigConfPtr->FrMsgBufferCfg[trigIdx].FrMsgBufferIdx; /* @req FR237 */ newData = Fr_Internal_CheckNewData(&Fr_Cfg, Fr_CtrlIdx, msgBufferIdx); if (newData == E_OK) { retval = Fr_Internal_GetNewData(&Fr_Cfg, Fr_CtrlIdx, trigIdx, msgBufferIdx, Fr_LSduPtr, Fr_LSduLengthPtr); _debug_rx_("RX idx=%d len=%d\n",trigConfPtr->FrTrigConfPtr[trigIdx].FrTrigSlotId, *Fr_LSduLengthPtr); for(uint32 i=0; i<*Fr_LSduLengthPtr;i++) { _debug_rx_("%02d ",Fr_LSduPtr[i]); } _debug_rx_("%c",'\n'); if (retval == E_OK) { *Fr_LPduStatusPtr = FR_RECEIVED; } } return retval; } /** * Checks the transmit status of the LSdu. * @param Fr_CtrlIdx * @param Fr_LPduIdx * @param Fr_TxLPduStatusPtr * @return */ /* @req FR094 */ /* @req FR244 */ Std_ReturnType Fr_CheckTxLPduStatus(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, Fr_TxLPduStatusType* Fr_TxLPduStatusPtr) { boolean isTxPending = FALSE; Std_ReturnType retval; uint32 trigIdx; /* @req FR240 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_CHECKTXLPDUSTATUS_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); const Fr_FrIfCCTriggeringType *trigConfPtr = &Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[Fr_CtrlIdx]; const Fr_FrIfLPduContainerType *lpduConfPtr = &Fr_Cfg.Fr_ConfigPtr->Fr_LpduConf[Fr_CtrlIdx]; /* @req FR241 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_CHECKTXLPDUSTATUS_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR242 */ VALIDATE_W_RV( (Fr_LPduIdx < lpduConfPtr->FrNbrLPdusConfigured), \ FR_CHECKTXLPDUSTATUS_ID, FR_E_INV_LPDU_IDX, E_NOT_OK ); /* @req FR343 */ VALIDATE_W_RV( ( Fr_TxLPduStatusPtr != NULL ), FR_CHECKTXLPDUSTATUS_ID, FR_E_INV_POINTER, E_NOT_OK); trigIdx = lpduConfPtr->FrLpdu[Fr_LPduIdx].FrLpdTriggIdx; /* If the Fr_ControllerInit has not run then the data partitioning has not been done, return E_NOT_OK. */ VALIDATE_W_RV( (trigConfPtr->FrMsgBufferCfg[trigIdx].FrDataPartitionAddr != 0UL), \ FR_CHECKTXLPDUSTATUS_ID, FR_E_ARC_DATA_PARTITION, E_NOT_OK); retval = Fr_Internal_GetTxPending(&Fr_Cfg, Fr_CtrlIdx, trigIdx, &isTxPending); if (retval == E_OK) { //If no transmission is pending. if (!isTxPending) { *Fr_TxLPduStatusPtr = FR_TRANSMITTED; } else { *Fr_TxLPduStatusPtr = FR_NOT_TRANSMITTED; } } return E_OK; } /** * Cancels the already pending transmission of a LPdu contained in a controllers physical transmit resource. * @param Fr_CtrlIdx * @param Fr_LPduIdx * @return */ /* @req FR610 */ /* @req FR611 */ Std_ReturnType Fr_CancelTxLPdu(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx) { Std_ReturnType retval; boolean isTxPending; uint16 msgBuffrIdx; uint32 trigIdx; /* @req FR614 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_CANCELTXLPDU_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); const Fr_FrIfCCTriggeringType *trigConfPtr = &Fr_Cfg.Fr_ConfigPtr->FrTrigConfig[Fr_CtrlIdx]; const Fr_FrIfLPduContainerType *lpduConfPtr = &Fr_Cfg.Fr_ConfigPtr->Fr_LpduConf[Fr_CtrlIdx]; /* @req FR615 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_CANCELTXLPDU_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR616 */ VALIDATE_W_RV( (Fr_LPduIdx < lpduConfPtr->FrNbrLPdusConfigured), \ FR_CANCELTXLPDU_ID, FR_E_INV_LPDU_IDX, E_NOT_OK ); trigIdx = lpduConfPtr->FrLpdu[Fr_LPduIdx].FrLpdTriggIdx; /* If the Fr_ControllerInit has not run then the data partitioning has not been done, return E_NOT_OK. */ VALIDATE_W_RV( (trigConfPtr->FrMsgBufferCfg[trigIdx].FrDataPartitionAddr != 0UL), \ FR_CANCELTXLPDU_ID, FR_E_ARC_DATA_PARTITION, E_NOT_OK); msgBuffrIdx = trigConfPtr->FrMsgBufferCfg[trigIdx].FrMsgBufferIdx; //To check if the buffer is in any pending transmission retval = Fr_Internal_GetTxPending(&Fr_Cfg, Fr_CtrlIdx, trigIdx, &isTxPending); if ((retval == E_OK) && isTxPending) { retval = Fr_Internal_CancelTx(&Fr_Cfg, Fr_CtrlIdx, msgBuffrIdx); } else { retval = E_NOT_OK; } return retval; } /** * Gets the current global FlexRay time. * @param Fr_CtrlIdx * @param Fr_CyclePtr * @param Fr_MacroTickPtr * @return */ /* @req FR042 */ /* @req FR256 */ Std_ReturnType Fr_GetGlobalTime(uint8 Fr_CtrlIdx, uint8* Fr_CyclePtr, uint16* Fr_MacroTickPtr) { Std_ReturnType retval; /* @req FR251 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_GETGLOBALTIME_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR252 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_GETGLOBALTIME_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR253 */ VALIDATE_W_RV( ( Fr_CyclePtr != NULL ), FR_GETGLOBALTIME_ID, FR_E_INV_POINTER, E_NOT_OK); /* @req FR254 */ VALIDATE_W_RV( ( Fr_MacroTickPtr != NULL ), FR_GETGLOBALTIME_ID, FR_E_INV_POINTER, E_NOT_OK); retval = Fr_Internal_GetGlobalTime(&Fr_Cfg, Fr_CtrlIdx, Fr_CyclePtr, Fr_MacroTickPtr); return retval; } /** * Sets the absolute FlexRay timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @param Fr_Cycle * @param Fr_Offset * @return */ /* @req FR033 */ Std_ReturnType Fr_SetAbsoluteTimer(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx, uint8 Fr_Cycle, uint16 Fr_Offset) { Std_ReturnType retval; /* @req FR267 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_SETABSOLUTETIMER_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR268 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_SETABSOLUTETIMER_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR269 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_SETABSOLUTETIMER_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR270 */ VALIDATE_W_RV( (Fr_Cycle <= Fr_Cfg.Fr_ConfigPtr->FrClusterConfig[Fr_CtrlIdx].FrClusterGCycleCountMax), FR_SETABSOLUTETIMER_ID, FR_E_INV_CYCLE, E_NOT_OK ); /* @req FR271 */ VALIDATE_W_RV( ((uint32)Fr_Offset < Fr_Cfg.Fr_ConfigPtr->FrClusterConfig[Fr_CtrlIdx].FrClusterGMacroPerCycle), FR_SETABSOLUTETIMER_ID, FR_E_INV_OFFSET, E_NOT_OK ); /* @req FR436 */ retval = Fr_Internal_IsSynchronous(&Fr_Cfg, Fr_CtrlIdx); VALIDATE_W_RV( (retval == E_OK), FR_SETABSOLUTETIMER_ID, FR_E_INV_POCSTATE, E_NOT_OK ); /* @req FR273 */ Fr_Internal_SetupAbsTimer(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx, Fr_Cycle, Fr_Offset); return E_OK; } /** * Stops an absolute timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @return */ /* @req FR095 */ Std_ReturnType Fr_CancelAbsoluteTimer(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx) { /* @req FR283 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_CANCELABSOLUTETIMER_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR284 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_CANCELABSOLUTETIMER_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR285 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_CANCELABSOLUTETIMER_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR287 */ Fr_Internal_DisableAbsTimer(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx); return E_OK; } /** * Gets IRQ status of an absolute timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @param Fr_IRQStatusPtr * @return */ /* @req FR108 */ Std_ReturnType Fr_GetAbsoluteTimerIRQStatus(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx, boolean* Fr_IRQStatusPtr) { /* @req FR327 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_GETABSTIMERIRQSTATUS_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR328 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_GETABSTIMERIRQSTATUS_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR329 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_GETABSTIMERIRQSTATUS_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR330 */ VALIDATE_W_RV( ( Fr_IRQStatusPtr != NULL ), FR_GETABSTIMERIRQSTATUS_ID, FR_E_INV_POINTER, E_NOT_OK); /* @req FR332 */ *Fr_IRQStatusPtr = Fr_Internal_GetAbsTimerIrqStatus(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx); return E_OK; } /** * Resets the interrupt condition of an absolute timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @return */ /* @req FR036 */ Std_ReturnType Fr_AckAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx) { /* @req FR305 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_ACKABSOLUTETIMERIRQ_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR306 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_ACKABSOLUTETIMERIRQ_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR307 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_ACKABSOLUTETIMERIRQ_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR309 */ Fr_Internal_ResetAbsTimerIsrFlag(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx); return E_OK; } /** * Disables the interrupt line of an absolute timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @return */ /* @req FR035 */ Std_ReturnType Fr_DisableAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx) { /* @req FR316 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_DISABLEABSTIMERIRQ_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR317 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_DISABLEABSTIMERIRQ_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR318 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_DISABLEABSTIMERIRQ_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR320 */ Fr_Internal_DisableAbsTimerIrq(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx); return E_OK; } /** * Enables the interrupt line of an absolute timer. * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @return */ /* @req FR034 */ Std_ReturnType Fr_EnableAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx) { /* @req FR294 */ VALIDATE_W_RV( (Fr_Cfg.Fr_HasIntiailized == TRUE), FR_ENABLEABSTIMERIRQ_ID, FR_E_NOT_INITIALIZED, E_NOT_OK ); /* @req FR295 */ VALIDATE_W_RV( (Fr_CtrlIdx < FR_ARC_CTRL_CONFIG_CNT), FR_ENABLEABSTIMERIRQ_ID, FR_E_INV_CTRL_IDX, E_NOT_OK ); /* @req FR296 */ VALIDATE_W_RV( (Fr_AbsTimerIdx <= Fr_Cfg.Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrArcAbsTimerMaxIdx), FR_ENABLEABSTIMERIRQ_ID, FR_E_INV_TIMER_IDX, E_NOT_OK ); /* @req FR298 */ Fr_Internal_EnableAbsTimerIrq(&Fr_Cfg, Fr_CtrlIdx, Fr_AbsTimerIdx); return E_OK; } /** * Returns the version information of this module. * @param VersioninfoPtr */ /* @req FR070 */ /* @req FR342 */ #if ( FR_VERSION_INFO_API == STD_ON ) void Fr_GetVersionInfo(Std_VersionInfoType* VersioninfoPtr) { /* @req FR340 */ VALIDATE( ( VersioninfoPtr != NULL ), FR_GETVERSIONINFO_ID, FR_E_INV_POINTER); /* @req FR341 */ VersioninfoPtr->vendorID = FR_VENDOR_ID; VersioninfoPtr->moduleID = FR_MODULE_ID; VersioninfoPtr->sw_major_version = FR_SW_MAJOR_VERSION; VersioninfoPtr->sw_minor_version = FR_SW_MINOR_VERSION; VersioninfoPtr->sw_patch_version = FR_SW_PATCH_VERSION; } #endif
2301_81045437/classic-platform
drivers/Fr/Fr.c
C
unknown
28,702
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ /* @req FR101 */ #ifndef FR_H_ #define FR_H_ /* @req FR102 */ /*@req FR667 */ #define FR_VENDOR_ID 60 #define FR_MODULE_ID 81 #define FR_AR_RELEASE_MAJOR_VERSION 4 #define FR_AR_RELEASE_MINOR_VERSION 0 #define FR_AR_RELEASE_REVISION_VERSION 3 /* @req FR650 */ #define FR_SW_MAJOR_VERSION 1 #define FR_SW_MINOR_VERSION 0 #define FR_SW_PATCH_VERSION 0 /* @req FR460 */ #include "Std_Types.h" /* @req FR459 */ #include "Fr_GeneralTypes.h" /* @req FR461 */ #include "Fr_Cfg.h" /* @req FR112 */ #include "MemMap.h" /* --- Error / Event IDs --- */ /* @req FR125 */ /* @req FR078 */ /* @req FR025 */ #define FR_E_INV_TIMER_IDX (uint8)0x01 /* @req FR488 */ #define FR_E_INV_POINTER (uint8)0x02 /* @req FR489 */ #define FR_E_INV_OFFSET (uint8)0x03 /* @req FR490 */ #define FR_E_INV_CTRL_IDX (uint8)0x04 /* @req FR491 */ #define FR_E_INV_CHNL_IDX (uint8)0x05 /* @req FR492 */ #define FR_E_INV_CYCLE (uint8)0x06 /* @req FR494 */ #define FR_E_NOT_INITIALIZED (uint8)0x08 /* @req FR495 */ #define FR_E_INV_POCSTATE (uint8)0x09 /* @req FR496 */ #define FR_E_INV_LENGTH (uint8)0x0A /* @req FR497 */ #define FR_E_INV_LPDU_IDX (uint8)0x0B /* @req FR633 */ #define FR_E_INV_HEADERCRC (uint8)0x0C #define FR_E_INV_CONFIG_IDX (uint8)0x0D #define FR_E_ARC_DATA_PARTITION (uint8)0x0E /* @req FR078 */ #define FR_CTRLINIT_SERVICE_ID (uint8)0x00 #define FR_STARTCOMMUNICATION_ID (uint8)0x03 #define FR_HALTCOMMUNICATION_ID (uint8)0x04 #define FR_ABORTCOMMUNICATION_ID (uint8)0x05 #define FR_SENDWUP_ID (uint8)0x06 #define FR_SETWAKEUPCHANNEL_ID (uint8)0x07 #define FR_GETPOCSTATUS_ID (uint8)0x0A #define FR_TRANSMITTXLPDU_ID (uint8)0x0B #define FR_RECEIVERXLPDU_ID (uint8)0x0C #define FR_CHECKTXLPDUSTATUS_ID (uint8)0x0D #define FR_GETGLOBALTIME_ID (uint8)0x10 #define FR_SETABSOLUTETIMER_ID (uint8)0x11 #define FR_CANCELABSOLUTETIMER_ID (uint8)0x13 #define FR_ENABLEABSTIMERIRQ_ID (uint8)0x15 #define FR_ACKABSOLUTETIMERIRQ_ID (uint8)0x17 #define FR_DISABLEABSTIMERIRQ_ID (uint8)0x19 #define FR_GETVERSIONINFO_ID (uint8)0x1B #define FR_INIT_SERVICE_ID (uint8)0x1C #define FR_GETABSTIMERIRQSTATUS_ID (uint8)0x20 #define FR_ALLOWCOLDSTART_ID (uint8)0x23 #define FR_CANCELTXLPDU_ID (uint8)0x2D /* @req FR464 */ /* @req FR501 */ /* @req FR646 */ /* !req FR648 */ typedef struct { const Fr_CtrlConfigParametersType *FrCtrlParam; const Fr_FrIfCCTriggeringType *FrTrigConfig; const Fr_FrIfClusterConfigType *FrClusterConfig; const Fr_FrIfLPduContainerType *Fr_LpduConf; }Fr_ConfigType; extern const Fr_ConfigType FrConfigData; /* @req FR098 */ void Fr_Init(const Fr_ConfigType* Fr_ConfigPtr); Std_ReturnType Fr_ControllerInit(uint8 Fr_CtrlIdx); Std_ReturnType Fr_AbortCommunication(uint8 Fr_CtrlIdx); Std_ReturnType Fr_HaltCommunication(uint8 Fr_CtrlIdx); Std_ReturnType Fr_AllowColdstart(uint8 Fr_CtrlIdx); Std_ReturnType Fr_GetPOCStatus(uint8 Fr_CtrlIdx, Fr_POCStatusType* Fr_POCStatusPtr); Std_ReturnType Fr_StartCommunication(uint8 Fr_CtrlIdx); Std_ReturnType Fr_SendWUP(uint8 Fr_CtrlIdx); Std_ReturnType Fr_SetWakeupChannel(uint8 Fr_CtrlIdx, Fr_ChannelType Fr_ChnlIdx); Std_ReturnType Fr_TransmitTxLPdu(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, const uint8* Fr_LSduPtr, uint8 Fr_LSduLength); Std_ReturnType Fr_ReceiveRxLPdu(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, uint8* Fr_LSduPtr, Fr_RxLPduStatusType* Fr_LPduStatusPtr, uint8* Fr_LSduLengthPtr ); Std_ReturnType Fr_CheckTxLPduStatus(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, Fr_TxLPduStatusType* Fr_TxLPduStatusPtr); Std_ReturnType Fr_CancelTxLPdu(uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx); Std_ReturnType Fr_GetGlobalTime(uint8 Fr_CtrlIdx, uint8* Fr_CyclePtr, uint16* Fr_MacroTickPtr); Std_ReturnType Fr_SetAbsoluteTimer(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx, uint8 Fr_Cycle, uint16 Fr_Offset); Std_ReturnType Fr_CancelAbsoluteTimer(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); Std_ReturnType Fr_GetAbsoluteTimerIRQStatus(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx, boolean* Fr_IRQStatusPtr); Std_ReturnType Fr_AckAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); Std_ReturnType Fr_DisableAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); Std_ReturnType Fr_EnableAbsoluteTimerIRQ(uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); Std_ReturnType Fr_AllSlots( uint8 Fr_CtrlIdx ); Std_ReturnType Fr_GetChannelStatus( uint8 Fr_CtrlIdx, uint16* Fr_ChannelAStatusPtr, uint16* Fr_ChannelBStatusPtr ); Std_ReturnType Fr_GetClockCorrection( uint8 Fr_CtrlIdx, sint16* Fr_RateCorrectionPtr, sint32* Fr_OffsetCorrectionPtr ); Std_ReturnType Fr_GetNumOfStartupFrames( uint8 Fr_CtrlIdx, uint8* Fr_NumOfStartupFramesPtr ); Std_ReturnType Fr_GetWakeupRxStatus( uint8 Fr_CtrlIdx, uint8* Fr_WakeupRxStatusPtr ); Std_ReturnType Fr_ReadCCConfig( uint8 Fr_CtrlIdx, uint8 Fr_ConfigParamIdx,uint32* Fr_ConfigParamValuePtr ); Std_ReturnType Fr_GetSyncFrameList( uint8 Fr_CtrlIdx, uint8 Fr_ListSize, uint16* Fr_ChannelAEvenListPtr, uint16* Fr_ChannelBEvenListPtr, uint16* Fr_ChannelAOddListPtr, uint16* Fr_ChannelBOddListPtr ); Std_ReturnType Fr_DisableLPdu( uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx ); Std_ReturnType Fr_PrepareLPdu( uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx ); Std_ReturnType Fr_ReconfigLPdu( uint8 Fr_CtrlIdx, uint16 Fr_LPduIdx, uint16 Fr_FrameId, Fr_ChannelType Fr_ChnlIdx, uint8 Fr_CycleRepetition, uint8 Fr_CycleOffset, uint8 Fr_PayloadLength, uint16 Fr_HeaderCRC ); #if ( FR_VERSION_INFO_API == STD_ON ) void Fr_GetVersionInfo(Std_VersionInfoType* VersioninfoPtr); #endif #endif /*FR_H_*/
2301_81045437/classic-platform
drivers/Fr/Fr.h
C
unknown
6,642
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ #ifndef FR_INTERNAL_H_ #define FR_INTERNAL_H_ #include "Fr.h" #if defined(CFG_RH850) #include "Fr_rh850f1x.h" #else #include "Fr_mpc5xxx.h" #endif #define FR_POC_CMD_ALLOW_COLDSTART POC_CMD_ALLOW_COLDSTART #define FR_POC_CMD_ALL_SLOTS POC_CMD_ALL_SLOTS #define FR_POC_CMD_CONFIG POC_CMD_CONFIG #define FR_POC_CMD_FREEZE POC_CMD_FREEZE #define FR_POC_CMD_READY POC_CMD_READY #define FR_POC_CMD_CONFIG_COMPLETE POC_CMD_CONFIG_COMPLETE #define FR_POC_CMD_RUN POC_CMD_RUN #define FR_POC_CMD_DEFAULT_CONFIG POC_CMD_DEFAULT_CONFIG #define FR_POC_CMD_HALT POC_CMD_HALT #define FR_POC_CMD_WAKEUP POC_CMD_WAKEUP typedef struct { const Fr_ConfigType *Fr_ConfigPtr; Fr_POCStateType Fr_CCPocState[FR_ARC_CTRL_CONFIG_CNT]; boolean Fr_HasIntiailized; #if defined(CFG_RH850) volatile struct FLXA_reg *hwPtr[FR_ARC_CTRL_CONFIG_CNT]; #endif }Fr_ContainerType; /* @req FR098 */ Std_ReturnType Fr_Internal_ClearPendingTx(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_ClearPendingRx(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_RunAllCCTest(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_RunCCTest(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_SetupCC(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_SetupRxTxResources(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); void Fr_Arc_ClearPendingIsr(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); void Fr_Internal_DisableAllTimers(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); void Fr_Internal_DisableAllFrIsr(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); void Fr_Internal_DisableAllLPdu(void); Std_ReturnType Fr_Internal_SetCtrlChiCmd(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 chiCmd); Std_ReturnType Fr_Internal_EnableCtrl(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); Std_ReturnType Fr_Internal_setupAndTestCC(Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); /** * Write the data to be transmitted. * @param Fr_Cfg * @param Fr_CtrlIdx * @param Fr_POCStatusPtr * @return */ Std_ReturnType Fr_Internal_GetChiPocState(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, Fr_POCStatusType* Fr_POCStatusPtr); Std_ReturnType Fr_Internal_SetTxData(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, const uint8* Fr_LSduPtr, uint8 Fr_LSduLength, uint16 Fr_MsgBuffrIdx); Std_ReturnType Fr_Internal_CheckHeader(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint32 trigIdx); Std_ReturnType Fr_Internal_CheckNewData(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint16 msgBufferIdx); /** * @brief Get new RX data. Received data is copied to Fr_LSduPtr and Fr_LSduLengthPtr is updated * with the length. * @param Fr_Cfg Pointer to the flexray configuration. * @param Fr_CtrlIdx Index of flexray controllers. * @param trigIdx Index into the trigger configuration. * @param msgBufferIdx Index into the message buffers. * @param Fr_LSduPtr Pointer to data to data to receive. * @param Fr_LSduLengthPtr Pointer to lengh of the data. Will be update by function. * @return */ Std_ReturnType Fr_Internal_GetNewData(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint32 trigIdx, uint16 msgBufferIdx, uint8* Fr_LSduPtr, uint8* Fr_LSduLengthPtr); /** * Checks the message status * @param Fr_Cfg * @param Fr_CtrlIdx * @param msgBufferIdx * @return */ Std_ReturnType Fr_Internal_GetTxPending(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint32 trigIdx, boolean *txPending); Std_ReturnType Fr_Internal_CancelTx(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint16 msgBufferIdx); Std_ReturnType Fr_Internal_SetWUPChannel(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, Fr_ChannelType Fr_ChnlIdx); Std_ReturnType Fr_Internal_GetGlobalTime(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8* Fr_CyclePtr, uint16* Fr_MacroTickPtr); /** * * @param Fr_Cfg * @param Fr_CtrlIdx * @return */ Std_ReturnType Fr_Internal_IsSynchronous(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx); void Fr_Internal_SetupAbsTimer(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx, uint8 Fr_Cycle, uint16 Fr_Offset); void Fr_Internal_DisableAbsTimer(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); /** * Gets IRQ status of a timer. * * @param Fr_Cfg * @param Fr_CtrlIdx * @param Fr_AbsTimerIdx * @return TRUE - If interrupt is pending * FALSE - Not pending */ boolean Fr_Internal_GetAbsTimerIrqStatus(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); void Fr_Internal_ResetAbsTimerIsrFlag(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); void Fr_Internal_DisableAbsTimerIrq(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); void Fr_Internal_EnableAbsTimerIrq(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 Fr_AbsTimerIdx); Std_ReturnType Fr_Internal_UpdateHeaderLength(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint8 length, uint16 msgBuffrIdx, uint32 frameTrigIdx); #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) static inline void Fr_Internal_reportDem(Dem_EventIdType eventId, Dem_EventStatusType eventStatus); #endif Fr_POCStateType Fr_Internal_GetProtState( const Fr_ContainerType *Fr_Cfg, uint8 cIdx ); #endif /*FR_INTERNAL_H_*/
2301_81045437/classic-platform
drivers/Fr/Fr_Internal.h
C
unknown
6,488
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ // #define _DEBUG_ /* ----------------------------[includes]------------------------------------*/ #include "Fr.h" #include "Fr_Internal.h" #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) #include "Dem.h" #endif #if defined(USE_DET) #include "Det.h" #endif #include "mpc55xx.h" #include "timer.h" #include <assert.h> #include <string.h> #include "debug.h" // #define _FR_DEBUG_INIT_ #if defined(_FR_DEBUG_INIT_) #define _debug_init_(...) printf (__VA_ARGS__); #else #define _debug_init_(...) #endif #if defined(_FR_DEBUG_TX_) #define _debug_tx_(...) printf (__VA_ARGS__); #else #define _debug_tx_(...) #endif #if defined(_FR_DEBUG_RX_) #define _debug_rx_(...) printf (__VA_ARGS__); #else #define _debug_rx_(...) #endif #if defined(_FR_DEBUG_TIMER_) #define _debug_timer_(...) printf (__VA_ARGS__); #else #define _debug_timer_(...) #endif /* ----------------------------[private define]------------------------------*/ #define POC_STATE_CONFIG 3u #define POC_STATE_PASSIVE 4u #define POC_STATE_RUN 5u #define MAX_WAIT_CYCLES (uint32)10000UL #ifndef DEM_EVENT_ID_NULL #define DEM_EVENT_ID_NULL 0u #endif #define FR_LENGTH_DIV 2UL #define V_CRC_SIZE (uint32)11UL #define V_CRC_POLYNOMIAL (uint32)0x385UL #define V_CRC_INIT (uint32)0x1AUL /* Number of shadow buffers... set this to 4 (don't care about memory) */ #define SHADOW_BUFFER_CNT 4 #define CMD_OK 0u #define CMD_TIMEOUT 1u /* ----------------------------[private macro]-------------------------------*/ #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) #define DEM_REPORT(_eventId, _status) Fr_Internal_reportDem((_eventId), (_status)) #else #define DEM_REPORT(_eventId, _status) #endif #define ALIGN8(_x) ((((_x) + 8ul - 1ul) / 8ul) * 8ul) #define _LOW16(_x) ((_x) & 0xfffful) #define _HIGH16(_x) (((_x)>>16) & 0xfffful) #define DIAG_SET(_x,_y) _x = (_y); \ if ( (_x) != (_y) ) { errCnt++; } /* ----------------------------[private typedef]-----------------------------*/ typedef enum { HEADER = 0, HEADER_AND_DATA, DATA, }MsgRAMReadoutType; typedef struct Fr_Info { uint32 staticSlots; uint32 dynamicSlots; uint32 bitRate; uint32 cycles; uint32 macrotick; const Fr_ContainerType *cfg; } Fr_InfoType; Fr_InfoType Fr_Info; /* ----------------------------[private function prototypes]-----------------*/ static Std_ReturnType findTrigIdx(const Fr_FrIfCCTriggeringType *FrTrigConf, uint32 searchedId, uint32 *trigIdx); static uint32 getHeaderCrc(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint32 frameTrigIdx, uint32 dynLen); /* ----------------------------[private variables]---------------------------*/ struct FR_tag * const Fr_HwReg[] = { ((struct FR_tag *) (&FR_0)), }; uint8 Fr_MsgBuffers[128*256] __balign(0x10); /* IMPROVEMENT, fix size here */ /* ----------------------------[functions]---------------------------*/ /* MBIDXRn index to: * - Header : SADR_MBHF= (FR_MBIDXn.MBIDX*8 + FR_SYMBADR.SMBA) * - Frame Data: SADR_MBDF= FR_MBDORn.MBDO + FR_SYMBADR.SMBA * * Memory Layout: * * Calc Description * --------------------------------------------------------------------------- * FrNbrTrigConfiged * 8 Headers for both static and dynamic messages * gNumberOfStaticSlots * gPayloadLengthStatic * 2 Static payload slots. * FrPPayloadLengthDynMax * * */ MB_HEADER_t * getHeader( struct FR_tag *hwPtr, uint16 idx ) { MB_HEADER_t *h; h = (MB_HEADER_t *)(idx * 8u + (((uint32)hwPtr->SYSBADHR.R)<<16) + ((uint32)hwPtr->SYSBADLR.R) ); return h; } uint8 * getPayload( const Fr_FrIfCCTriggeringType *trigCfg, uint32 msgBufIdx ) { uint8 *h; h = (uint8 *)trigCfg->FrMsgBufferCfg[msgBufIdx].FrDataPartitionAddr; return h; } boolean slotIsStatic(const Fr_FrIfClusterConfigType *clCfg, uint32 slotId ) { boolean rv = FALSE; if( slotId < clCfg->FrClusterGNumberOfStaticSlots ) { rv = TRUE; } return rv; } /** * Disable Tx * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_ClearPendingTx(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { Std_ReturnType retval = E_OK; /* IMPROVMENT */ return retval; } /** * Disable Rx * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_ClearPendingRx(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { Std_ReturnType retval = E_OK; /* IMPROVEMENT */ return retval; } /** * Compares the parameters written to register to those defined in the config. * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_RunCCTest(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { Std_ReturnType retval = E_OK; return retval; } /** * Wait for expression _wait_exp to become true for _us. */ static uint32 busyRead_1us( volatile const uint16 *baseAddr, uint16 mask, uint16 match) { uint32 rv = CMD_TIMEOUT; uint32 s = Timer_GetTicks(); while ( TIMER_TICK2US(Timer_GetTicks() - s) < (50u) ) { if( (*baseAddr & mask) == match ) { rv = CMD_OK; break; } } return rv; } static Std_ReturnType PCRInit( const Fr_ContainerType *Fr_Cfg, struct FR_tag *hwPtr, uint8 cIdx ) { const Fr_CtrlConfigParametersType *paramPtr = &Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx]; const Fr_FrIfClusterConfigType *cCfg = &Fr_Cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; const Fr_FrIfCCTriggeringType *FrTrigConf = &Fr_Cfg->Fr_ConfigPtr->FrTrigConfig[cIdx]; uint32 noiseListenTimeout; uint32 microPerCyleMin; uint32 microPerCyleMax; uint32 errCnt = 0; Std_ReturnType rv = E_OK; /* More or less a direct copy of * "Table 46-13. Protocol Configuration Register (PCR0-30) Fields" from the RM */ /** PCR[0] */ DIAG_SET( hwPtr->PCR0.B.STATIC_SLOT_LENGTH , cCfg->FrClusterGdStaticSlot ); _debug_init_("STATIC_SLOT_LENGTH=%d [MT]\n",hwPtr->PCR0.B.STATIC_SLOT_LENGTH); DIAG_SET( hwPtr->PCR0.B.ACTION_POINT_OFFSET , cCfg->FrClusterGdActionPointOffset - 1u); /** PCR[1] */ DIAG_SET( hwPtr->PCR1.B.MACRO_AFTER_FIRST_STATIC_SLOT , cCfg->FrClusterGMacroPerCycle - cCfg->FrClusterGdStaticSlot); /** PCR[2] */ DIAG_SET( hwPtr->PCR2.B.MINISLOT_AFTER_ACTION_POINT , cCfg->FrClusterGdMinislot - cCfg->FrClusterGdMiniSlotActionPointOffset - 1u); DIAG_SET( hwPtr->PCR2.B.NUMBER_OF_STATIC_SLOTS , cCfg->FrClusterGNumberOfStaticSlots); _debug_init_("NUMBER_OF_STATIC_SLOTS=%d\n",hwPtr->PCR2.B.NUMBER_OF_STATIC_SLOTS); /** PCR[3] */ DIAG_SET( hwPtr->PCR3.B.COLDSTART_ATTEMPTS , cCfg->FrClusterGColdStartAttempts); DIAG_SET( hwPtr->PCR3.B.MINISLOT_ACTION_POINT_OFFSET , cCfg->FrClusterGdMiniSlotActionPointOffset - 1u); DIAG_SET( hwPtr->PCR3.B.WAKEUP_SYMBOL_RX_LOW , cCfg->FrClusterGdWakeupRxLow); /** PCR[4] */ DIAG_SET( hwPtr->PCR4.B.CAS_RX_LOW_MAX , cCfg->FrClusterGdCasRxLowMax - 1u); DIAG_SET( hwPtr->PCR4.B.WAKEUP_SYMBOL_RX_WINDOW , cCfg->FrClusterGdWakeupRxWindow); /** PCR[5] */ DIAG_SET( hwPtr->PCR5.B.TSS_TRANSMITTER , cCfg->FrClusterGdTSSTransmitter); DIAG_SET( hwPtr->PCR5.B.WAKEUP_SYMBOL_RX_IDLE , cCfg->FrClusterGdWakeupRxIdle); DIAG_SET( hwPtr->PCR5.B.WAKEUP_SYMBOL_TX_LOW , cCfg->FrClusterGdWakeupTxActive); /* Maps to gdWakeupSymbolTxLow */ /** PCR[6] */ if (cCfg->FrClusterGdSymbolWindow != 0u) { DIAG_SET( hwPtr->PCR6.B.SYMBOL_WINDOW_AFTER_ACTION_POINT , cCfg->FrClusterGdSymbolWindow - cCfg->FrClusterGdActionPointOffset - 1u); } DIAG_SET( hwPtr->PCR6.B.MACRO_INITIAL_OFFSET_A , paramPtr->FrPMacroInitialOffsetA); /** PCR[7] */ /* From FR 2.1: pMicroPerMacroNom, renamed in FR 3.0 to aMicroPerMacroNom * * Calculation (from 2.1) : * pMicroPerMacroNom[µT/MT]= gdMacrotick[µs/MT] / pdMicrotick[µs/µT]= pMicroPerCycle[µT] / gMacroPerCycle[MT] */ DIAG_SET( hwPtr->PCR7.B.MICRO_PER_MACRO_NOM_HALF , (paramPtr->FrPMicroPerCycle / cCfg->FrClusterGMacroPerCycle) / 2 ); // IMPROVEMENT, so this is floor() and not round(pMicroPerMacroNom / 2) _debug_init_("MICRO_PER_MACRO_NOM_HALF=%d\n",hwPtr->PCR7.B.MICRO_PER_MACRO_NOM_HALF); DIAG_SET( hwPtr->PCR7.B.DECODING_CORRECTION_B , paramPtr->FrPDecodingCorrection + paramPtr->FrPDelayCompensationB + 2u); /** PCR[8] */ DIAG_SET( hwPtr->PCR8.B.WAKEUP_SYMBOL_TX_IDLE , cCfg->FrClusterGdWakeupTxIdle); DIAG_SET( hwPtr->PCR8.B.MAX_WITHOUT_CLOCK_CORRECTION_FATAL , cCfg->FrClusterGMaxWithoutClockCorrectFatal); DIAG_SET( hwPtr->PCR8.B.MAX_WITHOUT_CLOCK_CORRECTION_PASSIVE , cCfg->FrClusterGMaxWithoutClockCorrectPassive); /** PCR[9] */ DIAG_SET( hwPtr->PCR9.B.SYMBOL_WINDOW_EXISTS , (cCfg->FrClusterGdSymbolWindow != 0u) ? 1u : 0u); DIAG_SET( hwPtr->PCR9.B.MINISLOT_EXISTS , ( cCfg->FrClusterGNumberOfMinislots != 0u) ? 1u : 0u); DIAG_SET( hwPtr->PCR9.B.OFFSET_CORRECTION_OUT , paramPtr->FrPOffsetCorrectionOut); /** PCR[10] */ DIAG_SET( hwPtr->PCR10.B.MACRO_PER_CYCLE , cCfg->FrClusterGMacroPerCycle); _debug_init_("MACRO_PER_CYCLE=%d\n",hwPtr->PCR10.B.MACRO_PER_CYCLE); DIAG_SET( hwPtr->PCR10.B.SINGLE_SLOT_ENABLED , paramPtr->FrPKeySlotOnlyEnabled); /* Maps to pSingleSlotEnabled */ DIAG_SET( hwPtr->PCR10.B.WAKEUP_CHANNEL , (int)paramPtr->FrPWakeupChannel); /** PCR[11] */ DIAG_SET( hwPtr->PCR11.B.OFFSET_CORRECTION_START , paramPtr->FrPOffsetCorrectionStart); /* Named gOffsetCorrectionStart in FlexRay 3.0 */ DIAG_SET( hwPtr->PCR11.B.KEY_SLOT_USED_FOR_STARTUP , paramPtr->FrPKeySlotUsedForStartup); DIAG_SET( hwPtr->PCR11.B.KEY_SLOT_USED_FOR_SYNC , paramPtr->FrPKeySlotUsedForSync); /** PCR[12] */ DIAG_SET( hwPtr->PCR12.B.ALLOW_PASSIVE_TO_ACTIVE , paramPtr->FrPAllowPassiveToActive); /* Pre-calc header CRC * - Sync frame ind + Startup Frame Ind + Frame ID + Payload Length -> 20 bits * */ { uint32 keySlotIdx; Std_ReturnType status; uint32 crc; status = findTrigIdx(FrTrigConf, paramPtr->FrPKeySlotId, &keySlotIdx); if( status != E_OK ) { return E_NOT_OK; } crc = getHeaderCrc(Fr_Cfg, cIdx, keySlotIdx, FrTrigConf->FrTrigConfPtr[keySlotIdx].FrTrigLSduLength); DIAG_SET( hwPtr->PCR12.B.KEY_SLOT_HEADER_CRC , crc); _debug_init_("KeySlotId=%d CRC=0x%04x\n", paramPtr->FrPKeySlotId, hwPtr->PCR12.B.KEY_SLOT_HEADER_CRC); } /** PCR[13] */ DIAG_SET( hwPtr->PCR13.B.STATIC_SLOT_AFTER_ACTION_POINT , cCfg->FrClusterGdStaticSlot - cCfg->FrClusterGdActionPointOffset - 1u); DIAG_SET( hwPtr->PCR13.B.FIRST_MINISLOT_ACTION_POINT_OFFSET , MAX( cCfg->FrClusterGdActionPointOffset , cCfg->FrClusterGdMiniSlotActionPointOffset) - 1u); /** PCR[14] */ DIAG_SET( hwPtr->PCR14.B.LISTEN_TIMEOUT_H , (vuint16_t)_HIGH16(paramPtr->FrPdListenTimeout)); DIAG_SET( hwPtr->PCR14.B.RATE_CORRECTION_OUT , paramPtr->FrPRateCorrectionOut); /** PCR[15] */ DIAG_SET( hwPtr->PCR15.B.LISTEN_TIMEOUT_L , (vuint16_t)_LOW16(paramPtr->FrPdListenTimeout)); /** PCR[16] */ noiseListenTimeout = (cCfg->FrClusterGListenNoise * paramPtr->FrPdListenTimeout) - 1u; DIAG_SET( hwPtr->PCR16.B.NOISE_LISTEN_TIMEOUT_H , (vuint16_t)_HIGH16(noiseListenTimeout)); /* (gListenNoise * pdListenTimeout) - 1 */ DIAG_SET( hwPtr->PCR16.B.MACRO_INITIAL_OFFSET_B , paramPtr->FrPMacroInitialOffsetB); /** PCR[17] */ DIAG_SET( hwPtr->PCR17.B.NOISE_LISTEN_TIMEOUT_L , (vuint16_t)_LOW16(noiseListenTimeout)); /** PCR[18] */ DIAG_SET( hwPtr->PCR18.B.KEY_SLOT_ID , paramPtr->FrPKeySlotId); DIAG_SET( hwPtr->PCR18.B.WAKEUP_PATTERN , paramPtr->FrPWakeupPattern); /** PCR[19] */ DIAG_SET( hwPtr->PCR19.B.PAYLOAD_LENGTH_STATIC , cCfg->FrClusterGPayloadLengthStatic); DIAG_SET( hwPtr->PCR19.B.DECODING_CORRECTION_A , paramPtr->FrPDecodingCorrection + paramPtr->FrPDelayCompensationA + 2u); /** PCR[20] */ DIAG_SET( hwPtr->PCR20.B.MICRO_INITIAL_OFFSET_A , paramPtr->FrPMicroInitialOffsetA); DIAG_SET( hwPtr->PCR20.B.MICRO_INITIAL_OFFSET_B , paramPtr->FrPMicroInitialOffsetB); /** PCR[21] */ DIAG_SET( hwPtr->PCR21.B.LATEST_TX , cCfg->FrClusterGNumberOfMinislots - paramPtr->FrPLatestTx); /* * FR+RM Autosar * EXTERN_RATE_CORRECTION pExternRateCorrection Nothing..... * * This is cluster sync parameters.. we just leave it at 0 (we are proably not syncing clusters) */ DIAG_SET( hwPtr->PCR21.B.EXTERN_RATE_CORRECTION , 0u); /* pExternRateCorrection not found in Autosar */ /** PCR[22] */ DIAG_SET( hwPtr->PCR22.B.COMP_ACCEPTED_STARTUP_RANGE_A , paramPtr->FrPdAcceptedStartupRange - paramPtr->FrPDelayCompensationA); DIAG_SET( hwPtr->PCR22.B.MICRO_PER_CYCLE_H , (vuint16_t)_HIGH16(paramPtr->FrPMicroPerCycle)); /** PCR[23] */ DIAG_SET( hwPtr->PCR23.B.micro_per_cycle_l , (vuint16_t)_LOW16(paramPtr->FrPMicroPerCycle)); /** PCR[24] */ DIAG_SET( hwPtr->PCR24.B.MAX_PAYLOAD_LENGTH_DYNAMIC , paramPtr->FrPPayloadLengthDynMax); DIAG_SET( hwPtr->PCR24.B.CLUSTER_DRIFT_DAMPING , paramPtr->FrPClusterDriftDamping); microPerCyleMin = paramPtr->FrPMicroPerCycle - paramPtr->FrPRateCorrectionOut; /* pdMaxDrift was replaced by pRateCorrectionOut in FR3.0 */ microPerCyleMax = paramPtr->FrPMicroPerCycle + paramPtr->FrPRateCorrectionOut; /* pdMaxDrift was replaced by pRateCorrectionOut in FR3.0 */ DIAG_SET( hwPtr->PCR24.B.MICRO_PER_CYCLE_MIN_H , (vuint16_t)_HIGH16(microPerCyleMin)); /** PCR[25] */ DIAG_SET( hwPtr->PCR25.B.MICRO_PER_CYCLE_MIN_L , (vuint16_t)_LOW16(microPerCyleMin)); /** PCR[26] */ DIAG_SET( hwPtr->PCR26.B.ALLOW_HALT_DUE_TO_CLOCK , paramPtr->FrPAllowHaltDueToClock); DIAG_SET( hwPtr->PCR26.B.COMP_ACCEPTED_STARTUP_RANGE_B , paramPtr->FrPdAcceptedStartupRange - paramPtr->FrPDelayCompensationB); DIAG_SET( hwPtr->PCR26.B.MICRO_PER_CYCLE_MAX_H, (vuint16_t)_HIGH16(microPerCyleMax)); /** PCR[27] */ DIAG_SET( hwPtr->PCR27.B.MICRO_PER_CYCLE_MAX_L , (vuint16_t)_LOW16(microPerCyleMax)); /** PCR[28] */ DIAG_SET( hwPtr->PCR28.B.DYNAMIC_SLOT_IDLE_PHASE , cCfg->FrClusterGdDynamicSlotIdlePhase); DIAG_SET( hwPtr->PCR28.B.MACRO_AFTER_OFFSET_CORRECTION , cCfg->FrClusterGMacroPerCycle - paramPtr->FrPOffsetCorrectionStart); /** PCR[29] */ DIAG_SET( hwPtr->PCR29.B.MINISLOTS_MAX , (cCfg->FrClusterGNumberOfMinislots - 1u)); /* pExternOffsetCorrection in FR3.0, but not in recent autosar specs... set to 0 */ DIAG_SET( hwPtr->PCR29.B.EXTERN_OFFSET_CORRECTION , 0); /** PCR[30] */ DIAG_SET( hwPtr->PCR30.B.SYNC_NODE_MAX , cCfg->FrClusterGSyncFrameIDCountMax); if ( errCnt != 0u ) { rv = E_NOT_OK; } return rv; } /** * Setup the Message RAM and header for the configured FrIf triggering units. * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_SetupRxTxResources(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { /* Protocol Initialization * 1. Configure the Protocol Engine * a. issue CONFIG command via Protocol Operation Control Register (FR_POCR) * b. wait for POC:config in Protocol Status Register 0 (FR_PSR0) * c. configure the FR_PCR0,…, FR_PCR30 registers to set all protocol parameters * 2. Configure the Message Buffers and FIFOs. * a. set the number of message buffers used and the message buffer * segmentation in the Message Buffer Segment Size and Utilization Register (FR_MBSSUTR) * b. define the message buffer data size in the Message Buffer Data Size Register(FR_MBDSR) * c. configure each message buffer by setting the configuration values in the * Message Buffer Configuration, Control, Status Registers (FR_MBCCSRn), * Message Buffer Cycle Counter Filter Registers (FR_MBCCFRn), Message * Buffer Frame ID Registers (FR_MBFIDRn), Message Buffer Index Registers * (FR_MBIDXRn) * d. configure the FIFOs * e. issue CONFIG_COMPLETE command via Protocol Operation Control Register * (FR_POCR) * f. wait for POC:ready in Protocol Status Register 0 (FR_PSR0) */ const Fr_FrIfCCTriggeringType *trigCfg = &Fr_Cfg->Fr_ConfigPtr->FrTrigConfig[cIdx]; const Fr_CtrlConfigParametersType *paramPtr = &Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx]; const Fr_FrIfTriggeringConfType *trigElem; const Fr_FrIfClusterConfigType *clCfg = &Fr_Cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; Fr_Info.cfg = Fr_Cfg; volatile MSG_BUFF_CCS_t *mbPtr; struct FR_tag *hwPtr = Fr_HwReg[cIdx]; uint32 n; uint32 headerIndex = 0; uint32 rv; Std_ReturnType pcrInitRv; uint8 ccErrCnt = 0; boolean isStatic; uint32 staticCnt = 0u; uint32 dynamicCnt = 0u; /* 1a) Transition to the POC:config state. */ Fr_HwReg[cIdx]->POCR.R = (1u << (15u-0u)) | /* WME */ (2u << (15u-15u)); /* POCCMD = CONFIG */ /* 1b) POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } /* Wait until in POC:config */ rv = busyRead_1us( &Fr_HwReg[cIdx]->PSR0.R, (7u<<(15u-7u)),(1u<<(15u-7u))); /* PROTSTATE : 1 - POC:config */ if( rv != CMD_OK ) { return E_NOT_OK; } /* 1c) */ #if (FR_CTRL_TEST_COUNT > 0) for(n = 0; n < FR_CTRL_TEST_COUNT; n++) { /* @req SWS_Fr_00647 */ pcrInitRv = PCRInit(Fr_Cfg, hwPtr, cIdx); /* @req SWS_Fr_00598 */ if (pcrInitRv == E_OK) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_PASSED); break; } else { ccErrCnt++; } } /* @req SWS_Fr_00147 */ if (ccErrCnt == FR_CTRL_TEST_COUNT) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_FAILED); return E_NOT_OK; } #endif /* The hardware have: * 1. Individual Message Buffers * 2. Receive Shadow Buffers * 3. Receive FIFO Buffers * * Of these we setup 1) and 2) and choose NOT to support 3) * * The FrIfFrameTriggering that holds the slot information = Message Box * so we set that up. */ /* 2a) */ /* Place all static buffers in segment 1, dynamic in segment 2 */ hwPtr->MBSSUTR.B.LAST_MB_SEG1 = trigCfg->FrNbrTrigStatic - 1u; hwPtr->MBSSUTR.B.LAST_MB_UTIL = trigCfg->FrNbrTrigConfiged - 1u; /* 2b) */ hwPtr->MBDSR.B.MBSEG1DS = clCfg->FrClusterGPayloadLengthStatic; hwPtr->MBDSR.B.MBSEG2DS = paramPtr->FrPPayloadLengthDynMax; _debug_init_("LAST_MB_SEG1 %d\n",hwPtr->MBSSUTR.B.LAST_MB_SEG1); _debug_init_("LAST_MB_UTIL %d\n",hwPtr->MBSSUTR.B.LAST_MB_UTIL); _debug_init_("MBSEG1DS %d\n",hwPtr->MBDSR.B.MBSEG1DS); _debug_init_("MBSEG2DS %d\n",hwPtr->MBDSR.B.MBSEG2DS); /** 2c) Configure Individial Message Buffers */ /* precalc some values */ uint32 baseAddr = ( (((uint32)hwPtr->SYSBADHR.R)<<16) + ((uint32)hwPtr->SYSBADLR.R) ); uint32 hdrSize = ((trigCfg->FrNbrTrigConfiged + SHADOW_BUFFER_CNT) * 8u); /* Total number of headers */ uint32 seg1Size = (clCfg->FrClusterGPayloadLengthStatic * (trigCfg->FrNbrTrigStatic) * 2u ); uint32 seg2Size = (ALIGN8(paramPtr->FrPPayloadLengthDynMax) * (trigCfg->FrNbrTrigConfiged - trigCfg->FrNbrTrigStatic) * 2u ); _debug_init_("baseaddr =0x%08x\n",baseAddr); _debug_init_("hdrSize =0x%08x\n",hdrSize); _debug_init_("seg1Size =0x%08x\n",seg1Size); _debug_init_("seg2Size =0x%08x\n",seg2Size); for (n = 0; n < trigCfg->FrNbrTrigConfiged; n++) { _debug_init_("==== msg %d ====\n",n); /** * Add each trigger to a message box */ trigElem = &trigCfg->FrTrigConfPtr[n]; mbPtr = &hwPtr->MBCCS[n]; /** MBCCSR */ /* Check if enabled */ if( mbPtr->MBCCSR.B.EDS ) { mbPtr->MBCCSR.B.EDT = 1u; /* Trigger Enable->Disable */ } if (trigElem->FrTrigIsTx ) { mbPtr->MBCCSR.B.MTD = 1u; /* 0 - Rx, 1 - Tx */ } _debug_init_(" isTx=%d\n",mbPtr->MBCCSR.B.MTD ); /** MBCCFR */ if (trigElem->FrTrigChannel == FR_CHANNEL_AB) { mbPtr->MBCCFR.B.CHNLA = 1u; mbPtr->MBCCFR.B.CHNLB = 1u; } else if (trigElem->FrTrigChannel == FR_CHANNEL_B) { mbPtr->MBCCFR.B.CHNLB = 1u; } else if (trigElem->FrTrigChannel == FR_CHANNEL_A) { mbPtr->MBCCFR.B.CHNLA = 1u; } /* * Event/State transmission. * This relates have relation to FrIfAlwaysTransmit... * MTM: 0 - Message transmitted only once * MTM: 1 - Message is transmitted continuously * * FrIfAlwaysTransmit MTM * -------------------------------------------------------- * 0 0 -> Send NULL frame when no new data. * 0 1 -> Send Latest data even if no new data. * 1 0 -> Will send NO Null frames... just latest data. * 1 1 -> Pointless, data will be updated. * * ---> It seems to be most sane to send only updated data, NULL frames otherwise, * so, we keep MTM at 0. */ mbPtr->MBCCFR.B.MTM = 0u; /* See above */ /* It seems that cycle filtering can't be turned off in Autosar... so let's set it up * Logical expression: CYCCNT & MBCCFRn[CCFMSK] = MBCCFRn[CCFVAL] & MBCCFRn[CCFMSK] * * FrIfCycleRepetition - 1,2,4,8,16,32,64 * FrIfBaseCycle - 0 -- 63 * */ mbPtr->MBCCFR.B.CCFMSK = trigElem->FrTrigCycleRepetition - 1; mbPtr->MBCCFR.B.CCFVAL = trigElem->FrTrigBaseCycle; mbPtr->MBCCFR.B.CCFE = 1u; /* 1 - Cycle counter filtering enabled */ /** MBFIDRn */ /* SlotID = FrameID */ mbPtr->MBFIDR.B.FID = trigElem->FrTrigSlotId; _debug_init_(" SlotID=%d\n",mbPtr->MBFIDR.B.FID); /** MBIDXRn */ /* MBIDXRn index to: * - Header : SADR_MBHF= (FR_MBIDXn.MBIDX*8 + FR_SYMBADR.SMBA) * - Frame Data: SADR_MBDF= FR_MBDORn.MBDO + FR_SYMBADR.SMBA */ hwPtr->MBCCS[n].MBIDXR.B.MBIDX = n; isStatic = slotIsStatic(clCfg, trigElem->FrTrigSlotId ); uint32 offset; /* Calc payload addresses * After the headers (hdrSize) we have the payloads. Lets allocate static * buffers in one segment and dynamic in a section after that. * * Headers * Shadow Headers * Static Payloads * Dynamic Payloads * */ if (isStatic) { /* Static (SEG1) starts after the headers */ offset = hdrSize + (clCfg->FrClusterGPayloadLengthStatic * staticCnt * 2u); staticCnt++; _debug_init_(" Static\n"); } else { /* Dynamic (SEG2) starts after SEG1 */ offset = hdrSize + seg1Size + (ALIGN8(paramPtr->FrPPayloadLengthDynMax) * dynamicCnt * 2u ); dynamicCnt++; _debug_init_(" Dynamic\n"); } trigCfg->FrMsgBufferCfg[n].FrDataPartitionAddr = baseAddr + offset; hwPtr->MBDOR[n].B.MBDO = offset; _debug_init_(" MBDO=0x%08x (0x%08x) (\n",hwPtr->MBDOR[n].B.MBDO, trigCfg->FrMsgBufferCfg[n].FrDataPartitionAddr ); /* Not use so put in any data != 0 */ // trigCfg->FrMsgBufferCfg[n].FrDataPartitionAddr = 1UL; /* Trigger Index = Buffer Index*/ trigCfg->FrMsgBufferCfg[n].FrMsgBufferIdx = n; /* Pre-calculate CRC for header for static slots */ { uint32 crc; MB_HEADER_t *hPtr; hPtr = getHeader(hwPtr,n); if (trigElem->FrTrigPayloadPreamble == true){ hPtr->FRAME_HEADER.B.PPI = 1; }else{ hPtr->FRAME_HEADER.B.PPI = 0; } if( isStatic ) { /* Calculate header from configuration... not on the header itself */ crc = getHeaderCrc(Fr_Cfg,cIdx, n, 0u ); /* Length "0u" is don't care here since it's static */ hPtr->FRAME_HEADER.B.HDCRC = crc; _debug_init_(" Header: Addr=0x%08x, CRC=0x%08x\n",(uint32)hPtr,crc); } else{ /*if dynamic frame*/ /* Calculate header from configuration... not on the header itself */ crc = getHeaderCrc(Fr_Cfg,cIdx, n, (trigElem->FrTrigLSduLength) ); hPtr->FRAME_HEADER.B.HDCRC = crc; _debug_init_(" Header: Addr=0x%08x, CRC=0x%08x\n",(uint32)hPtr,crc); } /* Set FID and length */ hPtr->FRAME_HEADER.B.FID = trigElem->FrTrigSlotId; hPtr->FRAME_HEADER.B.PLDLEN = (trigElem->FrTrigLSduLength>>1u); _debug_init_(" Header: FID=0x%08x, PLDLEN=0x%08x\n",hPtr->FRAME_HEADER.B.FID,hPtr->FRAME_HEADER.B.PLDLEN); } /* Enable buffer */ mbPtr->MBCCSR.B.EDT = 1u; } headerIndex = trigCfg->FrNbrTrigConfiged; /** * Configure Receive Shadow Buffers * * RSBIR controls all the shadow buffers */ Fr_Info.staticSlots = staticCnt; Fr_Info.dynamicSlots= dynamicCnt; /* Shadow Buffers * * Allocate the shadow buffers after headers and SEG1 and SEG2 buffers * * */ uint32 sdataBuff = hdrSize + seg1Size + seg2Size; hwPtr->RSBIR.R = (0u << (15u-3u)) | (headerIndex) ;/* A, Seg 1 - SEL */ hwPtr->MBDOR[headerIndex].B.MBDO = sdataBuff; trigCfg->FrMsgBufferCfg[headerIndex].FrDataPartitionAddr = baseAddr + sdataBuff; _debug_init_("Shadow A Seg1 MBDO=0x%08x, Index=%d\n",hwPtr->MBDOR[headerIndex].B.MBDO,headerIndex ); headerIndex++; sdataBuff += (clCfg->FrClusterGPayloadLengthStatic * 2u); hwPtr->RSBIR.R = (2u << (15u-3u)) | (headerIndex) ;/* B, Seg 1 - SEL */ hwPtr->MBDOR[headerIndex].B.MBDO = sdataBuff; trigCfg->FrMsgBufferCfg[headerIndex].FrDataPartitionAddr = baseAddr + sdataBuff; _debug_init_("Shadow B Seg1 MBDO=0x%08x, Index=%d\n",hwPtr->MBDOR[headerIndex].B.MBDO,headerIndex ); headerIndex++; sdataBuff += (clCfg->FrClusterGPayloadLengthStatic * 2u); hwPtr->RSBIR.R = (1u << (15u-3u)) | (headerIndex) ;/* A, Seg 2 - SEL */ hwPtr->MBDOR[headerIndex].B.MBDO = sdataBuff; trigCfg->FrMsgBufferCfg[headerIndex].FrDataPartitionAddr = baseAddr + sdataBuff; _debug_init_("Shadow A Seg2 MBDO=0x%08x, Index=%d\n",hwPtr->MBDOR[headerIndex].B.MBDO,headerIndex ); headerIndex++; sdataBuff += (ALIGN8(paramPtr->FrPPayloadLengthDynMax) * 2u); hwPtr->RSBIR.R = (3u << (15u-3u)) | (headerIndex) ;/* B, Seg 2 - SEL */ hwPtr->MBDOR[headerIndex].B.MBDO = sdataBuff; trigCfg->FrMsgBufferCfg[headerIndex].FrDataPartitionAddr = baseAddr + sdataBuff; _debug_init_("Shadow B Seg2 MBDO=0x%08x, Index=%d\n",hwPtr->MBDOR[headerIndex].B.MBDO,headerIndex ); /* 2d) FIFO.... we don't use them */ /* 2e) Issue CONFIG_COMPLETE */ Fr_HwReg[cIdx]->POCR.R = (1u << (15u-0u)) | /* WME */ (4u << (15u-15u)); /* POCCMD = CONFIG_COMPLETE */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0u); if( rv != CMD_OK ) { return E_NOT_OK; } /* Wait until in POC:ready */ rv = busyRead_1us( &Fr_HwReg[cIdx]->PSR0.R, (7u<<(15u-7u)),(3u<<(15u-7u))); /* PROTSTATE : 3 - POC:ready */ if( rv != CMD_OK ) { return E_NOT_OK; } return E_OK; } /** * Used to find the trigger index linked to the LPdu * @param FrTrigConf * @param searchedId * @param trigIdx * @return */ static Std_ReturnType findTrigIdx(const Fr_FrIfCCTriggeringType *FrTrigConf, uint32 searchedId, uint32 *trigIdx) { uint32 n; for (n = 0; n < FrTrigConf->FrNbrTrigConfiged; n++) { if (FrTrigConf->FrTrigConfPtr[n].FrTrigSlotId == searchedId) { *trigIdx = n; return E_OK; } } return E_NOT_OK; } /** * Updates the length of a message buffer * @param Fr_Cfg * @param cIdx * @param msgBuffrIdx * @return */ Std_ReturnType Fr_Internal_UpdateHeaderLength(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 length, uint16 msgBufferIdx, uint32 frameTrigIdx) { Std_ReturnType retval = E_OK; struct FR_tag *hwPtr = Fr_HwReg[cIdx]; MB_HEADER_t *hPtr; uint32 crc; /* This is for dynamic messages only. * Since the length is in the header we need to re-calc the header CRC. * 1. Write length is buffer. * 2. Re-calc header CRC */ hPtr = getHeader(hwPtr,msgBufferIdx); /* 1) Write length */ hPtr->FRAME_HEADER.B.PLDLEN = (length>>1u); /* 2) Re-calc header CRC */ crc = getHeaderCrc(Fr_Cfg,cIdx, msgBufferIdx, length); hPtr->FRAME_HEADER.B.HDCRC = crc; return retval; } /** * Calculate checksum according to Flexray specification chapter 4.5. * @param Fr_Cfg * @param Fr_CtrlIdx * @param frameTrigIdx * @return */ /* !@req Flexray specification does not allow CC to calculate checksum */ static uint32 getHeaderCrc(const Fr_ContainerType *Fr_Cfg, uint8 Fr_CtrlIdx, uint32 frameTrigIdx, uint32 dynLen){ const Fr_FrIfTriggeringConfType *FrTrigConf = &Fr_Cfg->Fr_ConfigPtr->FrTrigConfig[Fr_CtrlIdx].FrTrigConfPtr[frameTrigIdx]; const Fr_FrIfClusterConfigType *clusterParamPtr = &Fr_Cfg->Fr_ConfigPtr->FrClusterConfig[Fr_CtrlIdx]; const Fr_CtrlConfigParametersType *paramPtr = &Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx]; // Data setup uint32 keySlotId = Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[Fr_CtrlIdx].FrPKeySlotId; uint8 slotIsKey = (FrTrigConf->FrTrigSlotId == keySlotId) ? 1 : 0; uint32 syncFrameInd = ((slotIsKey > 0) && paramPtr->FrPKeySlotUsedForSync) ? (uint32)1 : (uint32)0; uint32 startFrameInd = ((slotIsKey > 0) && paramPtr->FrPKeySlotUsedForStartup) ? (uint32)1 : (uint32)0; uint32 payloadLen = (FrTrigConf->FrTrigSlotId > clusterParamPtr->FrClusterGNumberOfStaticSlots) ? \ (dynLen/FR_LENGTH_DIV) : clusterParamPtr->FrClusterGPayloadLengthStatic; uint32 data = (syncFrameInd << 19u) | (startFrameInd << 18u) | (FrTrigConf->FrTrigSlotId << 7u) | (payloadLen); _debug_init_("CRC info: TrigSlotId=%d, slotisKey=%d, sync=%d, start=%d, len=%d\n",FrTrigConf->FrTrigSlotId,slotIsKey,syncFrameInd, startFrameInd,payloadLen); //Checksum calculation uint32 vCrcPolynomial = V_CRC_POLYNOMIAL; sint32 vNextBitIdx; uint32 vCrcReg = V_CRC_INIT; uint32 vCrcNext; uint32 nextBit; for (vNextBitIdx = 19; vNextBitIdx >= 0; vNextBitIdx--) { nextBit = (data >> (uint32)vNextBitIdx) & (uint32)0x01; vCrcNext = nextBit ^ ((vCrcReg >> (V_CRC_SIZE-1)) & (uint32)0x01); vCrcReg = vCrcReg << 1u; if (vCrcNext > 0) { vCrcReg = vCrcReg ^ vCrcPolynomial; } } return (uint32)(vCrcReg & (uint32)0x7FF); } /** * Clear pending status bits * * Reference manual chapter 21.3.14, the Host has access to the actual status and error information by reading registers * FLXAnFREIR, FLXAnFRSIR, FLXAnFROS, FLXAnFROTS and FLXAnFRITS. * * @param Fr_Cfg * @param cIdx */ void Fr_Arc_ClearPendingIsr(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { } /** * Disable all absolut timers * @param Fr_Cfg * @param cIdx */ void Fr_Internal_DisableAllTimers(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { } /** * Disable all interrupts * * @param Fr_Cfg * @param cIdx */ void Fr_Internal_DisableAllFrIsr(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { } /** * Run the configuration test n number of times and report status to the DEM. * @param cIdx * @return */ Std_ReturnType Fr_Internal_RunAllCCTest(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { Std_ReturnType retval = E_OK; Std_ReturnType status; uint8 ccErrCnt = 0; uint8 n; #if (FR_CTRL_TEST_COUNT > 0) for(n = 0; n < FR_CTRL_TEST_COUNT; n++) { /* @req FR647 */ status = Fr_Internal_RunCCTest(Fr_Cfg, cIdx); /* @req FR598 */ if (status == E_OK) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_PASSED); break; } else { ccErrCnt++; } } /* @req FR147 */ if (ccErrCnt == FR_CTRL_TEST_COUNT) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_FAILED); retval = E_NOT_OK; } #endif return retval; } /** * Set the CHI command according to FLXAnFRSUCC1.CMD page 991 ref manual. * @param Fr_Cfg * @param cIdx * @param chiCmd * @return */ Std_ReturnType Fr_Internal_SetCtrlChiCmd(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 chiCmd) { Std_ReturnType retval = E_OK; uint32 rv; Fr_HwReg[cIdx]->POCR.R = (1u << (15u-0u)) | /* WME */ (chiCmd << (15u-15u)); /* POCCMD = chiCmd*/ /* Wait for write cmd to complete, POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } /* Check for illegal transition */ if( Fr_HwReg[cIdx]->PIFR1.B.IPCIF ) { /* @req SWS_Fr_00181, Fr_AllowColdstart */ /* @req SWS_Fr_00186, Fr_HaltCommunication */ /* @req SWS_Fr_00190, Fr_AbortCommunication */ /* @req SWS_Fr_00195, Fr_SendWUP */ /* @req SWS_Fr_00201, Fr_SetWakeupChannel*/ DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_FAILED); retval = E_NOT_OK; Fr_HwReg[cIdx]->PIFR1.B.IPCIF = 1u; /* Clear error */ } return retval; } /** * Will enable controller if its disabled. * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_EnableCtrl(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { return E_OK; } /** * Setup the CC according to all configuration parameters and run the CC test. * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_setupAndTestCC(Fr_ContainerType *Fr_Cfg, uint8 cIdx) { const Fr_CtrlConfigParametersType *paramPtr = &Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx]; const Fr_FrIfClusterConfigType *clusterParamPtr = &Fr_Cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; uint32 tmp = 0; uint32 rv; Std_ReturnType setupRv = E_NOT_OK; /* * Make sure that we start from a clean slate */ if( Fr_HwReg[cIdx]->MCR.B.MEN == 1ul ) { /* To POC:halt (since it's only there we can disable the module */ Fr_HwReg[cIdx]->POCR.R = (1u << (15u-0u)) | /* WME */ (POC_CMD_FREEZE << (15u-15u)); /* POCCMD */ /* Wait for write cmd to complete, POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } /* Back to POC:default_config (since it's only there we can disable the module */ Fr_HwReg[cIdx]->POCR.R = (1u << (15u-0u)) | /* WME */ (POC_CMD_DEFAULT_CONFIG << (15u-15u)); /* POCCMD */ /* Wait for write cmd to complete, POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } /* Disable module, for some bizarre reason it does not always bite the first time */ { uint32 s = Timer_GetTicks(); Fr_HwReg[cIdx]->MCR.B.MEN = 0; while( Fr_HwReg[cIdx]->MCR.B.MEN == 1 ) { if( TIMER_TICK2US(Timer_GetTicks() - s) > (50u) ) { return E_NOT_OK; } Fr_HwReg[cIdx]->MCR.B.MEN = 0; } } /* Wait for write cmd to complete, POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } } /* Init step: (from "Initialization Sequence" in RM) * * Module Initialization * 1. Configure CC * a. configure the control bits in the Module Configuration Register (FR_MCR) * b. configure the system memory base address in System Memory * Base Address Register (FR_SYMBADR) * 2. Enable the CC. * a. write 1 to the module enable bit MEN in the Module Configuration * Register (FR_MCR) */ /** * 1a) FR_MSR */ if( Fr_HwReg[cIdx]->MCR.B.MEN == 0ul ) { MCR_t mcr; mcr.R = 0; /* If we would need single channel mode set mcr.B.SCM = 1 */ /* FR_MCR : CHB and CHA (FlexRay Channel B Enable and FlexRay Channel A Enable) */ if (paramPtr->FrPChannels == FR_CHANNEL_AB) { mcr.B.CHA = 1; mcr.B.CHB = 1; } else if (paramPtr->FrPChannels == FR_CHANNEL_B) { mcr.B.CHB = 1; } else if (paramPtr->FrPChannels == FR_CHANNEL_A) { mcr.B.CHA = 1; } else { /* All Channels disabled. */ } /* FR_MCR : SFFE (Synchronization Frame Filter Enable) */ #if 0 if ( Fr_DriverSpecificConfigPtr->Fr_SynchronizationFrameFiltering) { u16Temp |= FR_MCR_SFFE; } /* FR_MCR : CLKSEL (Protocol Engine Clock Source Select) */ /* FR_BASE_CLOCK_PLL = The clock source is system clock / 3. This should only be used if the system frequency is 120 MHz. */ /* Else, the clock source is an on-chip crystal oscillator. */ if (Fr_DriverSpecificConfigPtr->Fr_ClockSource == FR_BASE_CLOCK_PLL) { u16Temp |= FR_MCR_CLKSEL; } #else mcr.B.SFFE = 0; /* 0 - Disable frame filtering * (IMPROVEMENT: check this )*/ mcr.B.CLKSEL = 0; /* 0 - PE clock source is generated by on-chip crystal oscillator. * (IMPROVEMENT: check this ) */ #endif /* gdBit defines the bitrate */ switch(clusterParamPtr->FrClusterGdBit) { case FR_T100NS: /* 10 Mbits/s */ tmp = 0; break; case FR_T200NS: /* 5 Mbits/s */ tmp = 1; break; case FR_T400NS: /* 2.5 Bbits/s */ tmp = 2; break; default: break; } mcr.B.BITRATE = tmp; _debug_init_("bdBit=%d\n",mcr.B.BITRATE); /* Save the FR_MCR configuration into its register. */ Fr_HwReg[cIdx]->MCR.R = mcr.R; /** * 1b) configure the system memory base address in System Memory Base Address Register (FR_SYMBADR) */ Fr_HwReg[cIdx]->SYSBADHR.R = (((uint32)(&Fr_MsgBuffers))>>16u); Fr_HwReg[cIdx]->SYSBADLR.R = (((uint32)(&Fr_MsgBuffers)) & 0xffffu ); /** * 2a) Enable the FlexRay module. * */ Fr_HwReg[cIdx]->MCR.B.MEN = 1; /* Normal Mode: The protocol engine is now in its default configuration state (POC:default config). */ /* Wait for write cmd to complete, POCR.B.BSY */ rv = busyRead_1us( &Fr_HwReg[cIdx]->POCR.R, (1u<<(15u-8u)),0); if( rv != CMD_OK ) { return E_NOT_OK; } setupRv = Fr_Internal_SetupRxTxResources(Fr_Cfg,cIdx); } return setupRv; } Fr_POCStateType Fr_Internal_GetProtState( const Fr_ContainerType *Fr_Cfg, uint8 cIdx ) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; Fr_POCStateType state; const Fr_POCStateType ProtStateList[] = { FR_POCSTATE_DEFAULT_CONFIG, FR_POCSTATE_CONFIG, FR_POCSTATE_WAKEUP, FR_POCSTATE_READY, FR_POCSTATE_NORMAL_PASSIVE, FR_POCSTATE_NORMAL_ACTIVE, FR_POCSTATE_HALT, FR_POCSTATE_STARTUP }; if( hwPtr->PSR1.B.FRZ ) { state = FR_POCSTATE_HALT; } else { state = ProtStateList[hwPtr->PSR0.B.PROTSTATE]; } return state; } /** * Read chi poc status. * @param Fr_Cfg * @param cIdx * @param Fr_POCStatusPtr * @return E_OK or E_NOT_OK */ Std_ReturnType Fr_Internal_GetChiPocState(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, Fr_POCStatusType* Fr_POCStatusPtr) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; Fr_POCStatusType pocStatus = {0}; uint32 errMode = hwPtr->PSR0.B.ERRMODE; uint32 slotMode = hwPtr->PSR0.B.SLOTMODE; pocStatus.CHIHaltRequest = hwPtr->PSR1.B.HHR ? TRUE : FALSE; pocStatus.ColdstartNoise = hwPtr->PSR1.B.CPN ? TRUE : FALSE; pocStatus.Freeze = hwPtr->PSR1.B.FRZ ? TRUE : FALSE; const Fr_SlotModeType SlotModeList[] = { FR_SLOTMODE_KEYSLOT, FR_SLOTMODE_ALL_PENDING, FR_SLOTMODE_ALL, }; if ( slotMode > 2u) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_FAILED); return E_NOT_OK; } pocStatus.SlotMode = SlotModeList[slotMode]; const Fr_ErrorModeType ErrModeList[] = { FR_ERRORMODE_ACTIVE, FR_ERRORMODE_PASSIVE, FR_ERRORMODE_COMM_HALT }; if ( errMode > 2u) { DEM_REPORT(Fr_Cfg->Fr_ConfigPtr->FrCtrlParam[cIdx].FrDemEventParamRef, DEM_EVENT_STATUS_FAILED); return E_NOT_OK; } pocStatus.ErrorMode = ErrModeList[errMode]; pocStatus.State = Fr_Internal_GetProtState(Fr_Cfg,cIdx); const Fr_StartupStateType StartupList[] = { FR_STARTUP_UNDEFINED, FR_STARTUP_UNDEFINED, FR_STARTUP_COLDSTART_COLLISION_RESOLUTION, FR_STARTUP_COLDSTART_LISTEN, FR_STARTUP_INTEGRATION_CONSISTENCY_CHECK, FR_STARTUP_INTEGRATION_LISTEN, FR_STARTUP_UNDEFINED, FR_STARTUP_INITIALIZE_SCHEDULE, FR_STARTUP_UNDEFINED, FR_STARTUP_UNDEFINED, FR_STARTUP_COLDSTART_CONSISTENCY_CHECK, FR_STARTUP_UNDEFINED, FR_STARTUP_UNDEFINED, FR_STARTUP_INTEGRATION_COLDSTART_CHECK, FR_STARTUP_COLDSTART_GAP, FR_STARTUP_COLDSTART_JOIN }; pocStatus.StartupState = StartupList[hwPtr->PSR0.B.STARTUPSTATE]; const Fr_WakeupStatusType WakeupList[] = { FR_WAKEUP_UNDEFINED, FR_WAKEUP_RECEIVED_HEADER, FR_WAKEUP_RECEIVED_WUP, FR_WAKEUP_COLLISION_HEADER, FR_WAKEUP_COLLISION_WUP, FR_WAKEUP_COLLISION_UNKNOWN, FR_WAKEUP_TRANSMITTED, FR_WAKEUP_UNDEFINED }; pocStatus.WakeupStatus = WakeupList[hwPtr->PSR0.B.WAKEUPSTATUS]; //Successful readout, set output values. Fr_POCStatusPtr->CHIHaltRequest = pocStatus.CHIHaltRequest; Fr_POCStatusPtr->ColdstartNoise = pocStatus.ColdstartNoise; Fr_POCStatusPtr->ErrorMode = pocStatus.ErrorMode; Fr_POCStatusPtr->Freeze = pocStatus.Freeze; Fr_POCStatusPtr->SlotMode = pocStatus.SlotMode; Fr_POCStatusPtr->StartupState = pocStatus.StartupState; Fr_POCStatusPtr->State = pocStatus.State; Fr_POCStatusPtr->WakeupStatus = pocStatus.WakeupStatus; return E_OK; } /** * Set data to transmit * @param Fr_Cfg * @param cIdx * @param Fr_LSduPtr * @param Fr_LSduLength * @param Fr_MsgBuffrIdx * @return */ Std_ReturnType Fr_Internal_SetTxData(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, const uint8* Fr_LSduPtr, uint8 Fr_LSduLength, uint16 msgBufIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; volatile MSG_BUFF_CCS_t *mbPtr = &hwPtr->MBCCS[msgBufIdx]; uint8 *payloadPtr; uint16 data; Std_ReturnType rv = E_OK; /* * Write header and payload data. This is heavily inspired by Freescale unified driver as * the RM... is not that good in this area. */ /* Lock MB */ data = mbPtr->MBCCSR.R; data |= (1u<<(15u-6u)); // LCKT = 1 data &= ~(1u<<(15u-5u)); // EVB = 0; mbPtr->MBCCSR.R = data; /* Read and check if we got lock */ if( mbPtr->MBCCSR.B.LCKS ) { /* Clear flags */ mbPtr->MBCCSR.B.MBIF = 1u; /* For Tx Frame Header struct active fields are FID, PLDLEN and HDCRC * ..however these are already written at startup for static messages. */ const Fr_FrIfClusterConfigType *clCfg = &Fr_Cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; const Fr_FrIfCCTriggeringType *trigCfg = &Fr_Cfg->Fr_ConfigPtr->FrTrigConfig[cIdx]; payloadPtr = getPayload(trigCfg,msgBufIdx); uint32 padLength; if( slotIsStatic(clCfg, trigCfg->FrTrigConfPtr[msgBufIdx].FrTrigSlotId ) ) { /* Note! * For static data: * - Seems that additional data should be padded with 0x0000 * "if gPayloadLengthStatic > vTCHI!Length then the vTCHI!Length number of two-byte * payload words shall be copied from vTCHI!Message to vTF!Payload. The * remaining (gPayloadLengthStatic - vTCHI!Length) two-byte payload words in vTF!Payload * shall be set to the padding pattern 0x0000" */ /* Fr_LSduLength should match cluster config */ assert( (Fr_LSduLength>>1u) <= hwPtr->PCR19.B.PAYLOAD_LENGTH_STATIC ); padLength = (hwPtr->PCR19.B.PAYLOAD_LENGTH_STATIC * 2u - Fr_LSduLength); } else { /* Dynamic segment * The function Fr_Internal_UpdateHeaderLength() should already * setup the header (CRC, etc) * */ assert( (Fr_LSduLength>>1u) <= hwPtr->PCR24.B.MAX_PAYLOAD_LENGTH_DYNAMIC ); padLength = 0; // (trigCfg->FrTrigConfPtr[msgBufIdx].FrTrigLSduLength - Fr_LSduLength); } /* Copy data */ memcpy(payloadPtr, Fr_LSduPtr, Fr_LSduLength ); /* pad */ if( padLength != 0u ) { memset(payloadPtr+Fr_LSduLength-padLength,0,padLength); } _debug_tx_("-----> TX\n"); /* Commit */ mbPtr->MBCCSR.B.CMT = 1; /* Unlock */ mbPtr->MBCCSR.B.LCKT = 1u; } else { /* No lock on the buffer */ rv = E_NOT_OK; } return rv; } /** * Check if the index message buffer have received any new data. * @param Fr_Cfg * @param cIdx * @param msgBufferIdx * @return */ Std_ReturnType Fr_Internal_CheckNewData(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint16 msgBufIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; volatile MSG_BUFF_CCS_t *mbPtr = &hwPtr->MBCCS[msgBufIdx]; Std_ReturnType rv = E_NOT_OK; /* * A table called "Receive Message Buffer Update" describes the status * bits to look at. */ if( mbPtr->MBCCSR.B.DUP ) { /* Valid non-null frame */ rv = E_OK; } else { /* May have receviced a NULL frame, but we don't really care * since Autosar SWS_Fr_00236 "The function Fr_ReceiveRxLPdu shall ensure that * FR_RECEIVED is returned only for non-Nullframes". * * IMPROVEMENT: Do we need to ack anywhy here */ } return rv; } /** * Copy data from the message ram * @param Fr_Cfg * @param cIdx * @param msgBufferIdx * @param Fr_LSduLengthPtr * @return * See header file. */ Std_ReturnType Fr_Internal_GetNewData( const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint32 trigIdx, uint16 msgBufIdx, uint8* Fr_LSduPtr, uint8* Fr_LSduLengthPtr) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; const Fr_FrIfCCTriggeringType *trigCfg = &Fr_Cfg->Fr_ConfigPtr->FrTrigConfig[cIdx]; volatile MSG_BUFF_CCS_t *mbPtr = &hwPtr->MBCCS[msgBufIdx]; MB_HEADER_t *hPtr; uint16 newIndex; uint8 *payloadPtr; /* The natural way would be to read the header directly, however from the RM * regarding shadow buffers: * * "This means that the message buffer area in the FlexRay memory area * accessed by the application for reading the received message is different * from the initial setting of the message buffer. Therefore, the application * must not rely on the index information written initially into the Message * Buffer Index Registers (FR_MBIDXRn). Instead, the index of the message * buffer header field must be fetched from the Message Buffer Index * Registers (FR_MBIDXRn)." * * --> Status is held in the HW message boxes, get header and payload from index. */ /* Check that it's updated */ if( (mbPtr->MBCCSR.B.DUP == 1u) && (mbPtr->MBCCSR.B.MBIF == 1u) ) { /* Lock request */ mbPtr->MBCCSR.B.LCKT = 1u; /* Check that we actually locked it * (Contradictions?!: "Received Message Access" state that * receive message buffers must be in state HDis, HDisLck and HLck.. * but on the other hand table "Receive Message Buffer States and Accesses" * states that is should be read in HLckCCRx ) * */ if( mbPtr->MBCCSR.B.LCKS == 1u ) { /*-- Find message header/body --*/ /* Get the message box index first */ newIndex = mbPtr->MBIDXR.B.MBIDX; /* Get header for that index */ hPtr = getHeader(hwPtr,newIndex); *Fr_LSduLengthPtr = (hPtr->FRAME_HEADER.B.PLDLEN<<1u); payloadPtr = getPayload(trigCfg,newIndex); /* Copy SDU */ memcpy(Fr_LSduPtr, payloadPtr,*Fr_LSduLengthPtr ); /* -- Do some sanity checks (check valid frame) -- */ #if defined(CFG_FR_CHECK_BAD_SLOT_STATUS) /* This check is NOT verified */ /* get channel assignments, CHA and CHB */ uint8 chIdx = (((mbPtr->MBCCFR.R & 0x6000u) >> 13u) & 0x3u); /* Assign S_STATUS_t values in order: * CHA CHB * 0 0 Not valid * 0 1 B * 1 0 A * 1 1 Both */ const uint16 slotStatus[4u] = { 0, 0x8000u, 0x0080u, 0x8080u }; // Check valid frame VFB (bit 0) and VFA (bit 8) // In future include to check slot status register if ( (hPtr->SLOT_STATUS.R & slotStatus[chIdx]) != slotStatus[chIdx]) { while(1) {} /* : bad */ } #endif /*Clear Interrupt flag w1c*/ mbPtr->MBCCSR.B.MBIF = 1u; /*Unlock buffer*/ mbPtr->MBCCSR.B.LCKT = 1u; } } /* IMPROVEMENT: lots of checks in the code above. */ return E_OK; } /** * Checks the message buffer status * From Fr_CheckTxLPduStatus * * @param Fr_Cfg * @param cIdx * @param msgBufferIdx * @return */ Std_ReturnType Fr_Internal_GetTxPending(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint32 trigIdx, boolean *txPending) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; volatile MSG_BUFF_CCS_t *mbPtr = &hwPtr->MBCCS[trigIdx]; /* IMPROVEMENT: Use mailbox here instead * */ /* Check if something is commited for transmission */ if(mbPtr->MBCCSR.B.CMT) { *txPending = TRUE; } else { *txPending = FALSE; } return E_OK; } /** * Set the FLXAnFRIBCM.STXRH to 0 for the indexed message buffer. * @param Fr_Cfg * @param cIdx * @param msgBufferIdx * @return */ Std_ReturnType Fr_Internal_CancelTx(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint16 msgBufferIdx) { return E_OK; } /** * Set the wakeup channel * @param Fr_Cfg * @param cIdx * @param Fr_ChnlIdx * @return */ Std_ReturnType Fr_Internal_SetWUPChannel(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, Fr_ChannelType Fr_ChnlIdx) { return E_OK; } /** * Read out the global time from hw register * @param Fr_Cfg * @param cIdx * @param Fr_CyclePtr * @param Fr_MacroTickPtr * @return */ Std_ReturnType Fr_Internal_GetGlobalTime(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8* Fr_CyclePtr, uint16* Fr_MacroTickPtr) { Std_ReturnType rv = E_NOT_OK; struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if( Fr_Internal_IsSynchronous(Fr_Cfg, cIdx) == E_OK ) { *Fr_CyclePtr = hwPtr->CYCTR.R; /* Cycle counter */ *Fr_MacroTickPtr = hwPtr->MTCTR.R; /* Macro counter */ rv = E_OK; } return rv; } /** * Checks error status register if the unit is synchronous or not. * @param Fr_Cfg * @param cIdx * @return */ Std_ReturnType Fr_Internal_IsSynchronous(const Fr_ContainerType *Fr_Cfg, uint8 cIdx) { Fr_POCStateType state = Fr_Internal_GetProtState(Fr_Cfg,cIdx); Std_ReturnType rv = E_NOT_OK; /* From Autosar FR spec: * A FlexRay CC is considered synchronized, to the FlexRay cluster connected to, as * long as the following condition holds true: * ((!vPOC!Freeze) && (vPOC!State == NORMAL_ACTIVE) || (vPOC!State == NORMAL_PASSIVE)) */ if( ((state != FR_POCSTATE_HALT) && ( state == FR_POCSTATE_NORMAL_ACTIVE )) || ( state == FR_POCSTATE_NORMAL_PASSIVE ) ) { rv= E_OK; } return rv; } /** * Absolute timer setup * * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx * @param Fr_Cycle * @param Fr_Offset * @return */ void Fr_Internal_SetupAbsTimer(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx, uint8 Fr_Cycle, uint16 Fr_Offset) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; /* We have 2 timers, set them up: * * The HW have more capabilities (CYCMSK and Repeat) than the API in this case * so set the TI1CYCMSK to exact match (0x3f) */ if( Fr_AbsTimerIdx == 0U) { hwPtr->TICCR.B.T1SP = 1u; /* Stop Timer */ hwPtr->TI1CYSR.B.TI1CYCVAL = Fr_Cycle; hwPtr->TI1CYSR.B.TI1CYCMSK = 0x3FU; hwPtr->T1MTOR.R=Fr_Offset; /*Timer 1 Macrotic Offset*/ hwPtr->TICCR.B.T1REP = 0u; /* Set Repeat */ hwPtr->TICCR.B.T1TR = 1u; /* Start Timer */ } else if( Fr_AbsTimerIdx == 1U) { hwPtr->TICCR.B.T2SP = 1u; /* Stop Timer */ hwPtr->TI2CR0.B.TI2CYCVAL = Fr_Cycle; hwPtr->TI2CR0.B.TI2CYCMSK = 0x3FU; hwPtr->TI2CR1.R = Fr_Offset; /* IMPROVEMENT, some offset not in timer1 ?? */ hwPtr->TICCR.B.T2REP = 0u; /* Set Repeat */ hwPtr->TICCR.B.T2TR = 1u; /* Start Timer */ } else { assert(0); } } /** * Set the timer to halt. * From Fr_CancelAbsoluteTimer * * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx */ void Fr_Internal_DisableAbsTimer(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if( Fr_AbsTimerIdx == 0U) { hwPtr->TICCR.B.T1SP = 1u; /* Stop Timer */ } else if( Fr_AbsTimerIdx == 1U) { hwPtr->TICCR.B.T2SP = 1u; /* Stop Timer */ } else { assert(0); } } /** * Returns the absolute timer status * From Fr_GetAbsoluteTimerIRQStatus * * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx * @return */ boolean Fr_Internal_GetAbsTimerIrqStatus(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx) { boolean rv = FALSE; struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if( Fr_AbsTimerIdx == 0U) { if( hwPtr->PIFR0.B.TI1IF ) { rv = TRUE; } } else if (Fr_AbsTimerIdx == 1U) { if( hwPtr->PIFR0.B.TI2IF ) { rv = TRUE; } } else { assert(0); } return rv; } /** * Clear the interrupt flag for the selected absolute timer * Comes from Fr_AckAbsoluteTimerIRQ * * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx */ void Fr_Internal_ResetAbsTimerIsrFlag(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if (Fr_AbsTimerIdx == 0U) { hwPtr->PIFR0.B.TI1IF = 1u; while (hwPtr->PIFR0.B.TI1IF == 1u) {}; } else if (Fr_AbsTimerIdx == 1U) { hwPtr->PIFR0.B.TI2IF = 1u; while (hwPtr->PIFR0.B.TI2IF == 1u) {}; } else { assert(0); } } /** * Disables the interrupt line to the absolute timer. * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx */ void Fr_Internal_DisableAbsTimerIrq(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if( Fr_AbsTimerIdx == 0U) { hwPtr->PIER0.B.TI1IE = 0u; } else if (Fr_AbsTimerIdx == 1U) { hwPtr->PIER0.B.TI2IE = 0u; } else { assert(0); } } /** * Enables the interrupt line to the absolute timer. * @param Fr_Cfg * @param cIdx * @param Fr_AbsTimerIdx */ void Fr_Internal_EnableAbsTimerIrq(const Fr_ContainerType *Fr_Cfg, uint8 cIdx, uint8 Fr_AbsTimerIdx) { struct FR_tag *hwPtr = Fr_HwReg[cIdx]; if( Fr_AbsTimerIdx == 0U) { hwPtr->PIER0.B.TI1IE = 1u; } else if (Fr_AbsTimerIdx == 1U) { hwPtr->PIER0.B.TI2IE = 1u; } else { assert(0); } /* All FR_PIER0 flags routed through this gate, enable */ hwPtr->GIFER.B.PRIE = 1u; } /** * Used to wrap the call to DEM. * @param eventId * @param eventStatus */ #if defined(USE_DEM) || defined(CFG_FR_DEM_TEST) static inline void Fr_Internal_reportDem(Dem_EventIdType eventId, Dem_EventStatusType eventStatus) { /* @req FR628 */ /* @req FR630 */ if (eventId != DEM_EVENT_ID_NULL) { /* @req FR028 */ Dem_ReportErrorStatus(eventId, eventStatus); } } #endif void Fr_PrintInfo( void ) { uint32 cIdx = 0; const Fr_FrIfClusterConfigType *cCfg = &Fr_Info.cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; const Fr_CtrlConfigParametersType *pPtr = &Fr_Info.cfg->Fr_ConfigPtr->FrCtrlParam[cIdx]; const Fr_FrIfClusterConfigType *clCfg = &Fr_Info.cfg->Fr_ConfigPtr->FrClusterConfig[cIdx]; printf("bitRate: %d\n",111); printf("cycle: %d\n",111); printf("gMacroPerCycle: %d\n", cCfg->FrClusterGMacroPerCycle); printf("pMicroPerCycle: %d\n", pPtr->FrPMicroPerCycle); // printf("gdBit: %d\n", cCfg->FrClusterGdBit); printf("gdCycle: %4d [us] Duration of the cycle \n", (uint32)(cCfg->FrClusterGdCycle * 1000000)); printf("gdMacrotick: %4d [us] Duration of macrotick \n", (uint32)(cCfg->FrClusterGdMacrotick * 1000000)); printf("pdMicrotick: %d (25ns for 10Mbit)...0 in config\n", pPtr->FrPdMicrotick); printf("static Slots: %d (%d)\n",Fr_Info.staticSlots, clCfg->FrClusterGNumberOfStaticSlots ); printf("macrotick/static slot: %d\n",cCfg->FrClusterGdStaticSlot); printf("payload length : %d\n",cCfg->FrClusterGPayloadLengthStatic); printf("dynamic Slots: %d (%d)\n",Fr_Info.dynamicSlots, cCfg->FrClusterGNumberOfMinislots); printf("macrotick/dynamic slot: %d\n",cCfg->FrClusterGdMinislot); printf("\n\n"); printf("pMicroPerMacroNom: %d\n",(pPtr->FrPMicroPerCycle / (cCfg->FrClusterGMacroPerCycle ))); }
2301_81045437/classic-platform
drivers/Fr/Fr_mpc5xxx.c
C
unknown
62,948
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=PPC */ #ifndef FR_MPC5XXX_H_ #define FR_MPC5XXX_H_ #define POC_CMD_ALLOW_COLDSTART 0u #define POC_CMD_ALL_SLOTS 1u #define POC_CMD_CONFIG 2u #define POC_CMD_FREEZE 3u #define POC_CMD_READY 4u #define POC_CMD_CONFIG_COMPLETE 4u #define POC_CMD_RUN 5u #define POC_CMD_DEFAULT_CONFIG 6u #define POC_CMD_HALT 7u #define POC_CMD_WAKEUP 8u #endif /*FR_MPC5XXX_H_*/
2301_81045437/classic-platform
drivers/Fr/Fr_mpc5xxx.h
C
unknown
1,379
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.0.3 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ #ifndef FR_MPC5XXX_H_ #define FR_MPC5XXX_H_ //CHI Command Vector Bit #define CHI_CMD_NOT_ACCEPTED 0x00 #define CHI_CMD_CONFIG 0x01 #define CHI_CMD_READY 0x02 #define CHI_CMD_WAKEUP 0x03 #define CHI_CMD_RUN 0x04 #define CHI_CMD_ALL_SLOTS 0x05 #define CHI_CMD_HALT 0x06 #define CHI_CMD_FREEZE 0x07 #define CHI_CMD_SEND_MTS 0x08 #define CHI_CMD_ALLOW_COLDSTART 0x09 #define CHI_CMD_RESET_STATUS_INDICATORS 0x0A #define CHI_CMD_MONITOR_MODE 0x0B #define CHI_CMD_CLEAR_RAMS 0x0C #define POC_CMD_ALLOW_COLDSTART CHI_CMD_ALLOW_COLDSTART #define POC_CMD_ALL_SLOTS CHI_CMD_ALL_SLOTS #define POC_CMD_CONFIG CHI_CMD_CONFIG #define POC_CMD_FREEZE CHI_CMD_FREEZE #define POC_CMD_READY CHI_CMD_READY //#define POC_CMD_CONFIG_COMPLETE 4u #define POC_CMD_RUN CHI_CMD_RUN //#define POC_CMD_DEFAULT_CONFIG 6u #define POC_CMD_HALT CHI_CMD_HALT #define POC_CMD_WAKEUP CHI_CMD_WAKEUP struct FLXA_reg { uint32 FROC; uint32 pad_0; uint32 FROS; uint32 FRTEST1; uint32 FRTEST2; uint32 pad_1; uint32 FRLCK; uint32 FREIR; uint32 FRSIR; uint32 FREILS; uint32 FRSILS; uint32 FREIES; uint32 FREIER; uint32 FRSIES; uint32 FRSIER; uint32 FRILE; uint32 FRT0C; uint32 FRT1C; uint32 FRSTPW1; uint32 FRSTPW2; uint32 pad_2[11]; uint32 FRSUCC1; uint32 FRSUCC2; uint32 FRSUCC3; uint32 FRNEMC; uint32 FRPRTC1; uint32 FRPRTC2; uint32 FRMHDC; uint32 pad_3; uint32 FRGTUC1; uint32 FRGTUC2; uint32 FRGTUC3; uint32 FRGTUC4; uint32 FRGTUC5; uint32 FRGTUC6; uint32 FRGTUC7; uint32 FRGTUC8; uint32 FRGTUC9; uint32 FRGTUC10; uint32 FRGTUC11; uint32 pad_4[13]; uint32 FRCCSV; uint32 FRCCEV; uint32 pad_5[2]; uint32 FRSCV; uint32 FRMTCCV; uint32 FRRCV; uint32 FROCV; uint32 FRSFS; uint32 FRSWNIT; uint32 FRACS; uint32 pad_6; uint32 FRESID1; uint32 FRESID2; uint32 FRESID3; uint32 FRESID4; uint32 FRESID5; uint32 FRESID6; uint32 FRESID7; uint32 FRESID8; uint32 FRESID9; uint32 FRESID10; uint32 FRESID11; uint32 FRESID12; uint32 FRESID13; uint32 FRESID14; uint32 FRESID15; uint32 pad_7; uint32 FROSID1; uint32 FROSID2; uint32 FROSID3; uint32 FROSID4; uint32 FROSID5; uint32 FROSID6; uint32 FROSID7; uint32 FROSID8; uint32 FROSID9; uint32 FROSID10; uint32 FROSID11; uint32 FROSID12; uint32 FROSID13; uint32 FROSID14; uint32 FROSID15; uint32 pad_8; uint32 FRNMV1; uint32 FRNMV2; uint32 FRNMV3; uint32 pad_9[81]; uint32 FRMRC; uint32 FRFRF; uint32 FRFRFM; uint32 FRFCL; uint32 FRMHDS; uint32 FRLDTS; uint32 FRFSR; uint32 FRMHDF; uint32 FRTXRQ1; uint32 FRTXRQ2; uint32 FRTXRQ3; uint32 FRTXRQ4; uint32 FRNDAT1; uint32 FRNDAT2; uint32 FRNDAT3; uint32 FRNDAT4; uint32 FRMBSC1; uint32 FRMBSC2; uint32 FRMBSC3; uint32 FRMBSC4; uint32 pad_10[44]; uint8 FRWRDS[256]; /* Use the 8-bit access */ uint32 FRWRHS1; uint32 FRWRHS2; uint32 FRWRHS3; uint32 pad_11; uint32 FRIBCM; uint32 FRIBCR; uint32 pad_12[58]; uint8 FRRDDS[256]; /* Use the 8-bit access */ uint32 FRRDHS1; uint32 FRRDHS2; uint32 FRRDHS3; uint32 FRMBS; uint32 FROBCM; uint32 FROBCR; uint32 pad_13[58]; uint32 FRITC; uint32 FROTC; uint32 FRIBA; uint32 FRFBA; uint32 FROBA; uint32 FRIQC; uint32 FRUIR; uint32 FRUOR; uint32 FRITS; uint32 FROTS; uint32 FRAES; uint32 FRAEA; uint32 FRDA0; uint32 FRDA1; uint32 FRDA2; uint32 FRDA3; uint32 pad_14; uint32 FRT2C; }; #endif /*FR_INTERNAL_H_*/
2301_81045437/classic-platform
drivers/Fr/Fr_rh850f1x.h
C
unknown
5,140
#Flexray driver obj-$(USE_FR) += Fr.o obj-$(USE_FR) += Fr_PBcfg.o obj-$(USE_FR)-$(RH850F1H) += Fr_Internal.o obj-$(USE_FR)-$(CFG_PPC) += Fr_mpc5xxx.o inc-$(USE_FR) += $(ROOTDIR)/drivers/Fr vpath-$(USE_FR) += $(ROOTDIR)/drivers/Fr
2301_81045437/classic-platform
drivers/Fr/fr.mod.mk
Makefile
unknown
237
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /** @reqSettings DEFAULT_SPECIFICATION_REVISION=4.1.2 */ /** @tagSettings DEFAULT_ARCHITECTURE=RH850F1H */ /* General Wdg module requirements */ /* @req SWS_Wdg_00086 Preprocessor check of import include files. */ /* @req SWS_Wdg_00031 The Wdg module shall not implement an interface for de-initialization/shutdown. */ /* @req SWS_Wdg_00161 Access to internal watchdog HW. */ /* @req SWS_Wdg_00105 Imported types. */ /* @req SWS_Wdg_00159 Config variant VARIANT-POST-BUILD. */ #include "Wdg.h" #include "Wdg_Internal.h" #ifdef CFG_TMS570 #include "os_trap.h" #endif /* Declared volatile since depending on the requirements supported (see SWS_Wdg_00035 and 52) it might be accessed from an ISR. */ /* @req SWS_Wdg_00152 */ volatile WdgInternalState Wdg_State = WDG_UNINIT; const Wdg_ConfigType* Wdg_ConfigPtr = NULL; /* @req SWS_Wdg_00153 */ volatile uint16 Wdg_TriggerCounter = 0; /* @req SWS_Wdg_00154 */ WdgIf_ModeType Wdg_Mode = WDGIF_OFF_MODE; /* @req SWS_Wdg_00106 */ /* @req SWS_Wdg_00171 */ void Wdg_Init(const Wdg_ConfigType* ConfigPtr) { /* This requirement does not exist anymore in 4.2.1 but keeping it anyway. It was called WDG089 in 4.0. */ /* @req SWS_Wdg_00089 */ VALIDATE((NULL != ConfigPtr), WDG_INIT_SERVICE_ID, WDG_E_PARAM_POINTER); /* @req SWS_Wdg_00090 */ #if (WDG_DEV_ERROR_DETECT == STD_ON) /*lint -save -e9007 Note: Side effects on right hand of logical operator ||. OK because 2nd result is not needed if first fails. */ if ((Wdg_Hw_ValidateTimeout(ConfigPtr->Wdg_ModeConfig->WdgSettingsFast) != E_OK) || (Wdg_Hw_ValidateTimeout(ConfigPtr->Wdg_ModeConfig->WdgSettingsSlow) != E_OK)) { VALIDATE_FAIL(WDG_INIT_SERVICE_ID, WDG_E_PARAM_CONFIG); } /*lint -restore -e9007 */ #endif /* @req SWS_Wdg_00051 */ Wdg_ConfigPtr = ConfigPtr; /* @req SWS_Wdg_00001 */ /* @req SWS_Wdg_00100 */ /* @req SWS_Wdg_00101 */ /* @req SWS_Wdg_00173 */ if (Wdg_Hw_Init(Wdg_ConfigPtr) == E_OK) { /* @req SWS_Wdg_00019 */ Wdg_State = WDG_IDLE; } } /* @req SWS_Wdg_00107 */ Std_ReturnType Wdg_SetMode(WdgIf_ModeType Mode) { Std_ReturnType ret; #if (WDG_DEV_ERROR_DETECT == STD_ON) /* @req SWS_Wdg_00017 */ if (WDG_IDLE != Wdg_State) { (void) Det_ReportError(WDG_MODULE_ID, 0, WDG_SET_MODE_SERVICE_ID, WDG_E_DRIVER_STATE); return E_NOT_OK; } /* @req SWS_Wdg_00091 */ if ((WDGIF_OFF_MODE != Mode) && (WDGIF_FAST_MODE != Mode) && (WDGIF_SLOW_MODE != Mode)) { (void) Det_ReportError(WDG_MODULE_ID, 0, WDG_SET_MODE_SERVICE_ID, WDG_E_PARAM_MODE); return E_NOT_OK; } /* @req SWS_Wdg_00018 */ Wdg_State = WDG_BUSY; #endif /* WDG_DEV_ERROR_DETECT */ /* @req SWS_Wdg_00016 */ /* @req SWS_Wdg_00160 */ /* @req SWS_Wdg_00145 */ /* @req SWS_Wdg_00092 */ ret = Wdg_Hw_SetMode(Mode, Wdg_ConfigPtr, WDG_SET_MODE_SERVICE_ID); #if (WDG_DEV_ERROR_DETECT == STD_ON) /* @req SWS_Wdg_00018 */ Wdg_State = WDG_IDLE; #endif /* WDG_DEV_ERROR_DETECT */ /* @req SWS_Wdg_00103 */ return ret; } /* @req SWS_Wdg_00155 */ void Wdg_SetTriggerCondition(uint16 timeout) { /* @req SWS_Wdg_00136 */ /* @req SWS_Wdg_00138 */ /* @req SWS_Wdg_00139 */ /* @req SWS_Wdg_00140 */ /* @req SWS_Wdg_00146 */ #ifdef CFG_TMS570 OS_TRAP_Wdg_Hw_SetTriggerCondition(timeout); #else Wdg_Hw_SetTriggerCondition(timeout); #endif } #if (STD_ON == WDG_VERSION_INFO_API) /* @req SWS_Wdg_00109 */ void Wdg_GetVersionInfo(Std_VersionInfoType* versioninfo) { /* @req SWS_Wdg_00174 */ VALIDATE((NULL != versioninfo), WDG_GET_VERSION_INFO_SERVICE_ID,WDG_E_PARAM_POINTER); versioninfo->vendorID = WDG_VENDOR_ID; versioninfo->moduleID = WDG_MODULE_ID; versioninfo->sw_major_version = WDG_SW_MAJOR_VERSION; versioninfo->sw_minor_version = WDG_SW_MINOR_VERSION; versioninfo->sw_patch_version = WDG_SW_PATCH_VERSION; } #endif
2301_81045437/classic-platform
drivers/Wdg/Wdg.c
C
unknown
4,846
#DMA obj-$(USE_DMA) += Dma.o obj-$(USE_DMA) += Dma_Cfg.o inc-$(USE_DMA) += $(ROOTDIR)/$(ARCH_DRIVER_PATH-y)/drivers
2301_81045437/classic-platform
drivers/dma.mod.mk
Makefile
unknown
120
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /*lint -w2 Reduced static code analysis (only used during test) */ /* * DESCRIPTION * RAM filesystem */ /* ----------------------------[includes]------------------------------------*/ #define DBG #include <stdint.h> #include <errno.h> #include <string.h> #include "fs.h" #include "sys/queue.h" #include "MemMap.h" #include "debug.h" /* ----------------------------[private define]------------------------------*/ #define CHUNK_SIZE 1000 /* ----------------------------[private macro]-------------------------------*/ #ifndef MAX #define MAX(_x,_y) (((_x) > (_y)) ? (_x) : (_y)) #endif #ifndef ENOSPC #define ENOSPC 28 #endif /* ----------------------------[private typedef]-----------------------------*/ /* ----------------------------[private function prototypes]-----------------*/ /* ----------------------------[private variables]---------------------------*/ /* ----------------------------[private functions]---------------------------*/ /* ----------------------------[public functions]----------------------------*/ /** * * @param dev - File system device * @param f - File * @param pathname The filename * @return */ static int ramfs_open(FSDriverType *dev, FILE *f, const char *pathname) { return 0; } static int ramfs_close(FSDriverType *dev, FILE *f) { /*lint -e586 MISRA:CONFIGURATION:argument check:[MISRA 2012 Rule 21.6, required] */ dbg("ramfs_close no=%d\n",f->fileNo,f->filepath); /* WINIDEA_BP */ return 0; } static int ramfs_read(FSDriverType *dev, FILE *f, void *buf, size_t size) { /* If the starting position is at or after the end-of-file, 0 shall be returned */ if( f->end == 0 ) { return 0; } dbg("ramfs_read no=%d,buf=%p,size=%d (%s)\n",f->fileNo,f->data,size,f->filepath); memcpy(buf,f->data + f->pos,size); return size; } static int ramfs_write(FSDriverType *dev, FILE *f, const void *buf, size_t nbyte) { int totSize; if ( (f->pos + nbyte) > f->asize ) { totSize = MAX(CHUNK_SIZE,nbyte) + f->pos; dbg("ramfs_write no=%d,buf=%p,size=%d (%s)\n",f->fileNo,f->data,nbyte,f->filepath); f->data = realloc(f->data,totSize); f->asize = totSize; if( f->data == NULL ) { /* Can't allocate more */ dbg(" Fail: ENOSPC\n"); return -ENOSPC; } } memcpy((f->data + f->pos),buf,nbyte); return nbyte; } static int ramfs_lseek(FSDriverType *dev, FILE *f, int pos) { /* All things done in upper layer */ return 0; } FSDriverType FS_RamDevice = { .device.type = DEVICE_TYPE_FS, .name = "ram", .open = ramfs_open, .close = ramfs_close, .read = ramfs_read, .write = ramfs_write, .lseek = ramfs_lseek, };
2301_81045437/classic-platform
drivers/fs_ram.c
C
unknown
3,620
#ICU obj-$(USE_ICU) += Icu_Lcfg.o obj-$(USE_ICU) += Icu_PBcfg.o obj-$(USE_ICU)-$(CFG_MPC5645S) += Icu_mpc5xxx.o obj-$(USE_ICU)-$(CFG_MPC5746C) += Icu_mpc5xxx.o obj-$(USE_ICU)-$(CFG_MPC5646B) += Icu_mpc5xxx.o obj-$(USE_ICU)-$(CFG_MPC560X) += Icu_mpc5xxx.o obj-$(USE_ICU)-$(CFG_ZYNQ) += Icu_zynq.o obj-$(USE_ICU)-$(CFG_MPC5748G) += Icu_mpc5xxx.o vpath-$(USE_ICU)+= $(ROOTDIR)/mcal/Icu/src inc-$(USE_ICU) += $(ROOTDIR)/mcal/Icu/inc
2301_81045437/classic-platform
drivers/icu.mod.mk
Makefile
unknown
444
#irq
2301_81045437/classic-platform
drivers/irq.mod.mk
Makefile
unknown
4
#kernel # CPU specific ifeq ($(CFG_PPC),y) obj-$(USE_KERNEL) += mpc5xxx_handlers.o obj-$(USE_KERNEL) += mpc5xxx_handlers_asm.o ifeq ($(filter os_mpu_mpc5516.o os_mpu_mpc5643l.o os_mpu_spc56xl70.o os_mpu_mpc5744p.o os_mpu_mpc560x.o,$(obj-y)),) obj-$(USE_KERNEL)-$(CFG_MPC5516) += os_mpu_mpc5516.o obj-$(USE_KERNEL)-$(CFG_MPC5643L) += os_mpu_mpc5643l.o obj-$(USE_KERNEL)-$(CFG_SPC56XL70) += os_mpu_spc56xl70.o obj-$(USE_KERNEL)-$(CFG_MPC5744P) += os_mpu_mpc5744p.o obj-$(USE_KERNEL)-$(CFG_MPC560X) += os_mpu_mpc560x.o endif ifeq ($(filter mpc5xxx_callout_stubs.o,$(obj-y)),) obj-$(USE_KERNEL) += mpc5xxx_callout_stubs.o endif endif ifeq ($(CFG_ARM_CM3)$(CFG_ARM_CM4),y) obj-$(USE_KERNEL) += arm_cortex_mx_handlers.o ifeq ($(filter arm_cortex_mx_callout_stubs.o,$(obj-y)),) obj-$(USE_KERNEL) += arm_cortex_mx_callout_stubs.o endif endif obj-$(USE_KERNEL)-$(CFG_TMS570) += os_mpu_tms570.o ifeq ($(filter armv7ar_callout_stubs.o,$(obj-y)),) obj-$(USE_KERNEL)-$(CFG_TMS570) += armv7ar_callout_stubs.o obj-$(USE_KERNEL)-$(CFG_TRAVEO) += armv7ar_callout_stubs.o endif vpath-$(CFG_TRAVEO) += $(ROOTDIR)/$(ARCH_KERNEL_PATH-y)/integration obj-$(USE_KERNEL)-$(CFG_AURIX) += tcxxx_trap_asm.o obj-$(USE_KERNEL)-$(CFG_AURIX) += tcxxx_trap.o obj-$(USE_KERNEL)-$(CFG_TC2XX) += os_mpu_tc297.o obj-$(USE_KERNEL)-$(CFG_TC2XX) += tc2xx_trap_handlers.o obj-$(USE_KERNEL)-$(CFG_TC2XX) += tc2xx_callout_stubs.o
2301_81045437/classic-platform
drivers/kernel.mod.mk
Makefile
unknown
1,436
# Lin obj-$(USE_LIN) += Lin_PBcfg.o obj-$(USE_LIN) += Lin_Lcfg.o obj-$(USE_LIN)-$(CFG_MPC560X) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5744P) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5746C) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5748G) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5777M) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5643L) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5646B) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_SPC56XL70) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5645S) += LinFlex_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC560X) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5744P) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5746C) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5748G) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5777M) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5643L) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_SPC56XL70) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5645S) += LinFlex_Common.o obj-$(USE_LIN)-$(CFG_MPC5516) += Lin_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5567) += Lin_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC563XM) += Lin_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5644A) += Lin_mpc5xxx.o obj-$(USE_LIN)-$(CFG_MPC5668) += Lin_mpc5xxx.o obj-$(USE_LIN)-$(CFG_ZYNQ) += Lin_zynq.o obj-$(USE_LIN)-$(CFG_JAC6) += Lin_jacinto.o obj-$(USE_LIN)-$(CFG_TMS570) += Lin.o obj-$(USE_LIN)-$(CFG_TMS570) += Lin_Hw_tms570.o obj-$(USE_LIN)-$(CFG_TMS570) += Lin_Irq.o vpath-$(USE_LIN)+= $(ROOTDIR)/mcal/Lin/src inc-$(USE_LIN) += $(ROOTDIR)/mcal/Lin/inc inc-$(USE_LIN) += $(ROOTDIR)/mcal/Lin/src #Jacinto6 reqiures timer for hwbug #obj-$(USE_LIN)-$(CFG_JAC6) += Timer.o
2301_81045437/classic-platform
drivers/lin.mod.mk
Makefile
unknown
1,631
# Ocu obj-$(USE_OCU) += Ocu_mpc5xxx.o obj-$(USE_OCU) += Ocu_PBcfg.o obj-$(USE_OCU) += Ocu_Irq.o vpath-$(USE_OCU)+= $(ROOTDIR)/mcal/Ocu/src inc-$(USE_OCU) += $(ROOTDIR)/mcal/Ocu/inc
2301_81045437/classic-platform
drivers/ocu.mod.mk
Makefile
unknown
191
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* ----------------------------[information]----------------------------------*/ /* * * Description: * Implements terminal for isystems winidea debugger * Assumes JTAG access port is in non-cached area. */ /* ----------------------------[includes]------------------------------------*/ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "Std_Types.h" #include "MemMap.h" #include "device_serial.h" #include "sys/queue.h" #error "Status of this TTY: We have not been able to get this implementation to work in Code Composer 6.0" /* ----------------------------[private define]------------------------------*/ #define _DTOPEN (0xF0) #define _DTCLOSE (0xF1) #define _DTREAD (0xF2) #define _DTWRITE (0xF3) #define _DTLSEEK (0xF4) #define _DTUNLINK (0xF5) #define _DTGETENV (0xF6) #define _DTRENAME (0xF7) #define _DTGETTIME (0xF8) #define _DTGETCLK (0xF9) #define _DTSYNC (0xFF) #define LOADSHORT(x,y,z) { x[(z)] = (unsigned short) (y); \ x[(z)+1] = (unsigned short) (y) >> 8; } #define UNLOADSHORT(x,z) ((short) ( (short) x[(z)] + \ ((short) x[(z)+1] << 8))) #define PACKCHAR(val, base, byte) ( (base)[(byte)] = (val) ) #define UNPACKCHAR(base, byte) ( (base)[byte] ) #define CC_BUFSIZ 512 #define CC_BUFFER_SIZE ((CC_BUFSIZ)+32) /* ----------------------------[private macro]-------------------------------*/ /* ----------------------------[private typedef]-----------------------------*/ /* ----------------------------[private function prototypes]-----------------*/ /* ----------------------------[private variables]---------------------------*/ static unsigned char parmbuf[8]; volatile unsigned int _CIOBUF_[CC_BUFFER_SIZE] __attribute__ ((section (".cio"))); static unsigned char CIOTMPBUF[CC_BUFSIZ]; static uint16 cio_tmp_buf_index = 0; /* ----------------------------[private functions]---------------------------*/ /***************************************************************************/ /* */ /* WRITEMSG() - Sends the passed data and parameters on to the host. */ /* */ /***************************************************************************/ void writemsg(unsigned char command, register const unsigned char *parm, register const char *data, unsigned int length) { volatile unsigned char *p = (volatile unsigned char *)(_CIOBUF_+1); unsigned int i; /***********************************************************************/ /* THE LENGTH IS WRITTEN AS A TARGET INT */ /***********************************************************************/ _CIOBUF_[0] = length; /***********************************************************************/ /* THE COMMAND IS WRITTEN AS A TARGET BYTE */ /***********************************************************************/ *p++ = command; /***********************************************************************/ /* PACK THE PARAMETERS AND DATA SO THE HOST READS IT AS BYTE STREAM */ /***********************************************************************/ for (i = 0; i < 8; i++) PACKCHAR(*parm++, p, i); for (i = 0; i < length; i++) PACKCHAR(*data++, p, i+8); /***********************************************************************/ /* THE BREAKPOINT THAT SIGNALS THE HOST TO DO DATA TRANSFER */ /***********************************************************************/ __asm(" .global C$$IO$$"); __asm("C$$IO$$: nop"); } /***************************************************************************/ /* */ /* READMSG() - Reads the data and parameters passed from the host. */ /* */ /***************************************************************************/ void readmsg(register unsigned char *parm, register char *data) { volatile unsigned char *p = (volatile unsigned char *)(_CIOBUF_+1); unsigned int i; unsigned int length; /***********************************************************************/ /* THE LENGTH IS READ AS A TARGET INT */ /***********************************************************************/ length = _CIOBUF_[0]; /***********************************************************************/ /* UNPACK THE PARAMETERS AND DATA */ /***********************************************************************/ for (i = 0; i < 8; i++) *parm++ = UNPACKCHAR(p, i); if (data != NULL) for (i = 0; i < length; i++) *data++ = UNPACKCHAR(p, i+8); } /****************************************************************************/ /* HOSTWRITE() - Pass the write command and its arguments to the host. */ /****************************************************************************/ int HOSTwrite(int dev_fd, const char *buf, unsigned count) { int result; // WARNING. Can only handle count == 1! if (count != 1) _exit(1); if (count > CC_BUFSIZ) count = CC_BUFSIZ; if (cio_tmp_buf_index < CC_BUFSIZ) { CIOTMPBUF[cio_tmp_buf_index++] = *buf; if (*buf != 0xA) { // Only flush if newline return 0; } } LOADSHORT(parmbuf,dev_fd,0); LOADSHORT(parmbuf,cio_tmp_buf_index,2); writemsg(_DTWRITE,parmbuf,(char *)CIOTMPBUF,cio_tmp_buf_index); readmsg(parmbuf,NULL); result = UNLOADSHORT(parmbuf,0); cio_tmp_buf_index = 0; return result; } /* ----------------------------[public functions]----------------------------*/ static int CodeComposer_Read( uint8_t *buffer, size_t nbytes ) { return 0; } static int CodeComposer_Open( const char *path, int oflag, int mode ) { return 0; } static int CodeComposer_Write( uint8_t *buffer, size_t nbytes) { HOSTwrite(0, buffer, nbytes); return (nbytes); } DeviceSerialType CodeComposer_Device = { .name = "serial_code_composer", // .init = T32_Init, .read = CodeComposer_Read, .write = CodeComposer_Write, .open = CodeComposer_Open, };
2301_81045437/classic-platform
drivers/serial_dbg_code_composer.c
C
unknown
7,363
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef SERIAL_DBG_WINIDEA_H_ #define SERIAL_DBG_WINIDEA_H_ extern DeviceSerialType CodeComposer_Device; #endif /* SERIAL_DBG_WINIDEA_H_ */
2301_81045437/classic-platform
drivers/serial_dbg_code_composer.h
C
unknown
909
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ /* * DESCRIPTION * Lauterbach T32 (debugger) terminal */ /* ----------------------------[includes]------------------------------------*/ #include <stdint.h> #include "device_serial.h" #include "sys/queue.h" #include "MemMap.h" /* ----------------------------[private define]------------------------------*/ /* ----------------------------[private macro]-------------------------------*/ /* ----------------------------[private typedef]-----------------------------*/ /* ----------------------------[private function prototypes]-----------------*/ static int t32_Write( uint8_t *data, size_t nbytes); static int t32_Read( uint8_t *data, size_t nbytes ); static int t32_Open( const char *path, int oflag, int mode ); /* ----------------------------[private variables]---------------------------*/ SECTION_RAM_NO_CACHE_BSS static volatile char t32_outport; SECTION_RAM_NO_CACHE_BSS static volatile char t32_inport; DeviceSerialType T32_Device = { .device.type = DEVICE_TYPE_CONSOLE, .name = "serial_t32", // .init = T32_Init, .read = t32_Read, .write = t32_Write, .open = t32_Open, }; /* ----------------------------[private functions]---------------------------*/ void t32_writebyte(char c) { /* T32 can hang here for several reasons; * - term.view e:address.offset(v.address(t32_outport)) e:0 */ while (t32_outport != 0 ) ; /* wait until port is free */ t32_outport = c; /* send character */ } /* ----------------------------[public functions]----------------------------*/ void T32_Init( void ) { /* Nothing to do */ } /** * Write data to the T32 terminal * * @param fd File number * @param _buf * @param nbytes * @return */ static int t32_Write( uint8_t *data, size_t nbytes) { for (int i = 0; i < nbytes; i++) { if (*(data + i) == '\n') { t32_writebyte ('\r'); } t32_writebyte (*(data + i)); } return nbytes; } /** * Read characters from terminal * * @param data Where to save the data to. * @param nbytes The maximum bytes to read * @return The number of bytes read. */ static int t32_Read( uint8_t *data, size_t nbytes ) { size_t b = nbytes; while (nbytes > 0) { while (t32_inport== 0) {}; /* wait for ready */ *data = t32_inport; t32_inport = 0; data++; nbytes--; } return b; } static int t32_Open( const char *path, int oflag, int mode ) { return 0; }
2301_81045437/classic-platform
drivers/serial_dbg_t32.c
C
unknown
3,308
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef SERIAL_DBG_T32_H_ #define SERIAL_DBG_T32_H_ extern DeviceSerialType T32_Device; #endif /* SERIAL_DBG_T32_H_ */
2301_81045437/classic-platform
drivers/serial_dbg_t32.h
C
unknown
888