libwismart.h 77.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477

/**
 * \file libwismart.h
 * WiSmart library header file.
 * \author
 * eConais RnD Group
 */

/*
 * This software is copyrighted by and is the sole property of eConais.
 * All rights, title, ownership, or other interests in the software remain
 * the property of eConais. This software may only be used in accordance
 * with the corresponding license agreement.  Any unauthorized use,
 * duplication, transmission, distribution, or disclosure of this software
 * is expressly forbidden.
 *
 * This copyright notice may not be removed or modified without prior written
 * consent of eConais.
 *
 * eConais reserves the right to modify this software without
 * notice.
 *
 * eConais
 * Patras Science Park                           support@econais.com
 * 26504 Platani, Patras                         http://www.econais.com
 * GREECE

 *
 * This file is part of WiSmart SDK
 *
 * Author: eConais RnD Group
 *
 */

#ifndef LIBWISMART_H_
#define LIBWISMART_H_

#include "ch.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>     /* chprintf */

/* include file with mcu specific defines */
#include "libwismart_mcu.h"

#ifndef TRUE
#define TRUE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

#ifndef NULL
#define NULL (void *)0
#endif

#ifndef WISMART_SUCCESS
#define WISMART_SUCCESS 1
#endif

#ifndef WISMART_FAILURE
#define WISMART_FAILURE 0
#endif

/* generic print function */
void print(const char *fmt, ...);
#define printf print
#ifndef PRINT
#define PRINT print
#endif

/** \addtogroup WSL_SYSTEM
*
* @{
*/

typedef struct {
    void *          port;              /* type GPIO_TypeDef* */
    uint32_t        ahb;
    uint16_t        pin;
    uint8_t         source;
    uint32_t        remap;
}   wismart_hwif_port_t;

typedef struct {
    /* external interrupt */
    wismart_hwif_port_t gpio_ext_int;

    uint8_t         exti_port_source;
    uint8_t         exti_pin_source;
    uint32_t        exti_line;
    uint8_t         exti_irq_number;    /* type IRQn_Type */

    /* 1.2v wifi regulator */
    wismart_hwif_port_t gpio_1_2v;

    /* 3.3v wifi regulator */
    wismart_hwif_port_t gpio_3_3v;
} wismart_hwif_wifi_t;

typedef struct {
    uint8_t               enable;
    void                * channel;
    uint8_t               irq;
    uint32_t              it_complete;
} wismart_hwif_dma_t;

typedef struct {
    void *          usart;              /* type USART_TypeDef* */
    uint32_t        baud_rate;
    uint8_t         tx_irq;             /* type IRQn_Type */
    uint32_t        tx_rcc;
    uint8_t         gpio_af;

    /* GPIO Configurations */
    wismart_hwif_port_t gpio_tx;
    wismart_hwif_port_t gpio_rx;

    /* DMA Configurations */
    wismart_hwif_dma_t  dma_tx;
    wismart_hwif_dma_t  dma_rx;

    /* GPIO Configurations */
    wismart_hwif_port_t gpio_rts;

} wismart_hwif_usart_t;

typedef struct {
    uint8_t         isFS; /* enable or disable FS */
    uint8_t         useULPI_PHY;

    /* FS pins- HS pins without PHY */
    uint32_t        fs_ahb;
    wismart_hwif_port_t host_powersw;

    wismart_hwif_port_t sof;
    wismart_hwif_port_t vbus;
    wismart_hwif_port_t id;
    wismart_hwif_port_t dm;
    wismart_hwif_port_t dp;

    /* HS pins with PHY*/
    wismart_hwif_port_t D[8];
    wismart_hwif_port_t hs_clk;
    wismart_hwif_port_t hs_stp;
    wismart_hwif_port_t hs_nxt;
    wismart_hwif_port_t hs_dir;

} wismart_hwif_usb_t;

typedef enum {
#ifdef STM32F1
    /*
        HSE
    */
    WISMART_MCU_FREQ_32_HSE = 1,
    WISMART_MCU_FREQ_48_HSE = 3,
    WISMART_MCU_FREQ_64_HSE = 5,
    WISMART_MCU_FREQ_72_HSE = 7,

    /*
        HSI
    */
    WISMART_MCU_FREQ_36_HSI = 0,
    WISMART_MCU_FREQ_48_HSI = 2,
    WISMART_MCU_FREQ_64_HSI = 4,
#endif

#ifdef STM32F4
/* TODO: Add the frequency that F4 support */
#endif
} wismart_hwif_mcu_freq_t;

typedef struct {
    wismart_hwif_mcu_freq_t    freq;
    uint8_t                    enableWkupPin;
} wismart_hwif_mcu_t;

typedef struct {
    wismart_hwif_mcu_t          mcu;
    wismart_hwif_wifi_t         wifi;
    wismart_hwif_usart_t        debug;
    wismart_hwif_usb_t          usb;
} wismart_hwif_t;

typedef enum {
    WISMART_ENCRYPTION_OPEN,
    WISMART_ENCRYPTION_WEP,
    WISMART_ENCRYPTION_WPAWPA2
} wismart_bss_encryption_t;

typedef struct {
    uint8_t               ssid[32];
    uint8_t               ssid_len;
    uint8_t               mac_address[6];
    int32_t               rssi;
    int32_t               snr;
    uint8_t               channel;
    uint8_t               encryption; /* wismart_bss_encryption_t */
    uint8_t               bssType;
} wismart_scan_result_t;

typedef struct {
    uint8_t               min_channel_time;
    uint8_t               max_channel_time;
    char                  ssid[33];
    uint16_t              channels;
} wismart_scan_parms_t;


enum {
    WISMART_PERIPHERAL_DMA2, /* DMA2 is used by SDIO peripheral. SDIO must be the only owner of DMA2 or else TX underruns/RX overruns will occur */
};

/** @} */


#define RAM_CCM_SECTION __attribute__ ((section(".ccm")))
enum {
    WISMART_WIFI_DISCONNECTED,
    WISMART_WIFI_CONNECTED,
    WISMART_WRONG_PASSPHRASE,
    WISMART_WIFI_CONN_TIMEOUT,
    WISMART_WIFI_CONN_FAILED
};

enum {
    WISMART_DHCP_SUCCESS, 
    WISMART_DHCP_FAILED
};

typedef enum {
    WISMART_MODE_SOFTAP, 
    WISMART_MODE_CLIENT,
    WISMART_MODE_ADHOC
} wismart_mode_e;


/*
    Below are the return status codes of libwismart_IsConnected():

    WISMART_NOT_CONNECTED: WiFi not connected yet
    WISMART_ASSOCIATED: WiFi connected, no IP connectivity yet
    WISMART_CONNECT: WiFi connected, IP connection completed
 */
enum {
    WISMART_NOT_CONNECTED, 
    WISMART_ASSOCIATED, 
    WISMART_CONNECTED
};

enum
{
    LIBWISMART_DHCP_START=0,
    LIBWISMART_DHCP_WAIT_ADDRESS,
    LIBWISMART_DHCP_ADDRESS_ASSIGNED,
    LIBWISMART_DHCP_TIMEOUT
};
/** @} */

/*---------------------------------------------------------------------------*/
/** \defgroup WSL_INIT Initialization
*
* \brief The group of functions to initialize library, Wi-Fi, TPC/IP and shutdown the Wi-Fi
* @{
*/

/**
 * \fn const char* libwismart_GetVersion(void);
 * \brief Get the version of libwismart
 *
 * This function can be used to get the version of libwismart
 *
 * @return version the libwismart version string, e.g "1.0.0"
 *
*/
const char* libwismart_GetVersion(void);


/*---------------------------------------------------------------------------*/
/** \brief Get the Default HW interface of the wismart.
 *
 * This function return the default HW interface that we can use on init 
 * function. We can use this function to get the default hwif and then modify 
 * it for our platform.
 *
 *
*/
wismart_hwif_t libwismart_GetDefaultHWIF(void);

/*---------------------------------------------------------------------------*/
/** \brief Initialize the library.
 *
 * This function will take care the device initialization
 * This includes initialization for MCU, Sensors, I/O and Wi-FI.
 * This is the first function to call before anything else,
 * otherwise the device will not function properly.
 *
 * @param user_hw The HW stuct for all internal modules.
 *
*/
int libwismart_Init(wismart_hwif_t user_hw);

/*---------------------------------------------------------------------------*/
/** \brief Init WiFi Module
 *
 * This function initialize WiFi module and prepares the hardware to be ready
 * for connection.
 *
 */
int libwismart_WiFiInit(void);

/*---------------------------------------------------------------------------*/
/** \brief Set WiFi MAC Address
 *
 * This function set the WiFi mac address.
 * This function must be called before libwismart_WiFiInit to be valid.
 * To disable the user defined mac address you must set the mac to ff:ff:ff:ff:ff:ff.
 * The selected mac is remaining and after rebooting or shutdown.
 *
 */
void libwismart_WiFi_Set_MAC(char *mac);

/*---------------------------------------------------------------------------*/
/** \brief Get WiFi MAC Address
 *
 * This function return the WiFi mac address.
 * The mac address is valid only when the WiFi is on, 
 * otherwise is return 00:00:00:00:00:00.
 *
 */
void libwismart_WiFi_Get_MAC(char *mac);


/*---------------------------------------------------------------------------*/
/** \brief Shutdown WiFi Module
 *
 * This function closes the WiFi module. It can be used to limit the power
 * consumption. To re-enable the WiFi, run libwismart_WiFiInit()
 *
 */
int libwismart_WiFiShutdown(void);

/*---------------------------------------------------------------------------*/
/** \brief Get WiFi MAC Address
 *
 * This function returns the wifi mode of operation.
 * \retval WISMART_MODE_CLIENT
 * \retval WISMART_MODE_SOFTAP
 * \retval WISMART_MODE_ADHOC
 */
uint8_t libwismart_GetWiFiMode(void);
/** @} */

/*---------------------------------------------------------------------------*/
/** \defgroup WSL_SYSTEM System management
*
* \brief Set of library functions to manage system resources, reboot the system,
*  handle IRQs and I/O ports like USB
* @{
*/

/**
 * A timer.
 *
 * This structure is used for declaring a timer. The timer must be set
 * with libwismart_TimerSet() before it can be used.
 *
 * \hideinitializer
 */
typedef unsigned long wismart_time_t;
struct wismart_timer {
    VirtualTimer    vt;
    vtfunc_t        func;
    void           *params;
    wismart_time_t  interval;
};

typedef struct wismart_timer wismart_timer_t;

/*---------------------------------------------------------------------------*/
/**
 * Set a timer.
 *
 * This function is used to set a timer for a time sometime in the
 * future.
 *
 * \param t A pointer to the timer
 * \param interval The interval before the timer expires
 * \param func callback function that is called when the timer expires
 * \param params extra data to pass in func
 */
void libwismart_TimerSet(wismart_timer_t *t, wismart_time_t interval, vtfunc_t func, void * params);

/*---------------------------------------------------------------------------*/
/**
 * Set a timer from within an IRQ handler.
 *
 * This function is used to set a timer for a time sometime in the
 * future. It should be used only when a timer must be set from within
 * an IRQ handler.
 *
 * \param t A pointer to the timer
 * \param interval The interval before the timer expires
 * \param func callback function that is called when the timer expires
 * \param params extra data to pass in func
 */
void libwismart_TimerSetI(wismart_timer_t *t, wismart_time_t interval, vtfunc_t func, void * params);

/*---------------------------------------------------------------------------*/
/**
 * Reset the timer with the same interval.
 *
 * This function resets the timer with the same interval that was
 * given to the libwismart_TimerSet() function. The start point of the interval
 * is the exact time that the timer last expired.
 *
 * \param t A pointer to the timer.
 *
 */
void libwismart_TimerReset(wismart_timer_t *t);

/*---------------------------------------------------------------------------*/
/**
 * Stop a timer.
 *
 * This function stops a running timer
 *
 * \param t A pointer to the timer
 *
 */
void libwismart_TimerStop(wismart_timer_t *t);

/** \brief Reset the device.
 *
 * This function resets the device
 *
 */
void libwismart_Reboot(void);

/*---------------------------------------------------------------------------*/




/** \brief Get the number of free pbufs from pool.
 *
 * This function returns the number of free pbufs that you
 * can allocate from pool.
 *
 */
uint8_t libwismart_GetMemFree_PBufPool(void);

/* Memory statistics. All values are in bytes. */
typedef struct{
    size_t free;          /* The size of Core and Chibios free memory */
    size_t free_core;     /* The size of free memery thet the chibios never use and it can be used from chibios */
    size_t free_chibios;  /* The sum of all free fragments that the chibios have. Note this is not a continue buffer unless we have only one fragment.  */ 
    size_t max_free_frag; /* The size of the bigger fragment */
    size_t min_free_frag; /* The size of the smaller fragment */
    size_t num_free_frag; /* Number of free memory fragments that the chibios have. The fragments are not continue memory chank. */ 
} wismart_mem_stat_ram_t;

/** \brief Get statistics about the main heap/ram.
 *
 * This function returns the statistics about the main heap/ram.
 *
 */
wismart_mem_stat_ram_t libwismart_GetMemFree_Ram(void);



/** @} */

/*---------------------------------------------------------------------------*/
/** \defgroup WSL_WIFI Wi-Fi related functions
*
* \brief Library functions related to Wi-Fi client mode
* @{
*/
/** \brief callback used to inform applications about the connection result
 *  with a Wi-Fi Network.
 *
 *  @param result returns WISMART_WIFI_CONNECTED or WISMART_WIFI_FAILED
 */
typedef void (*wificonnect_callback)(int result);


typedef void (*wifiscanresult_callback)(wismart_scan_result_t* scan_result);


/*---------------------------------------------------------------------------*/
/** \addtogroup WSL_WIFI
*
* @{
*/
/**\brief Create a new 802.11 WiFi Ad-Hoc network
 *
 * This function will create a new 802.11 WiFi Ad-Hoc (IBSS) network.
 * Other clients will be able to connect to this Ad-Hoc network. After the
 * WiFi connection has been established, usually both ends need to have a
 * static IP address. In WiSmart, you can use the API function
 * libwismart_SetStaticIP(), documented later in this file.
 *
 * Using Ad-Hoc mode you can also configure the device by accessing the
 * builtin web server.
 *
 * @param ibss_ssid the name of the Ad-Hoc (IBSS) network.
 * @param ibss_ssid the preferred channel (1-11).
 */
void libwismart_WiFiCreateAdHoc(char *ibss_ssid,
                                int channel,
                                wificonnect_callback wificb);
/** @} */


/*---------------------------------------------------------------------------*/
/** \brief Connect to a WiFi network.
 *
 * This function will initiate a connection with a WiFi Network.
 * It can be used for a new connection or for switching to another
 * WiFi network.
 *
 * @param ssid (unsigned char *) The SSID (network name) of the Access Point.
 * @param key (unsigned char *) PSK(raw key) or passphrase. Pass NULL for
 * open networks.
 * @param cb callback used to inform applications about the connection result.
 * Pass NULL if you don't care about the connection result.
 *
 */
int  libwismart_WiFiConnect(char* ssid,
                            char* key,
                            wificonnect_callback cb);

/*---------------------------------------------------------------------------*/
/** \brief Connect to a WiFi network with a specific MAC Address.
 *
 * This function will initiate a connection with a WiFi Network.
 * It can be used for a new connection or for switching to another
 * WiFi network. It is different from libwismart_WiFiConnect in that it tries
 * to connect to specific BSSID
 *
 * @param ssid (unsigned char *) The SSID (network name) of the Access Point.
 * @param bssid (unsigned char *) The BSSID (mac address) of the Access Point.
 * @param key (unsigned char *) PSK(raw key) or passphrase. Pass NULL for
 * open networks.
 * @param cb callback used to inform applications about the connection result.
 * Pass NULL if you don't care about the connection result.
 *
 */
int libwismart_WiFiConnectBSSID(char* ssid,
                                char* bssid,
                                char* key,
                                wificonnect_callback wificb);

/*---------------------------------------------------------------------------*/
/** \brief Connect to a WPS network with a specific SSID.
 *
 * This function will initiate a connection with a WiFi Network with
 * Wi-Fi Protected Setup (WPS) support
 *
 * @param ssid (unsigned char *) The SSID (network name) of the Access Point.
 * @param pin (unsigned char *) The PIN number in case WPS PIN Method has
 * been selected.
 * @param cb callback used to inform applications about the connection result.
 * Pass NULL if you don't care about the connection result.
 *
 */
int libwismart_WiFiConnectWPS(char* ssid,
                              char* pin,
                              wificonnect_callback wificb);


/*---------------------------------------------------------------------------*/
/* WPA ENTERPRISE SECTION                                                    */
/*---------------------------------------------------------------------------*/

/* we need to obtain certificates from somewhere, for now, assume this
   is a filename */
typedef const char *certificate_t;

/* the same goes for the private key.. */
typedef const char *private_key_t;

/* EAP-TLS Parameters */
struct tls_data {
    const char *identity;              /* the identity to use */
    certificate_t client_cert;         /* the client certificate to use */
    private_key_t private_key;         /* private key to use */
    const char *private_key_password;  /* ...and its password */
    certificate_t ca_cert;             /* root CA certificate */
};

/* EAP-TTLS Parameters */
struct ttls_data {
    const char *identity;        /* the identity to use */
    const char *password;        /* password to use */
    certificate_t ca_cert;       /* root CA certificate */
};

/* EAP-PEAP Parameters */ 
struct peap_data {
    const char *identity;        /* the identity to use */
    const char *password;        /* password to use */
    certificate_t ca_cert;       /* root CA certificate */
};

/* EAP Method */
typedef enum {
    WISMART_EAP_METHOD_TTLS = 1,
    WISMART_EAP_METHOD_PEAP,
    WISMART_EAP_METHOD_TLS
} eap_method_t;

/* this struct contains all the parameters needed for WPA/WPA2 Enterprise */ 
struct wpa_param {
    eap_method_t eap_method;  /* this specifies which EAP Peer Method to use */
    union {
        struct tls_data tls;    /* EAP-TLS */
        struct ttls_data ttls;  /* EAP-TTLS */
        struct peap_data peap;  /* EAP-PEAP */
    } u;
};

/*---------------------------------------------------------------------------*/
/** \brief Connect to a WPA/WPA Enterprise network with a specific SSID.
 *
 * This function will initiate a connection with a WPA/WPA2 Enterprise 
 * network (802.1x authentication). Make sure that a radius server has been
 * configured and you have been provided with a username and a password.
 * EAP-TTLS and EAP-PEAP methods are supported.
 *
 * @param ssid (unsigned char *) The SSID (network name) of the Access Point.
 * @param wp (const struct wpa_param *) All the required parameters for 
 * WPA/WPA2 Enterprise authentication.
 * @param cb callback used to inform applications about the connection result.
 */
int libwismart_WiFiConnectEnterprise(char* ssid,
                                     const struct wpa_param *wp,
                                     wificonnect_callback wificb);


/*---------------------------------------------------------------------------*/
/** \brief Disconnect from the WiFi network
 *
 * This function will disconnect the device from the WiFi network that
 * we are connected.
 *
 */
int libwismart_WiFiDisconnect(void);


/*---------------------------------------------------------------------------*/
/** \brief Set a connection timeout.
 *
 * Set the number of scan requests after which the device will send
 * a connection timeout indication.
 */
void libwismart_SetScanRunsForConnTimeout(int scan_runs);

/*---------------------------------------------------------------------------*/
/** \brief Set WEP Key.
 *
 * This function will set the preferred WEP Key and WEP Key Index. It should
 * be called after libwismart_WiFiConnect().
 *
 * @param wepkey (unsigned char *) The selected WEP key.
 * @param keyindex (int) The selected WEP key index (1-4)
 *
 */
int libwismart_WiFiSetWep(char *wepkey, int keyindex);


/*---------------------------------------------------------------------------*/
/*  Packet Filtering Mechanism                                               */
/*---------------------------------------------------------------------------*/
typedef enum{ 
    FILTERS_CMD       =(1<<0), /* data cfm is included in this filter as well*/
    FILTERS_DATA      =(1<<1),
    FILTERS_EAPOL     =(1<<2),
    FILTERS_BROADCAST =(1<<3),
    FILTERS_MULTICAST =(1<<4),
    FILTERS_UDP       =(1<<5),
    FILTERS_TCP       =(1<<6),
    FILTERS_ICMP      =(1<<7),
    FILTERS_IGMP      =(1<<8),
    FILTERS_UNKNOWN_IP=(1<<9),
    FILTERS_NOT_IP    =(1<<11), /* it's not IP or ARP packet */
    FILTERS_ARP       =(1<<12),
}wismart_wifi_filters_t;

/** \brief Check a specific type of packets whether is filtered-out
 *
 * This function will check whether the specific type of packets is filtered-out.
 *
 * @param filter (wismart_wifi_filters_t) The packet type that we want to check if it's filtered-out.
 *
 */
uint8_t libwismart_WiFi_Filter_Get(wismart_wifi_filters_t filter);

/** \brief Remove filter from specific type of packet .
 *
 * This function will remove from filters a specific type of packets
 *
 * @param filter (wismart_wifi_filters_t) The packet type that we don't want to filter-out.
 *
 */
void libwismart_WiFi_Filter_Clean(wismart_wifi_filters_t filter);

/** \brief Filter-out the specific type of packets.
 *
 * This function will filter-out the speific type of packets
 *
 * @param filter (wismart_wifi_filters_t) The packet type to filter-out.
 *
 */
void libwismart_WiFi_Filter_Set(wismart_wifi_filters_t filter);


/*---------------------------------------------------------------------------*/
/* Roaming Mechanism                                                         */
/*---------------------------------------------------------------------------*/
/**
 * \brief Enables Roaming Mechanism
 *
 * This function enables the roaming mechanism. Only if this mechanism is enabled
 * the user will be informed about triggering events.
 *
 */
void libwismart_EnableRoaming(void);

/**
 * \brief Disables Roaming Mechanism
 *
 * This function disables the roaming mechanism. After disabling this mechanism the
 * user is no longer be informed about triggering events.
 *
 */
void libwismart_DisableRoaming(void);

/**
 * \brief Check if Roaming is enabled
 *
 * @param result returns 1 if roaming is enabled or 0 if it's disabled
 */
int libwismart_isRoamingEnabled(void);

/*! Below are the states/zones of the roaming mechanism */
typedef enum {
    ROAM_STATE_NORM,
    ROAM_STATE_ALERT,
    ROAM_STATE_PANIC,
} roam_state_t;

/*! Below are the types of the roaming events */
typedef enum {
    ROAM_TYPE_ALERT  = 0,
    ROAM_TYPE_PANIC = 1,
} roam_type_t;

/*! Below are the ID's of the roaming events */
typedef enum {
    ROAM_ID_RSSI  = 0,
    ROAM_ID_SNR   = 1,
    ROAM_ID_D     = 2,
} roam_id_t;

/*! Below are the ID's of the roaming events */
typedef enum {
    ROAM_TREND_ASCENDING   = 0,
    ROAM_TREND_DESCENDING  = 1,
} roam_trend_t;

/*! Below are the mode of roaming */
typedef enum {
    ROAM_MODE_CONTINUOUS   = 0,
    ROAM_MODE_ONETIME_SHOT = 1,
} roam_mode_t;

/*---------------------------------------------------------------------------*/
/** \brief This function set the BG scan time for specific roaming state.
 *
 * @param state The Roaming state tha we want to set the bg scan time.
 * @param sec   The BG scan time in Seconds.
 * 
 */
void libwismart_Roam_SetBGScanTime(roam_state_t state, uint8_t sec);

/*---------------------------------------------------------------------------*/
/** \brief This function Get the BG scan time for specific roaming state.
 *
 * @param state The Roaming state tha we want to get the bg scan time.
 * 
 */
uint8_t libwismart_Roam_GetBGScanTime(roam_state_t state);
       
/*---------------------------------------------------------------------------*/
/**
 * \brief This function adds a roaming event trigger threshold
 *
 *
 * \param ID Specifies if this is an RSSI, SNR or DS trigger
 * \param Value Actual triggering value
 * \param Type Defines whether when this threshold is reached, a scan or a roaming
 * action will take place
 * \param Type Specifies if a trigger is needed when the value of the specified
 * parameter(rssi, snr, ds) is increased over the specified threshold or decreased
 * under the specified threshold
 * \param Mode Specifies whether this is a continuous or one shot trigger
 */
uint8_t libwismart_AddRoamingEventThreshold(roam_id_t       ID, 
                                            uint32_t        Value, 
                                            roam_type_t     Type, 
                                            roam_trend_t    Trend, 
                                            roam_mode_t     Mode);

/*---------------------------------------------------------------------------*/
/**
 * \brief This function removes a roaming event trigger threshold
 *
 *
 * \param ID Specifies trigger ID that is to be removed
 */
uint8_t libwismart_RemoveRoamingEventThreshold(uint8_t ID);

/*---------------------------------------------------------------------------*/
/** \brief callback used to inform applications about the returned snr value
 *
 *  @param result returns WISMART_WIFI_CONNECTED or WISMART_WIFI_FAILED
 */
typedef void (*snr_callback)(int32_t result);

/*---------------------------------------------------------------------------*/
/** \brief callback used to inform applications about the returned rssi value
 *
 *  @param result returns WISMART_WIFI_CONNECTED or WISMART_WIFI_FAILED
 */
typedef void (*rssi_callback)(int32_t result);


/*---------------------------------------------------------------------------*/
/** \brief Programms the aquisition of current rssi value
 *
 * This function will initiate the procedure of the aquisition of the current
 * rssi value. The actual value will be sent to the calling application to the
 * specified callback function
 *
 * @param rssicb callback used to inform applications about the rssi value.
 *
 */
void libwismart_GetRssi(rssi_callback rssicb);


/** @} */

/*---------------------------------------------------------------------------*/
/** \brief Performs a Scan Request
 *
 * This function performs a scan request
 *
 * @param scan_result_cb The callback that will be invoked when receiving a scan result
 * @param parms Scan parameters
 */
void libwismart_ScanRequest(wifiscanresult_callback scan_result_cb, wismart_scan_parms_t* parms);

/*---------------------------------------------------------------------------*/
/** \brief Enable a BG scaning mechanism.
 *
 * This function enable the BG scan mechanism
 *
 * @param scan_period The period of scanning in seconds.
 */
void libwismart_Scan_Enable_BG(uint8_t scan_period);

/*---------------------------------------------------------------------------*/
/** \addtogroup WSL_SYSTEM
*
* @{
*/
/** \brief Get the Mac Address of WiSmart
 *
 * This function will retrieve the mac address of the device.
 * It's useful for status reporting and for using it as
 * something that uniquely identify this device.
 *
 * @param mac The mac address of WiSmart
 *
 */
void libwismart_GetMac(unsigned char *mac);


/*---------------------------------------------------------------------------*/
/** \brief Get the BSSID of the WiFi Access Point
 *
 * This function will retrieve the BSSID (usually mac address)
 * of the WiFi Access Point that the device is connected.
 *
 * @param bssid The bssid of Access Point
 *
 */
int  libwismart_GetApMac(unsigned char *bssid);
/** @} */


/** \addtogroup WSL_TCP_IP
*
* @{
*/

/*---------------------------------------------------------------------------*/
/** \brief callback used to inform applications about the result
 *  of the DHCP procedure.
 *
 *  @param result returns WISMART_DHCP_SUCCESS or WISMART_DHCP_FAILED
 */
typedef void (*dhcp_result_callback)(int result);

/*---------------------------------------------------------------------------*/
/** \brief Register DHCP callback.
 *
 *
 * @param cb callback used to inform applications about the DHCP result.
 * Pass NULL if you don't care about the DHCP result.
 *
 */
void libwismart_RegisterDhcpCB(dhcp_result_callback cb);

/*---------------------------------------------------------------------------*/
/** \brief Start DHCP Server.
 *
 * This function is used to start the dhcp server, used in SoftAP mode

 * @param ipaddress The server ip address
 * @param netmask   The server netmask
 * @param gateway   The server gateway
 * @param dhcp_pool_size The size of pool of client IP addresses
 *
 */

void libwismart_StartDhcpServer(char* ipaddress,
                                char* netmask,
                                char* gateway,
                                int dhcp_pool_size);


/*---------------------------------------------------------------------------*/

typedef struct
{
    uint8_t addr[4];
} libwismart_ip_addr_t;

/** \brief Enable/Disable DHCP mechanism.
 *
 * This function will Enable/Disable DHCP mechanism.
 *
 * By default the DHCP mechanism is enabled.
 *
 * @param enable To enable the dhcp mechanism or not.
 *
 */
void libwismart_DhcpEnable(uint8_t enable);

/** \brief Set Static IP
 *
 * This function will set a static IP address to WiSmart
 *
 * Currently only setting a static IPv4 address is supported.
 *
 * @param ip_address The selected IP Address, e.g 192.168.1.100
 * @param netmask The selected Netmask, e.g 255.255.255.0
 * @param gateway The IP Address of the Gateway, e.g 192.168.1.1
 *
 */
void libwismart_SetStaticIP(libwismart_ip_addr_t *ip_address, libwismart_ip_addr_t *netmask, libwismart_ip_addr_t* gateway);

/*---------------------------------------------------------------------------*/
/** \brief Get Current IP
 *
 * This function gets the current IP address
 *
 * @param ip_address Struct containing the current IP Address,e.g 192.168.1.100
 * @param netmask Struct containing the current Netmask, e.g 255.255.255.0
 * @param gateway Struct containing the current Gateway, e.g 192.168.1.1
 *
 */
void libwismart_GetCurrentIP(libwismart_ip_addr_t *ip_address, libwismart_ip_addr_t *netmask, libwismart_ip_addr_t *gateway);

/** @} */

/*---------------------------------------------------------------------------*/
/** \addtogroup WSL_WIFI
*
* @{
*/

/** \brief Returns the connection status of the device
 *
 * \return WISMART_NOT_CONNECTED: WiFi not connected yet
 * \return WISMART_ASSOCIATED: WiFi connected, no IP connectivity yet
 * \return WISMART_CONNECT: WiFi connected, IP connection completed
 *
 */
int libwismart_IsConnected(void);
/** @} */

/*---------------------------------------------------------------------------*/
/* Power Save Mechanism                                                      */
/*---------------------------------------------------------------------------*/
/** \defgroup WSL_POWER_MGMT Power Management
*
* @{
*/

/*! Below are the power resources of power mgmt */
typedef enum power_resource{
    POWER_RES_APP       = 0, /*!< Resource for User applications */
    POWER_RES_DATA      = 1, /*!< LwIP Data traffic(Internal library USE)*/
    POWER_RES_CMD       = 2, /*!< RX WiFi CMD (Internal USE)*/
    POWER_RES_DMA       = 3, /*!< Using DMA controller*/
    POWER_RES_SDIO      = 4, /*!< Internal library USE*/
    POWER_RES_WIFI      = 5, /*!< Internal library USE*/
}power_resource_t;

/*---------------------------------------------------------------------------*/
/** \brief Enable power save of the device.
 *
 * This function will enable the Power Save
 * scheme of the device.
 *
*/
void libwismart_PowerSave_Enable(void);


/*---------------------------------------------------------------------------*/
/** \brief Disable the power save of the device.
 *
 * This function will disable the Power Save
 * scheme of the device.
 *
*/
void libwismart_PowerSave_Disable(void);


/*---------------------------------------------------------------------------*/
/** \brief Get the state of power save.
 *
 * This function will return the state of the Power Save.
 *
*/
uint8_t libwismart_PowerSave_isEnable(void);

/*---------------------------------------------------------------------------*/
/** \brief Get the state of the higher power save mode.
 *
 * This function will return the state 
 * of the higher power save mode.
 *
*/
uint8_t libwismart_PowerSave_isHigherProfile(void);


/*---------------------------------------------------------------------------*/
/** \brief Request resource from the chip.
 *
 * This function increases the request resource counter.
 * The one that requests the resource must release it as soon as
 * it finishes the work that has to do. Automatically the system
 * will be go to sleep if no one need the resource.
 *
*/
void libwismart_PowerSave_ReqResource(power_resource_t res);


/*---------------------------------------------------------------------------*/
/** \brief Release resource from the chip.
 *
 * This function decreases the request resource counter.
 *
*/
void libwismart_PowerSave_RelResource(power_resource_t res);

/*---------------------------------------------------------------------------*/
/** \brief Reset a resource.
 *
 * This function reset the resource counter.
 * Automatically the system will be go to sleep if no one need the resource.
 * NOTE: Use this with CAUTION.
*/
void libwismart_PowerSave_ResetResource(power_resource_t res);

/*---------------------------------------------------------------------------*/
/** \brief Request resource from the chip. For IRQ context.
 *
 * This function increases the request resource counter.
 * The one that requests the resource must release it as soon as
 * it finishes the work that has to do. Automatically the system
 * will be go to sleep if no one need the resource.
 *
*/
void libwismart_PowerSave_ReqResourceI(power_resource_t res);


/*---------------------------------------------------------------------------*/
/** \brief Release resource from the chip. For IRQ context.
 *
 * This function decreases the request resource counter.
 *
*/
void libwismart_PowerSave_RelResourceI(power_resource_t res);



/*---------------------------------------------------------------------------*/
/** \brief Reset a resource.
 *
 * This function reset the resource counter.
 * Automatically the system will be go to sleep if no one need the resource.
 * NOTE: Use this with CAUTION.
*/
void libwismart_PowerSave_ResetResourceI(power_resource_t res);

/*---------------------------------------------------------------------------*/
/** \brief Enable or Disable the higher power save mode.
 *
 * This function enables or disables the higher power save profile.
 * When this mode is enabled, the device can wake-up only from external irq or rtc.
 *
 */
void libwismart_PowerSave_HigherProfile(uint8_t enable);


/*---------------------------------------------------------------------------*/
/** \brief Shutdown the MCU.
 *
 * This function shutdowns the mcu and sets rtc for wake-up (reset),timeout 
 * is in secs. When we enable this mode, the device can wake-up(reset) only 
 * from external irq or rtc. If you selected source of wake-up is rtc then,
 * it's not possible to set the wake-up pin as source. To select the wake-up
 * pin as a source set the timeout to TIME_INFINITE.
 *
 */
void libwismart_PowerSave_MCUShutdown(systime_t timeout);

/*---------------------------------------------------------------------------*/
/** \brief Disable the WiFi Power save.
 *
 * This function disable the wifi power save.
 * By default the wifi power save is on.
 * Note: must be called after libwismart_WiFiInit().
 *
 */
void libwismart_WiFi_PSDisable(void);

/*---------------------------------------------------------------------------*/
/** \brief Enable the WiFi Power save.
 *
 * This function Enable the wifi power save.
 * By default the wifi power save is on.
 * Note: must be called after libwismart_WiFiInit().
 *
 */
void libwismart_WiFi_PSEnable(void);
/** @} */

/**
* \defgroup WSL_DEBUG Debugging
*
* \brief Functions and structures used for debugging
*
* @{
*/

typedef void (*debugport_rx_callback)(char);

/*---------------------------------------------------------------------------*/
/** \brief Set Callback function for received characters over debug port
 *
 * This function will initialize the receive path of WiSmart UART interface
 * from the DEBUG port.
 *
 * @param uartrcv_callback This function callback will be called when we
 * receive one character in debug uart.
 *
 */
void  libwismart_UART_InitRecv(debugport_rx_callback cb);


/*---------------------------------------------------------------------------*/
/** \brief Sends a Char to the Default output Port (USART1).
 *
 * This function sends the provided byte to the DEBUG UART port.
 * The function waits until the byte is transfered.
 *
 * @param data Char to be written to DEBUG UART port
 *
 */
void  libwismart_UART_SendChar(unsigned char data);

/*---------------------------------------------------------------------------*/
/** \brief Sends a Char to the Default output Port (USART1) from irq context.
 *
 * This function sends the provided byte to the DEBUG UART port from irq context.
 * The function waits until the byte is transfered.
 *
 * @param data Char to be written to DEBUG UART port
 *
 */
void  libwismart_UART_SendCharI(char data);

/*---------------------------------------------------------------------------*/
/** \brief Sends a Char Buff to the Default output Port (USART1).
 *
 * This function sends the provided bytes to the DEBUG UART port.
 * The function waits until the bytes is transfered.
 *
 * @param data Char to be written to DEBUG UART port
 * @param len Lenength of char to be written to DEBUG UART port
 *
 */
void  libwismart_UART_SendBuff(unsigned char *data, uint16_t len);

/*---------------------------------------------------------------------------*/
/** \brief Recv a Char Buff from the Default output Port (USART1).
 *
 * This function recv the provided bytes from the DEBUG UART port.
 *
 * If we know from before the number of chars that we are going to
 * recv we must use this function because is optimal for power
 * consuption and performance.
 *
 * The function waits until the bytes is received or the user abort the DMA.
 *
 * @param buff      Array with the buffer that we are going to write the received data.
 * @param len       Number of the characters that we are going to recv.
 * @param timeout   The timeout for the DMA receive call. The time is in ms. To disable
 *                  the timeout set it to TIME_INFINITE.
 *
 * @return          The number of the received bytes.
 *
 */
uint16_t  libwismart_UART_RecvBuff(unsigned char *buff, uint16_t len, systime_t timeout);

/*---------------------------------------------------------------------------*/
/** \brief Abort any DMA RX waiting in default output port (USART1).
 *
 * This function abort any DMA RX waiting. The @libwismart_UART_RecvBuff 
 * will be return the number of data that it have be recv until now.
 *
 */
void libwismart_UART_RecvBuff_Abort(void);

/*---------------------------------------------------------------------------*/
/** \brief Abort any DMA RX waiting in default output port (USART1) from IRQ context.
 *
 * This function abort any DMA RX waiting. The @libwismart_UART_RecvBuff 
 * will be return the number of data that it have be recv until now.
 *
 */
void libwismart_UART_RecvBuff_AbortI(void);


/** @} */

/*---------------------------------------------------------------------------*/
/*  Delay Functions                                                          */
/*---------------------------------------------------------------------------*/
/** \addtogroup WSL_SYSTEM
*
* @{
*/
/**  \brief Perform a delay expressed in milliseconds
*   The maximum possible delay is 262.14 ms / cpu_speed in MHz.
*
*   @param delay Milliseconds to delay
*/
void libwismart_Delay_ms(unsigned long delay);

/*---------------------------------------------------------------------------*/
/**
 * \brief Get the time in ms.
 *
 * This function returns the time in ms. The time is measured from the start
 * of the device.
 *
 */
uint32_t libwismart_GetTime(void);

/*---------------------------------------------------------------------------*/
/**
 * \brief This function returns the elpased time in ms. 
 *
 * Calculate the elapsed time between startTimeMs and Now, taking into
 * account possible timer overflow conditions.
 * This function returns the elpased time in ms. 
 *
 * NOTE: startTimeMs must be a time returned from libwismart_GetTime() for this
 *          function to work properly.
 */
uint32_t libwismart_ElapsedTime(uint32_t startTimeMs);

/*---------------------------------------------------------------------------*/
typedef enum{
    TR_ALWAYS      = (~0),
    TR_ALL         = (~0),
    TR_WIFI        = (1 << 0),
    TR_WPA         = (1 << 1),
    TR_WPA_EXTREME = (1 << 2),
    TR_TRANS       = (1 << 3),
    TR_UART        = (1 << 4),
    TR_TIMER       = (1 << 5),
    TR_SOFTAP      = (1 << 6),
    TR_SOFTAP_PS   = (1 << 7),
    TR_PS          = (1 << 8),
    TR_DHCP        = (1 << 9),
    TR_ROAM        = (1 << 10),
    TR_SCAN        = (1 << 11),
} trace_mask_e;

/**
 * \brief Enable debug trace bit
 *
 * This function enables a specific trace bit from trace_mask_e.
 *
 */
void libwismart_SetTraceMask(trace_mask_e bit_field);

/**
 * \brief Clear trace bit
 *
 * This function clears a specific trace bit from trace_mask_e
 *
 */
void libwismart_ClearTraceMask(trace_mask_e bit_field);

/**
 * \brief Get current trace mask
 *
 * This function return the current trace mask.
 *
 */
trace_mask_e libwismart_GetTraceMask(void);

/**
 * \brief eConais implementation of snprintf
 *
 * This function implements the snprintf because the 
 * standard implementation has a bug with chibios stack.
 *
 */
size_t libwismart_snprintf(char *str, size_t size, const char *fmt, ...);

/**
 * \brief eConais implementation of sprintf
 *
 * This function implements the sprintf because the 
 * standard implementation has a bug with chibios stack
 *
 */
size_t libwismart_sprintf(char *str, const char *fmt, ...);

/** @} */

/*---------------------------------------------------------------------------*/


/** \addtogroup WSL_WIFI
*
* @{
*/


/** \brief Below are the power resources of power mgmt */
typedef enum {
    WISMART_WIFI_AP_CLIENT_CONNECTED        = 0, /*!< */
    WISMART_WIFI_AP_CLIENT_DISCONNECTED     = 1, /*!< */
    WISMART_WIFI_AP_CLIENT_EXPIRED          = 2, /*!< To be added */
    WISMART_WIFI_AP_CLIENT_GET_IP           = 3, /*!< */
} wismart_softap_cb_t;

/** \brief callback used to inform applications about new wifi clients.
 */
typedef void (*wismart_softap_clients_cb)(wismart_softap_cb_t         reason,
                                          const uint8_t               *mac,
                                          const libwismart_ip_addr_t  *ip);


/** \brief Create a WiFi network (Access Point mode)
 *
 * This function will create a new a WiFi Network. Other WiFi clients 
 * will be able to connect to it.
 *
 * @param ssid (unsigned char *) The SSID (network name) of the Access Point.
 * @param key (unsigned char *) PSK(raw key) or passphrase. Pass NULL for
 * open networks.
 * @param wificb callback will inform the application whether the new WiFi
 * network has been created or not.
 * @param clientscb callback will inform the application about the connection
 * changes of clients (added/deleted etc)
 */
int libwismart_WiFi_SoftAP_Start(char *ssid,
                                 uint8_t channel,
                                 unsigned char* key,
                                 wificonnect_callback wificb,
                                 wismart_softap_clients_cb clientscb);


/** \brief Stop SoftAP.
 *
 * This function will Stop the SoftAP and it will clean all the resources
 * that it's using. After that, the wifi module will be in shutdown mode.
 *
 */
int libwismart_WiFi_SoftAP_Stop(void);
/** @} */

/*---------------------------------------------------------------------------*/
/**
* \defgroup WSL_TCP_IP TCP/IP (LwIP)
*
* \brief Function related to TCP/IP stack which is based on LwIP open source project.
* The API is kept the same as in original LwIP project, but the code is heavily 
* modified and integrated with the Wi-Fi driver.
*
* @{
*/

/** \brief Lock the LwIP module for atomic access
 *
 * This function will lock the LwIP module for atomic access.
 *
 */
void libwismart_LwIP_lock(void);


/*---------------------------------------------------------------------------*/
/** \brief Unlock the LwIP module.
 *
 * This function will unlock the LwIP module for atomic access.
 *
 */
void libwismart_LwIP_unlock(void);

/*---------------------------------------------------------------------------*/
/** \brief Enabled BSD Socket API
 *
 * This function enables the BSD-like socket API of wismart and it's the 
 * first function to call before using the API. Check tcp_socket.c for an
 * example.
 *
 */
void libwismart_EnableBsdSocketAPI(void);


/*---------------------------------------------------------------------------*/
/** \brief Set a hostname for this device
 *
 * This function set the hostname of this device.
 * NOTE: this must be called after libwismart_WiFi_Init() 
 *       and before the wifi connection.
 *
 */
void libwismart_LwIP_SetHostname(char *hostname);

/** @} */

/** \addtogroup WSL_SYSTEM
*
* @{
*/


/*---------------------------------------------------------------------------*/
/** \brief USB configuration function
 */
void libwismart_USB_Init(void);

/** \brief USB processing function
 */
void libwismart_USB_Process(void);

#ifdef USB_LOCK

/** \brief USB lock function
 */
void libwismart_USB_lock(void);

/** \brief USB unlock function
 */
void libwismart_USB_unlock(void);
#endif /* USB_LOCK */

#ifdef FF_LOCK

/** \brief FF lock function
 */
void libwismart_FF_lock(void);

/** \brief FF unlock function
 */
void libwismart_FF_unlock(void);
#endif /* FF_LOCK */

/** \brief Return the hwif struct that define the selected hw defines.
 */
wismart_hwif_t libwismart_GetWismartHWIF(void);

/*---------------------------------------------------------------------------*/
/*  IRQ Handlers                                                             */
/*---------------------------------------------------------------------------*/


/*! \brief This function handles the WiFi Interrupt from FW
 *
 *  This function Handles the WiFi Interrupt from FW.
 *  This function must be called from the user for the selected external wifi irq.
 */
void libwismart_WiFi_IRQHandler(void);


/*! \brief This function handles the UART Rx Interrupt from debug serial port.
 *
 *  This function handles the UART Rx Interrupt from debug serial port.
 *  This function must be called from the user for the selected uart irq.
 */
void libwismart_UART_IRQHandler(void);

/*! \brief This function handles the UART Rx Interrupt from debug serial port.
 *
 *  This function handles the UART Rx Interrupt from debug serial port.
 *  This function must be called from the user for the selected uart irq.
 */
void libwismart_UART_TXDMA_IRQHandler(void);

/*! \brief This function handles the UART Rx Interrupt from debug serial port.
 *
 *  This function handles the UART Rx Interrupt from debug serial port.
 *  This function must be called from the user for the selected uart irq.
 */
void libwismart_UART_RXDMA_IRQHandler(void);

/*! \brief This function handles USB-On-The-Go FS/HS global interrupt request.
 *
 *  This function must be called from OTG_FS_IRQHandler or OTG_HS_IRQHandler irqs.
 */
void libwismart_USB_IRQHandling(void);

/** @} */


/*---------------------------------------------------------------------------*/
/* Commander Module (UART CLI application helper functions)                  */
/*---------------------------------------------------------------------------*/

/** \addtogroup COMMANDER_MODULE Commander Module
*
* \brief The group of functions used by the Commander application
* @{
*/

typedef void (*libwismart_cmd_execute)(char *argv[], uint8_t argc);

typedef struct{
    const char *cmd_name;
    libwismart_cmd_execute func;
    const char *cmd_help;
} libwismart_cmd_struct_t;


/*!
 * \brief Init the commander module with specific cmd table
 *
 * This function init the commander module with specific cmd table.
 *
 */
void libwismart_Commander_Init(libwismart_cmd_struct_t *cmd_table, uint8_t cmd_num );


/*!
 * \brief Send a char to the commander module.
 *
 * This function Send a char to the commander module. If the input is enter the cmd will be execute.
 *
 */
void libwismart_Commander_Input(char data);


/*!
 * \brief Send a char to the commander module from irq.
 *
 * This function Send a char to the commander module from irq context. If the input is enter the cmd will be execute.
 *
 */
void libwismart_Commander_InputI(char data);

/*!
 * \brief Proccess the executed cmd.
 *
 * This function process the executed cmd.
 * This function must be called inside of the main loop.
 *
 */
void libwismart_Commander_Proccess(void);

/*!
 * \brief Proccess the executed cmd.
 *
 * This function process the executed cmd.
 * This function must be called inside of the main loop.
 * This function will block until a cmd arive.
 * This is the best choise for power consuption.
 *
 */
void libwismart_Commander_Block_Proccess(void);

/** @} */

/*---------------------------------------------------------------------------*/
/* Pbuf Queues Manager Module                                                */
/*---------------------------------------------------------------------------*/

/** \defgroup PBUF_QUEUES Pbuf Queues
*
* \brief The group of functions that supports PBUF Queues operations
* @{
*/

/**
* \brief The structures below are used to store pbuf queues.
*/
typedef struct{
    struct pbuf    **queue;
    uint8_t          head_index;
    uint8_t          tail_index;
    uint8_t          len;
    uint8_t          max_len;
    Semaphore        sem;
} wismart_pbuf_queue_t;

/*!
 * \brief Init the pbuf queue.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 * @param max_len (uint8_t *) The max number of pbuf in queues.
 *
 */
void libwismart_PBufQueue_Init(wismart_pbuf_queue_t * queue, uint8_t max_len);

/*!
 * \brief Deinit the pbuf queue.
 *
 * Cleans the queue and will free any pbufs that have been stored.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 */
void libwismart_PBufQueue_Deinit(wismart_pbuf_queue_t * queue);

/*!
 * \brief Add a pbuf to the queue
 *
 * Add a pbuf to the queue if we have free space available. 
 * Otherwise return WISMART_FAILURE.
 * This function increases the pbuf reference. Because of this,
 * the user must free the pbuf after the use of this function.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 * @param p (struct pbuf *) The pbuf that we want to store.
 *
 * @return WISMART_SUCCESS if we add the pbuf successful.
 *
 */
uint8_t libwismart_PBufQueue_Add(wismart_pbuf_queue_t * queue,struct pbuf *p);

#define libwismart_PBufQueue_Add_Debug(q,p, _status) if(!(*_status=libwismart_PBufQueue_Add(q,p))) EC_DBG(TR_WIFI, "[%s][%d] Fail adding %x pbuf to "#q" queue\r\n", __func__, __LINE__, p)

/*!
 * \brief Get pbuf from the queue
 *
 * This funcion retrieves a pbuf from the queue but without remove it from the queue.
 * In case that the queue is empty the function returns NULL.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 * @return (struct pbuf *) The pbuf.
 *
 */
struct pbuf *libwismart_PBufQueue_GetLast(wismart_pbuf_queue_t * queue);


/*!
 * \brief Remove the last pbuf from the queue
 *
 * This function removes the last pbuf from the queue but without freeing it.
 * The user must free the pbuf when he has finished with the pbuf.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 * @return (struct pbuf *) The pbuf.
 *
 */
struct pbuf *libwismart_PBufQueue_RemoveLast(wismart_pbuf_queue_t * queue);

/*!
 * \brief Remove and free the last pbuf from the queue
 *
 * This function will remove and free the last pbuf from the queue.
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 * @return (struct pbuf *) The pbuf.
 *
 */
void libwismart_PBufQueue_RemoveFreeLast(wismart_pbuf_queue_t * queue);

/*!
 * \brief Return the state of the queue.
 *
 * This function will return whether the queue is full or not
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 * @return TRUE/FALSE
 *
 */
uint8_t libwismart_PBufQueue_isFull(wismart_pbuf_queue_t * queue);


/*!
 * \brief Return the state of the queue if is Empty
 *
 * This function will return whether the queue is empty or not
 *
 * @param queue (data_queue_t *) The pbuf queue.
 *
 * @return TRUE/FALSE
 *
 */
uint8_t libwismart_PBufQueue_isEmpty(wismart_pbuf_queue_t * queue);

/** @} */

/*---------------------------------------------------------------------------*/
/* WiFi Profile Configuration Module                                         */
/*---------------------------------------------------------------------------*/

/** \defgroup WIFI_PROFILES WiFi Profiles
*
* \brief The group of functions used by the WiFi profiles module
* @{
*/

/*
    Values for 'profile_enabled' profile configuration option
 */
enum {
    PROFILE_DISABLED,
    PROFILE_ENABLED
};

/*
    Values for 'wifi_mode' profile configuration option
 */
enum {
    PROFILE_WIFI_MODE_CLIENT = 1,
    PROFILE_WIFI_MODE_SOFTAP,
    PROFILE_WIFI_MODE_ADHOC,
    PROFILE_WIFI_MODE_WPS
};

/*
    Values for 'security' profile configuration option
 */
enum {
    PROFILE_SECURITY_OPEN = 1,
    PROFILE_SECURITY_WEP40,
    PROFILE_SECURITY_WEP104,
    PROFILE_SECURITY_WPA_WPA2
};

/*
    Values for 'dhcp_mode' profile configuration option

    PROFILE_DHCP_CLIENT_MODE: Enables the dhcp client, used in WiFi client mode and WPS
    PROFILE_STATIC_IP_MODE: Use a static IP configuration, used in WiFi client mode, AD-Hoc and WPS
    PROFILE_DHCP_SERVER_MODE: Enables the DHCP Server, used in WiFi SoftAP Mode only
 */
enum {
    PROFILE_DHCP_CLIENT_MODE = 1,
    PROFILE_STATIC_IP_MODE,
    PROFILE_DHCP_SERVER_MODE
};

/*
    Values for 'wps_method' profile configuration option
 */
enum {
    PROFILE_WPS_PIN_METHOD = 1,
    PROFILE_WPS_PUSH_BUTTON_METHOD
};

/*
    Values for 'fixed_rate' profile configuration option
 */
enum {
    PROFILE_AUTO_RATE =     0,    /* Auto rate */
    PROFILE_RATE_2MBPS =    0x84, /* 2 Mbps */
    PROFILE_RATE_5_5_MBPS = 0x8b, /* 5.5 Mbps */
    PROFILE_RATE_11_MBPS =  0x96, /* 11 Mbps */
    PROFILE_RATE_9_MBPS =   0x12, /* 9 Mbps */
    PROFILE_RATE_18_MBPS =  0x24, /* 18 Mbps */
    PROFILE_RATE_36_MBPS =  0x48, /* 36 Mbps */
    PROFILE_RATE_54_MBPS =  0x6c  /* 54 Mbps */
};

/*!
 * \brief Store a buffer in the profile
 *
 * This function will store a buffer in the configuration profile
 *
 */
int libwismart_ProfileSet_Buf(char* config_var, char* value);

/*!
 * \brief Store a string value in the profile
 *
 * This function will store a string value in the configuration profile
 *
 */
int libwismart_ProfileSet_Str(char* config_var, char* value);

/*!
 * \brief Store an integer value in the profile
 *
 * This function will store an integer value in the configuration profile
 *
 */
int libwismart_ProfileSet_Int(char* config_var, uint16_t value);

/*!
 * \brief Get a string value from the profile
 *
 * This function will get a string value from the configuration profile
 *
 */
int libwismart_ProfileGet_Str(char* config_var, char* out_value);

/*!
 * \brief Get an integer value in the profile
 *
 * This function will get an integer value in the configuration profile
 *
 */
int libwismart_ProfileGet_Int(char* config_var, uint16_t* out_value);

/*!
 * \brief Read a buffer from a profile
 *
 * This function will gread a buffer from a configuration profile
 *
 */
int libwismart_ProfileGet_Buf(char* config_var, char* out_value);
/** @} */

/*---------------------------------------------------------------------------*/
/* User Registry Module                                                      */
/*---------------------------------------------------------------------------*/

/** \defgroup Registry Registry
*
 * \brief The group of functions used by the Registry module
* @{
*/

typedef struct {
    uint16_t size;
    uint16_t address;
    uint16_t registryFile;
} wismart_registryKey_t;

/*!
 * \brief Create a registry key for a generic data type of size 'key_size'.
 *
 * This function will return a registry key for a specific data type that 
 * needs to be stored in registry. E.g if you have one struct and one 
 * array, this function should be called 2 times, one for each data type. 
 * 
 * Note that this function must be called before libwismart_RegistryOpen(). 
 * 
 * @param key (wismart_registryKey_t *) The returned registry key.
 * @param registryFile                  The registry file with which this key is related.
 * @param key_size                      The size of the registry key.
 *
 * @return WISMART_SUCCESS on success
 * @return WISMART_FAILURE if the data type does not fit in memory
 */
int libwismart_RegistryCreateKey(wismart_registryKey_t *key, uint16_t registryFile, uint32_t key_size);

/*!
 * \brief Opens a registry file
 * 
 * This function must be called only after all registry values have been 
 * registered with libwismart_RegistryCreateKey().
 * 
 * After calling this function the rest API is unlocked, and user can call
 * libwismart_RegistryGet(),libwismart_RegistrySet() and 
 * libwismart_RegistryIsValueEmpty().
 *
 * @param registryFile                  The registry file which is going to be opened.
 *
 * @return WISMART_SUCCESS on success
 * @return WISMART_FAILURE if the registry file fails to open
 */
int libwismart_RegistryOpen(uint16_t registryFile);

/*!
 * \brief Sets the value of a registry item.
 * 
 * This function will set the value of the selected registry
 * item using the registry key that has been created with
 * libwismart_RegistryCreateKey()
 *
 * @param key (wismart_registryKey_t *) The registry key.
 * @param pdata_in (void *) The address of data type containing
 *        the data to save
 *
 * @return WISMART_SUCCESS on success
 * @return WISMART_FAILURE on write error
 */
int libwismart_RegistrySet(wismart_registryKey_t *key, void *pdata_in);

/*!
 * \brief Gets the value of a registry item.
 * 
 * This function will get the value of the selected registry
 * item using the registry key that has been created with
 * libwismart_RegistryCreateKey()
 *
 * @param key (wismart_registryKey_t *) The registry key.
 * @param pdata_out (void *) Buffer containing the retrieved data
 *
 * @return WISMART_SUCCESS on success
 * @return WISMART_FAILURE on write error
 */
int libwismart_RegistryGet(wismart_registryKey_t *key, void *pdata_out);


/*!
 * \brief Checks if a registry item has a value.
 * 
 * This is true only if libwismart_RegistrySet() has been called at
 * least once.
 * 
 * @param key (wismart_registryKey_t *) The registry key.
 *
 * @retval 0 : if the registry item has a value
 * @retval 1 : if the registry item has not a value
 */
int libwismart_RegistryIsValueEmpty(wismart_registryKey_t* key);

/*!
 * \brief This function formats the registry. All settings will be lost.
 * 
 * @param registryFile                  The registry file which is going to be formatted.
 *
 * @retval WISMART_FAILURE  if there was an error while formating
 *         the registry file
 * @retval WISMART_SUCCESS  if the registry file was formated succesfully
 */        
int libwismart_RegistryFormat(uint16_t registryFile);

/** @} */
/*---------------------------------------------------------------------------*/
/* TCP Statistics                                                            */
/*---------------------------------------------------------------------------*/

typedef struct {
    uint16_t        xmit;
    uint16_t        drop;
    uint16_t        chkerr;
    uint16_t        err;
    uint16_t        rterr;
}   wismart_tcp_stats_t;

/*!
 * \brief Clears the TCP Statistics
 *
 * This function clears the TCP statistics
 *
 */
void libwismart_ClearTcpStats(void);

/*!
 * \brief Prints the TCP Statistics
 *
 * This function prints TCP statistics
 *
 */
void libwismart_PrintTcpStats(void);

/*!
 * \brief Retrieve TCP Statistics
 *
 * This function can be used to retrieve TCP statistics
 *
 * @param stats Structure containing the statistics
 */
void libwismart_GetTcpStats(wismart_tcp_stats_t* stats);

/** @} */
/*---------------------------------------------------------------------------*/
/* Console Commands                                                            */
/*---------------------------------------------------------------------------*/
/*!
 * \brief Send a Console Cmd
 *
 * This function Sends a console command to wifi fw
 *
 * @param command Buffer containing the command itself
 * @param command_len size of buffer
 */
void libwismart_SendConsoleRequest(unsigned char* command, uint16_t command_len);

/*---------------------------------------------------------------------------*/
/* DLNA API                                                                  */
/*---------------------------------------------------------------------------*/
/** \defgroup DLNA DLNA API
*
* \brief The group of functions to initialize library, Wi-Fi, TPC/IP and 
*  shutdown the Wi-Fi
* @{
*/

/**
    @brief Definiton for the setVolumeCb_t.
    @param volumeValue The value to which the volume must be set to. Values
            range from 0 to 100.
 */
typedef void        (*setVolumeCb_t)(uint32_t volumeValue);

/**
    @brief Definiton for the getVolumeCb_t.
    @retval The current value of the volume. Values range from 0 to 100.
 */
typedef uint32_t    (*getVolumeCb_t)(void);

/**
    @brief Definiton for the setMuteCb_t.
    @param muteValue The current status of the mute. Can be LW_DLNA_MUTE_ON or LW_DLNA_MUTE_OFF 
 */
typedef void        (*setMuteCb_t)(uint32_t muteValue);

/**
    @brief Definiton for the getMuteCb_t.
    @retval The current status of the mute. Can be LW_DLNA_MUTE_ON or LW_DLNA_MUTE_OFF 
 */
typedef uint32_t    (*getMuteCb_t)(void);

/**
    @brief Definiton for the setUriCb_t.
    @param uri The uri of the audio file
    @param ip The IP of the server in which the resource is located
    @param port The port of the server that user must connect to in order to retrieve the audio file
 */
typedef void        (*setUriCb_t)(uint8_t* uri);

/**
    @brief Definiton for the playCb_t.
    @note  User application should start playing the audio file from the current URI when this callback
            is called. Normally, the control device sends a STOP soap action, then a SET_URI soap action
            and finally a PLAY soap action. Some control devices send only the SET_URI and STOP actions.
            This means that when receiving a PLAY soap action, user application must stop the playback
            of the current audio file, and start playing the new file received from the SET_URI action.
 */
typedef void        (*playCb_t)(void);

/**
    @brief Definiton for the pauseCb_t.
 */
typedef void        (*pauseCb_t)(void);

/**
    @brief Definiton for the stopCb_t.
 */
typedef void        (*stopCb_t)(void);

/**
    @brief Definiton for the seekCb_t.
    @param bytePos The byte number from  which the playback must be continued.
 */
typedef void        (*seekCb_t)(uint32_t bytePos);

/**
    @brief Definition for DLNA_MUTE_ON
 */
#define DLNA_MUTE_ON    (1)

/**
    @brief Definition for DLNA_MUTE_OFF
 */
#define DLNA_MUTE_OFF   (0)


/**  
    @brief Initializes the DLNA stack. This includes all DLNA servers, connections
            and the related memory modules. Must be called when wismart's wifi is connected.
    @param dmrFriendlyName Registers the name with which the wismart DMR(speaker) will be listed when
            control devices scan for media renderers.
    @param dmsFriendlyName Registers the name with which the wismart DMS(server) will be listed when
            control devices scan for media server. Pass NULL if DMS functionality is not needed.
    @param manufacturer The name of the manufacturer. This name will be sent when control devices
            ask for the device descriptor.
    @param manufacturerUrl the URL of the manufacturer
    @param udn The unique identifier of the device. It is not permitted two dlna devices to share the same
            UDN. 
            \nUUIDs are 128 bit numbers that MUST be formatted as specified by the following grammar:
            
            \nUUID = 4 * <hexOctet> - 2 * <hexOctet> - 2 * <hexOctet> - 2 * <hexOctet> - 6 * <hexOctet>
            \nhexOctet = <hexDigit> <hexDigit> hexDigit = 0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|A|B|C|D|E|F
            
            \nThe following is an example of the string representation of a UUID:
            \n2fac1234-31f8-11b4-a222-08002b34c003
    @retval 0 on success
    @retval negative on error
*/
uint32_t libwismart_dlna_init(uint8_t * dmrFriendlyName, uint8_t * dmsFriendlyName, uint8_t* manufacturer, uint8_t* manufacturerUrl, uint8_t* udn);

uint32_t libwismart_dlna_connect(void);


/**
    @brief After calling this function the device will restart in softAp mode
            with SSID "WisAudio" and open encryption. User can connect to this
            network from his device, and by typing 192.168.1.1:50000 in device's
            web browser the configuration web page will show up.
 */
void dlnaEnterConfigurationMode(void);


/**
    @brief Enables DLNA's debug messages
 */
void libwismart_dlna_debugEnable(void);

/**
    @brief Disables DLNA's debug messages
 */
void libwismart_dlna_debugDisable(void);


/**
    @brief Informs the DLNA stack that the playback of the current audio file finished. This function
            must be called when the user application retrieved and played the whole file. The
            DLNA stack will then inform all subscribers that the current state of the audio/video
            transport is STOPPED, so they can update their GUIs (Stop their playback progress bar for example).
 */
void libwismart_dlna_playbackFinished(void);

/**
    @brief Informs the DLNA stack for the current byte position of the
            playback. With this function the DLNA stack updates the corresponding
            state variables, and all control points know the exact position of the playback, so
            they can update their seek bars.
    @param currentByte The current byte number that is be played.
    @param totalBytes The total size of the audio file. This is received from the HTTP response.
 */
void libwismart_dlna_updatePositionInfo(uint32_t currentByte, uint32_t totalBytes);


/**
    @brief Callback function tha DLNA stack uses to inform the user application
            that the volume must be set in a spesific level.
 */
void libwismart_dlna_setVolumeCb(setVolumeCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to get from the the user application
            the current volume level.
 */
void libwismart_dlna_getVolumeCb(getVolumeCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that the volume must muted
 */
void libwismart_dlna_setMuteCb(setMuteCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to get from the the user application
            the current mute state.
 */
void libwismart_dlna_getMuteCb(getMuteCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that it must start playing the the audio file from the current URI.
 */
void libwismart_dlna_playCb(playCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that the playback must be paused.
 */
void libwismart_dlna_pauseCb(pauseCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that the volume must be stopped.
 */
void libwismart_dlna_stopCb(stopCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that the playback must be continued from a certain point
 */
void libwismart_dlna_seekCb(seekCb_t funcPtr);

/**
    @brief Callback function tha DLNA stack uses in order to inform the user application
            that a the current URI was updated.
 */
void libwismart_dlna_setUriCb(setUriCb_t funcPtr);

/**
    @brief Opens a file from DMS.
 
    @param fileUri The url of the file to be opened
    @param seekPos The initial byte position from which the read will start
    @param fileSize Stores the size of the opened file in bytes
 
    @retval 0 on success
    @retval positive on error
 */
uint32_t libwismart_dlna_dmsFile_open(uint8_t* fileUri, uint32_t seekPos, uint32_t* fileSize );


/**
    @brief Closes the file opened with libwismart_dlna_dmsFile_open()
 
    @retval 0 on success
    @retval positive on error
 */
uint32_t libwismart_dlna_dmsFile_close(void);


/**
    @brief Reads data from DMS.
 
    @param dataBuffer The buffer in which the read data will be stored
    @param bytesRequested The size of 'dataBuffer' in bytes
    @param bytesReturned How many bytes where actually read
 
    @retval 0 on success
    @retval positive on error
 */
uint32_t libwismart_dlna_dmsFile_read(uint8_t* dataBuffer, uint32_t bytesRequested, uint32_t* bytesReturned);


/**
    @brief Locks the sychronization object for dms open/read/close operations
 */
void libwismart_dlna_dmsFile_lock(void);


/**
    @brief Unlocks the sychronization object for dms open/read/close operations
 */
void libwismart_dlna_dmsFile_unlock(void);


/** @} */



/*---------------------------------------------------------------------------*/
/* HTTP SERVER API                                                           */
/*---------------------------------------------------------------------------*/
/** \defgroup HTTP_SERVER_API HTTP Server API
*
* \brief The group of functions to initialize and use the internal HTTP server
* @{
*/

/**
    @brief Memory allocation types for buffers passed into the HTTP server 
 */
enum WISMART_SERVER_ALLOC_T{
    WISMART_SERVER_ALLOC_STATIC = 0, ///< Inform server that the specific buffer is static, and no de-allocation should be made
    WISMART_SERVER_ALLOC_DYNAMIC,    ///< Inform server that the specific buffer is dynamic, and the server should call the wismart_server_free_cb_t function in order to free the memory
};

/**
    @brief HTTP server's callback return values 
 */
enum WISMART_SERVER_ERR_T{
    WISMART_SERVER_ERR_OK = 0,
    WISMART_SERVER_ERR_MEM,
    WISMART_SERVER_ERR_NOT_READY,
    WISMART_SERVER_ERR_FATAL,
    WISMART_SERVER_ERR_NOT_FOUND,
    WISMART_SERVER_ERR_STRING_NOT_FOUND = 0xffffff00,
    WISMART_SERVER_ERR_OTHER
};

/**
    @brief This struct is used to describe the HTTP resources
            that are to be handled by the HTTP Server
 */
typedef struct {
    /**
        @brief The name of the resource
    */
    char*       name;
    /**
        @brief Specifies if the resource has dynamic content
    */
    uint8_t     hasDynamicContent;
    /**
        @brief Specifies any function that should be called when the resource is requested
    */
    void        (*scriptCb)(void);
    /**
        @brief Pointer to resource's data
    */
    uint8_t*    dataPtr;
    /**
        @brief The file size of the resource
    */
    uint32_t    dataSize;
    /**
        @brief The mime type of the resource
    */
    char*       mimeType;
    /**
        @brief Specifies if the browser is allowed to cache the resource locally
                in order the page to be loaded faster
    */
    uint8_t     canBeCached;
}wismart_server_resource_t;

/**
    @brief Type definition of the callback function to be called when the dynamic
            content should be processed
 */
typedef uint32_t    (*wismart_server_dynamic_cb_t)(char* varName, char** varValue, uint8_t* varAllocType);

/**
    @brief Type definition of the callback function to be called when dynamically allocated memory should be freed
 */
typedef void        (*wismart_server_free_cb_t)(void*);

/**
    @brief This function allocates memory for the HTTP server and starts the server thread.
 
    @param serverPort Server's listening port (Usually 80)
    @param serverName Desired server's name, used in HTTP responses
    @param dynamicCb  callback function to be called when the dynamic content should be processed
    @param freeCb     callback function to be called when dynamically allocated memory should be freed
    @param resources  An array of the HTTP resources to be handled by the server. The last resource should
                        have the 'name' field point to NULL in order the server to know the number of the resources.
 */
uint32_t libwismart_server_start(uint16_t serverPort, char* serverName, wismart_server_dynamic_cb_t dynamicCb, wismart_server_free_cb_t freeCb, wismart_server_resource_t* resources);
uint32_t libwismart_server_connect(void);
uint32_t libwismart_server_GET(char* variableName, char* variableValue, uint32_t maxVariableValueLen);
uint32_t libwismart_server_POST(char* variableName, char* variableValue, uint32_t maxVariableValueLen);


/** @} */




/*---------------------------------------------------------------------------*/
/* Link List Util                                                            */
/*---------------------------------------------------------------------------*/
/** \defgroup STM32_PERIPHERALS MCU Peripheral locks
*
* \brief The group of functions that make thread safe some peripheral resources.
* @{
*/

void libwismart_peripheral_lock(uint8_t wimsartPeripheral);
void libwismart_peripheral_unlock(uint8_t wimsartPeripheral);
    
/** @} */

/*---------------------------------------------------------------------------*/
/* Link List Util                                                            */
/*---------------------------------------------------------------------------*/
/** \defgroup STM32_PERIPHERALS Over The Air (OTA) Upgrade
*
* \brief The group of functions that make possible to upgrade firmware over the air
* @{
*/
uint8_t libwismart_set_ota_ftp_parameters(char* wifi_ssid, char* wifi_passphrase, char* ftp_server_ip, uint16_t ftp_server_port, char* ftp_username, char* ftp_password, char* ftp_filename, uint8_t keepApplicationRegistrySettings);
/** @} */

/*---------------------------------------------------------------------------*/
/* Link List Util                                                            */
/*---------------------------------------------------------------------------*/
/** \defgroup LINK_LIST Linked Lists API
*
* \brief The group of functions to initialize and use of thread save of link list API.
* @{
*/

typedef struct wismart_link_list_node{
    struct wismart_link_list_node   *next;
    void                            *data;
} wismart_link_list_node_t;

typedef struct wismart_link_list{
    wismart_link_list_node_t    *root;
    Semaphore                    sem;
    uint16_t                     len;
} wismart_link_list_t;

wismart_link_list_t* libwismart_LinkList_Init(void);

uint8_t libwismart_LinkList_AddLast(wismart_link_list_t *list,void *data);

uint8_t libwismart_LinkList_AddFirst(wismart_link_list_t *list,void *data);

uint8_t libwismart_LinkList_AddAfter(wismart_link_list_t *list,void *preData,void *data);

uint8_t libwismart_LinkList_Exist(wismart_link_list_t *list,void *data);

uint8_t libwismart_LinkList_Remove(wismart_link_list_t *list,void *data);

void *libwismart_LinkList_RemoveFirst(wismart_link_list_t *list);

void *libwismart_LinkList_RemoveLast(wismart_link_list_t *list);

void *libwismart_LinkList_GetLast(wismart_link_list_t *list);

void *libwismart_LinkList_GetFirst(wismart_link_list_t *list);

void *libwismart_LinkList_GetFirstNode(wismart_link_list_t *list);


uint8_t libwismart_LinkList_FilterExec(wismart_link_list_t *list, 
                                       uint8_t (*selection)(void *data),
                                       void    (*func)(void *data));

void
libwismart_LinkList_Exec(wismart_link_list_t *list,
                         void    *priv_data,
                         void   (*func)(void *priv_data, void *data));

void *
libwismart_LinkList_Find(wismart_link_list_t *list,
                         void    *priv_data,
                         uint8_t  (*func)(void *priv_data, void *data));

void *
libwismart_LinkList_FindAndRemove(wismart_link_list_t *list,
                                  void    *priv_data,
                                  uint8_t (*func)(void *priv_data, void *data));

uint16_t
libwismart_LinkList_Count(wismart_link_list_t *list);

/** @} */

/**
    @brief WiSmart Recover Mechanism 
*/
int libwismart_WiFiReInit(void);


#endif /* LIBWISMART_H_ */


/** @} */