diff --git a/README.md b/README.md
index 584decf..8146421 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,59 @@
# WIZ550S2E
-Serial to Ethernet Module based on W5500 & Cortex-M0
+Serial to Ethernet Module based on [W5500](http://wizwiki.net/wiki/doku.php?id=products:w5500:start) & Cortex-M0
## Firmware
-These are Firmware projects (source code) based on LPCXpresso IDE.
-Firmware source code.
+These are Firmware projects (source code) based on LPCXpresso IDE (it has been optimized in LPCXpresso v7.5.0_254(recommend)).
+
+These are can't build on LPCXpresso v8.x.x. We recommend LPCXpresso v7.5.0_254.
+
+- [Official Download Page](https://nxp.flexnetoperations.com/control/frse/product?child_plneID=730797&cert_num=276240197&ver=ARC).
+- [Direct Download Link](https://s3.amazonaws.com/LPCXpresso7/LPCXpresso_7.5.0_254.exe) (Windows).
+
+Firmware source code are two types as follows.
- Application
-- Boot
+- Bootloader
-**the order of compile.**
+**The order of compile**
1. lpc_chip_11exx.
2. wiznet_s2e_wiz550s2e_board.
-3. WIZ550S2E_App.
+3. WIZ550S2E_App or WIZ550S2E_Boot.
+
+- [...More detail](http://wizwiki.net/forum/viewtopic.php?f=109&t=3586&p=10892&hilit=LPCXpresso+v7.5.0_254#p10892)
![s2e](http://wizwiki.net/wiki/lib/exe/fetch.php?t=1428621268&w=499&h=203&tok=26df60&media=products:wiz550s2e:s2e.png "s2e")
+**Firmware download**
+
+In this case there is only just [.hex file.](https://github.com/Wiznet/WIZ550S2E/releases)
+
+If you would like to use [.bin file](http://wizwiki.net/wiki/doku.php?id=products:wiz550s2e:wiz550s2e_download), look at the following that : Configuration Tool/FW Uploading in [WIZ550S2E Wiki page](http://wizwiki.net/wiki/doku.php?id=products:wiz550s2e:start)
+
+1. Connect WIZ550S2E and RS232I/F board and DC+5V adpater and RS232 serial cable and lan cable.
+
+
+
+
+2. HW/TRIG switch off.
+
+
+
+
+3. Check LED.
+
+
+
+
+4. Short J5 and push reset switch.
+
+
+
+
+5. firmware download using [Flash Magic](http://www.flashmagictool.com/).
+
+
+
+
## Images
### WIZ550S2E Module
@@ -67,7 +106,7 @@ Firmware source code.
- Status LEDs
- DC-Jack (for +5V Input Power)
-For more details, please refer to [WIZ550S2Eweb Wiki page](http://wizwiki.net/wiki/doku.php?id=products:wiz550s2e:start) in [WIZnet Wiki](http://wizwiki.net).
+For more details, please refer to [WIZ550S2E Wiki page](http://wizwiki.net/wiki/doku.php?id=products:wiz550s2e:start) in [WIZnet Wiki](http://wizwiki.net).
## Configuration Tool
@@ -93,3 +132,41 @@ Install JAVA Runtime Environment
## Revision History
v1.0.0
- First release : Apr. 2015
+
+v1.0.1
+- Fixed Project set
+
+v1.0.2
+- Fixed bug
+ - In mixed mode
+ - Before : when connecting to the server, the '+' had to be include in the serial data.
+ - After : when serial data is generated directly connecting.
+ - In AT command
+ - Before : at = a t. in other words, ignore space.
+ - After : at != a t. in other words, admitte space.
+- Add function
+ - Check unlink in mixed mode
+ - AT+FDNS = domain name
+
+v1.0.3
+- Fixed bug
+ - AT Command Trigger
+ - Before : AT command is actived regardless of AT command enable.
+ - After : AT command is actived regard of AT command enable.
+- Add function
+ - AT+NMODE : (AT command) Saving the changes made to AT mode to memory.
+
+v1.0.4
+- Fixed bug
+ - Time packing problem in UDP mode.
+ - Before : Not work normally after the first time.
+ - After : Work normally
+ - Upper and lower case problems in config Data.
+ - Before : Only uppercase letters work normally.
+ - After : Works in both uppercase and lowercase.
+
+v1.1.0
+- ioLibrary Update
+- Dependency Removal (remove "board.h" in "w5500.h")
+- Remove garbage file
+
\ No newline at end of file
diff --git a/WIZ550S2E_App/.cproject b/WIZ550S2E_App/.cproject
index b861473..9a7e05d 100644
--- a/WIZ550S2E_App/.cproject
+++ b/WIZ550S2E_App/.cproject
@@ -19,7 +19,7 @@
-
+
@@ -150,6 +150,7 @@
+
diff --git a/WIZ550S2E_App/.settings/language.settings.xml b/WIZ550S2E_App/.settings/language.settings.xml
deleted file mode 100644
index 5641b67..0000000
--- a/WIZ550S2E_App/.settings/language.settings.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/WIZ550S2E_App/Release/makefile b/WIZ550S2E_App/Release/makefile
new file mode 100644
index 0000000..0a37c68
--- /dev/null
+++ b/WIZ550S2E_App/Release/makefile
@@ -0,0 +1,69 @@
+################################################################################
+# Automatically-generated file. Do not edit!
+################################################################################
+
+-include ../makefile.init
+
+RM := rm -rf
+
+# All of the sources participating in the build are defined here
+-include sources.mk
+-include src/netutil/subdir.mk
+-include src/callback/subdir.mk
+-include src/S2E/subdir.mk
+-include src/PlatformHandler/subdir.mk
+-include src/Internet/httpServer/subdir.mk
+-include src/Internet/TFTP/subdir.mk
+-include src/Internet/SNTP/subdir.mk
+-include src/Internet/SNMP/subdir.mk
+-include src/Internet/MQTT/MQTTPacket/src/subdir.mk
+-include src/Internet/MQTT/subdir.mk
+-include src/Internet/FTPServer/subdir.mk
+-include src/Internet/FTPClient/subdir.mk
+-include src/Internet/DNS/subdir.mk
+-include src/Internet/DHCP/subdir.mk
+-include src/Ethernet/W5500/subdir.mk
+-include src/Ethernet/subdir.mk
+-include src/Configuration/subdir.mk
+-include src/ATcmd/library/subdir.mk
+-include src/ATcmd/subdir.mk
+-include src/subdir.mk
+-include subdir.mk
+-include objects.mk
+
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(strip $(C_DEPS)),)
+-include $(C_DEPS)
+endif
+endif
+
+-include ../makefile.defs
+
+# Add inputs and outputs from these tool invocations to the build variables
+
+# All Target
+all: WIZ550S2E_App.axf
+
+# Tool invocations
+WIZ550S2E_App.axf: $(OBJS) $(USER_OBJS)
+ @echo 'Building target: $@'
+ @echo 'Invoking: MCU Linker'
+ arm-none-eabi-gcc -nostdlib -L"D:\__Workspace\___Source\WIZnet\WIZ550S2E\wiznet_s2e_wiz550s2e_board\Release" -L"D:\__Workspace\___Source\WIZnet\WIZ550S2E\lpc_chip_11exx\Release" -Xlinker -Map="WIZ550S2E_App.map" -Xlinker --gc-sections -Xlinker --allow-multiple-definition -mcpu=cortex-m0 -mthumb -T "WIZ550S2E.ld" -L ../linkscripts -o "WIZ550S2E_App.axf" $(OBJS) $(USER_OBJS) $(LIBS)
+ @echo 'Finished building target: $@'
+ @echo ' '
+ $(MAKE) --no-print-directory post-build
+
+# Other Targets
+clean:
+ -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) WIZ550S2E_App.axf
+ -@echo ' '
+
+post-build:
+ -@echo 'Performing post-build steps'
+ -arm-none-eabi-size "WIZ550S2E_App.axf" ; arm-none-eabi-objcopy -O ihex "WIZ550S2E_App.axf" "WIZ550S2E_App.hex" ; arm-none-eabi-objcopy -v -O binary "WIZ550S2E_App.axf" "WIZ550S2E_App.bin" ; # checksum -p LPC11E36_501 -d "WIZ550S2E_App.bin"
+ -@echo ' '
+
+.PHONY: all clean dependents
+.SECONDARY: post-build
+
+-include ../makefile.targets
diff --git a/WIZ550S2E_App/src/Ethernet/W5500/w5500.c b/WIZ550S2E_App/src/Ethernet/W5500/w5500.c
index 2cfd6fd..68d4cb8 100644
--- a/WIZ550S2E_App/src/Ethernet/W5500/w5500.c
+++ b/WIZ550S2E_App/src/Ethernet/W5500/w5500.c
@@ -2,19 +2,23 @@
//
//! \file w5500.c
//! \brief W5500 HAL Interface.
-//! \version 1.0.1
+//! \version 1.0.2
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2014/05/01> V1.0.2
//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501
//! Fixed the problem on porting into under 32bit MCU
//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh
//! Thank for your interesting and serious advices.
-//! <2013/10/21> 1st Release
//! <2013/12/20> V1.0.1
//! 1. Remove warning
//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_
//! for loop optimized(removed). refer to M20131220
+//! <2013/10/21> 1st Release
//! \author MidnightCow
//! \copyright
//!
@@ -55,6 +59,7 @@
#define _W5500_SPI_FDM_OP_LEN2_ 0x02
#define _W5500_SPI_FDM_OP_LEN4_ 0x03
+#if (_WIZCHIP_ == 5500)
////////////////////////////////////////////////////
uint8_t WIZCHIP_READ(uint32_t AddrSel)
@@ -69,7 +74,7 @@ uint8_t WIZCHIP_READ(uint32_t AddrSel)
if(!WIZCHIP.IF.SPI._read_burst || !WIZCHIP.IF.SPI._write_burst) // byte operation
{
- WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16);
+ WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16);
WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8);
WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0);
}
@@ -259,3 +264,4 @@ void wiz_recv_ignore(uint8_t sn, uint16_t len)
setSn_RX_RD(sn,ptr);
}
+#endif
diff --git a/WIZ550S2E_App/src/Ethernet/W5500/w5500.h b/WIZ550S2E_App/src/Ethernet/W5500/w5500.h
index f0ffcb0..44c1aa5 100644
--- a/WIZ550S2E_App/src/Ethernet/W5500/w5500.h
+++ b/WIZ550S2E_App/src/Ethernet/W5500/w5500.h
@@ -5,6 +5,10 @@
//! \version 1.0.0
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2013/10/21> 1st Release
//! \author MidnightCow
//! \copyright
@@ -39,12 +43,17 @@
//
//*****************************************************************************
+//
+
#ifndef _W5500_H_
#define _W5500_H_
#include
-#include "../wizchip_conf.h"
-#include "board.h"
+#include "wizchip_conf.h"
+
+/// @cond DOXY_APPLY_CODE
+#if (_WIZCHIP_ == 5500)
+/// @endcond
#define _W5500_IO_BASE_ 0x00000000
@@ -144,7 +153,7 @@
* @sa MR : Mode register.
* @sa GAR, SUBR, SHAR, SIPR
* @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt.
- * @sa RTR, RCR : Data retransmission.
+ * @sa _RTR_, _RCR_ : Data retransmission.
* @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE.
* @sa UIPR, UPORTR : ICMP message.
* @sa PHYCFGR, VERSIONR : etc.
@@ -197,9 +206,9 @@
*
RST
Reserved
WOL
PB
PPPoE
Reserved
FARP
Reserved
*
* - \ref MR_RST : Reset
- * - \ref MR_WOL : Wake on LAN
- * - \ref MR_PB : Ping block
- * - \ref MR_PPPOE : PPPoE mode
+ * - \ref MR_WOL : Wake on LAN
+ * - \ref MR_PB : Ping block
+ * - \ref MR_PPPOE : PPPoE mode
* - \ref MR_FARP : Force ARP mode
*/
#define MR (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_CREG_BLOCK << 3))
@@ -259,10 +268,10 @@
/**
* @ingroup Common_register_group
* @brief Interrupt mask register(R/W)
- * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR.
- * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words,
- * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n
- * Each bit of @ref IMR defined as the following.
+ * @details @ref _IMR_ is used to mask interrupts. Each bit of @ref _IMR_ corresponds to each bit of @ref IR.
+ * When a bit of @ref _IMR_ is and the corresponding bit of @ref IR is an interrupt will be issued. In other words,
+ * if a bit of @ref _IMR_ is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n
+ * Each bit of @ref _IMR_ defined as the following.
*
*
7
6
5
4
3
2
1
0
*
IM_IR7
IM_IR6
IM_IR5
IM_IR4
Reserved
Reserved
Reserved
Reserved
@@ -272,7 +281,9 @@
* - \ref IM_IR5 : PPPoE Close Interrupt Mask
* - \ref IM_IR4 : Magic Packet Interrupt Mask
*/
-#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3))
+//M20150401 : Rename SYMBOE ( Re-define error in a compile)
+//#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3))
+#define _IMR_ (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3))
/**
* @ingroup Common_register_group
@@ -294,20 +305,24 @@
/**
* @ingroup Common_register_group
* @brief Timeout register address( 1 is 100us )(R/W)
- * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000
- * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response
+ * @details @ref _RTR_ configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref _RTR_ is x07D0.
+ * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref _RTR_, W5500 waits for the peer response
* to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command).
- * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout.
+ * If the peer does not respond within the @ref _RTR_ time, W5500 retransmits the packet or issues timeout.
*/
-#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3))
+//M20150401 : Rename SYMBOE ( Re-define error in a compile)
+//#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3))
+#define _RTR_ (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3))
/**
* @ingroup Common_register_group
* @brief Retry count register(R/W)
- * @details @ref RCR configures the number of time of retransmission.
- * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = .
+ * @details @ref _RCR_ configures the number of time of retransmission.
+ * When retransmission occurs as many as ref _RCR_+1 Timeout interrupt is issued (@ref Sn_IR_TIMEOUT = '1').
*/
-#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3))
+//M20150401 : Rename SYMBOE ( Re-define error in a compile)
+//#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3))
+#define _RCR_ (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3))
/**
* @ingroup Common_register_group
@@ -348,7 +363,7 @@
* @ingroup Common_register_group
* @brief Unreachable IP register address in UDP mode(R)
* @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number
- * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates
+ * which socket is not open and @ref IR_UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates
* the destination IP address & port number respectively.
*/
#define UIPR (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_CREG_BLOCK << 3))
@@ -357,7 +372,7 @@
* @ingroup Common_register_group
* @brief Unreachable Port register address in UDP mode(R)
* @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number
- * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR
+ * which socket is not open and @ref IR_UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR
* indicates the destination IP address & port number respectively.
*/
#define UPORTR (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_CREG_BLOCK << 3))
@@ -485,7 +500,7 @@
* @ingroup Socket_register_group
* @brief source port register(R/W)
* @details @ref Sn_PORT configures the source port number of Socket n.
- * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered.
+ * It is valid when Socket n is used in TCP/UDP mode. It should be set before OPEN command is ordered.
*/
#define Sn_PORT(N) (_W5500_IO_BASE_ + (0x0004 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3))
@@ -501,8 +516,8 @@
* @ingroup Socket_register_group
* @brief Peer IP register address(R/W)
* @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode.
- * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command.
- * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection.
+ * In TCP client mode, it configures an IP address of TCP serverbefore CONNECT command.
+ * In TCP server mode, it indicates an IP address of TCP clientafter successfully establishing connection.
* In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command.
*/
#define Sn_DIPR(N) (_W5500_IO_BASE_ + (0x000C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3))
@@ -511,8 +526,8 @@
* @ingroup Socket_register_group
* @brief Peer port register address(R/W)
* @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode.
- * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command.
- * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection.
+ * In TCP clientmode, it configures the listen port number of TCP serverbefore CONNECT command.
+ * In TCP Servermode, it indicates the port number of TCP client after successfully establishing connection.
* In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command.
*/
#define Sn_DPORT(N) (_W5500_IO_BASE_ + (0x0010 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3))
@@ -816,7 +831,7 @@
* 1 : Enable No Delayed ACK option\n
* This bit is applied only during TCP mode (P[3:0] = 001.\n
* When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n
- * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR.
+ * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref _RTR_.
*/
#define Sn_MR_ND 0x20
@@ -913,46 +928,46 @@
* The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n
*
*
\b Sn_MR (P[3:0])
\b Sn_SR
- *
Sn_MR_CLOSE (000
- *
Sn_MR_TCP (001
SOCK_INIT (0x13)
- *
Sn_MR_UDP (010
SOCK_UDP (0x22)
- *
S0_MR_MACRAW (100
SOCK_MACRAW (0x02)
+ *
Sn_MR_CLOSE (000)
+ *
Sn_MR_TCP (001)
SOCK_INIT (0x13)
+ *
Sn_MR_UDP (010)
SOCK_UDP (0x22)
+ *
S0_MR_MACRAW (100)
SOCK_MACRAW (0x02)
*
*/
#define Sn_CR_OPEN 0x01
/**
* @brief Wait connection request in TCP mode(Server mode)
- * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP).
- * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client
- * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN.
- * When a �TCP clientconnection request is successfully established,
- * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes
- * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED.
+ * @details This is valid only in TCP mode (\ref Sn_MR(P3:P0) = \ref Sn_MR_TCP).
+ * In this mode, Socket n operates as a TCP serverand waits for connection-request (SYN packet) from any TCP client
+ * The @ref Sn_SR changes the state from \ref SOCK_INIT to \ref SOCKET_LISTEN.
+ * When a TCP clientconnection request is successfully established,
+ * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the @ref Sn_IR(0) becomes
+ * But when a TCP clientconnection request is failed, @ref Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED.
*/
#define Sn_CR_LISTEN 0x02
/**
* @brief Send connection request in TCP mode(Client mode)
- * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port).
+ * @details To connect, a connect-request (SYN packet) is sent to TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port).
* If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n
* The connect-request fails in the following three cases.\n
* 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n
* 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n
* 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED.
- * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client
+ * @note This is valid only in TCP mode and operates when Socket n acts as TCP client
*/
#define Sn_CR_CONNECT 0x04
/**
* @brief Send closing request in TCP mode
- * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n
+ * @details Regardless of TCP serveror TCP client the DISCON command processes the disconnect-process (b>Active closeor Passive close.\n
* @par Active close
* it transmits disconnect-request(FIN packet) to the connected peer\n
* @par Passive close
* When FIN packet is received from peer, a FIN packet is replied back to the peer.\n
* @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n
- * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED.
+ * Otherwise, TCPTO occurs (\ref Sn_IR(3)='1') and then @ref Sn_SR is changed to @ref SOCK_CLOSED.
* @note Valid only in TCP mode.
*/
#define Sn_CR_DISCON 0x08
@@ -1031,24 +1046,24 @@
/* Sn_SR values */
/**
* @brief Closed
- * @details This indicates that Socket n is released.\N
+ * @details This indicates that Socket n is released.\n
* When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status.
*/
#define SOCK_CLOSED 0x00
/**
* @brief Initiate state
- * @details This indicates Socket n is opened with TCP mode.\N
- * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N
+ * @details This indicates Socket n is opened with TCP mode.\n
+ * It is changed to @ref SOCK_INIT when @ref Sn_MR(P[3:0]) = 001 and OPEN command is ordered.\n
* After @ref SOCK_INIT, user can use LISTEN /CONNECT command.
*/
#define SOCK_INIT 0x13
/**
* @brief Listen state
- * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n
+ * @details This indicates Socket n is operating as TCP servermode and waiting for connection-request (SYN packet) from a peer TCP client.\n
* It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n
- * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = .
+ * Otherwise it will change to @ref SOCK_CLOSED after TCPTO @ref Sn_IR(TIMEOUT) = '1') is occurred.
*/
#define SOCK_LISTEN 0x14
@@ -1057,7 +1072,7 @@
* @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n
* It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n
* If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n
- * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred.
+ * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = '1') is occurred.
*/
#define SOCK_SYNSENT 0x15
@@ -1065,14 +1080,14 @@
* @brief Connection state
* @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n
* If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n
- * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = .
+ * If not, it changes to @ref SOCK_CLOSED after timeout (@ref Sn_IR[TIMEOUT] = '1') is occurred.
*/
#define SOCK_SYNRECV 0x16
/**
* @brief Success to connect
* @details This indicates the status of the connection of Socket n.\n
- * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or
+ * It changes to @ref SOCK_ESTABLISHED when the TCP SERVERprocessed the SYN packet from the TCP CLIENTduring @ref SOCK_LISTEN, or
* when the CONNECT command is successful.\n
* During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command.
*/
@@ -1113,14 +1128,14 @@
/**
* @brief Closing state
* @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n
- * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = .
+ * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout(@ref Sn_IR[TIMEOUT] = '1') is occurred.
*/
#define SOCK_LAST_ACK 0x1D
/**
* @brief UDP socket
- * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n
- * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n
+ * @details This indicates Socket n is opened in UDP mode(@ref Sn_MR(P[3:0]) = '010').\n
+ * It changes to SOCK_UDP when @ref Sn_MR(P[3:0]) = '010' and @ref Sn_CR_OPEN command is ordered.\n
* Unlike TCP mode, data can be transfered without the connection-process.
*/
#define SOCK_UDP 0x22
@@ -1163,6 +1178,10 @@
*/
#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter()
+#ifdef _exit
+#undef _exit
+#endif
+
/**
* @brief Exit a critical section
*
@@ -1174,13 +1193,9 @@
* @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF()
* @sa WIZCHIP_CRITICAL_ENTER()
*/
-#ifdef _exit
-#undef _exit
-#endif
#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit()
-
////////////////////////
// Basic I/O Function //
////////////////////////
@@ -1333,8 +1348,13 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @return uint16_t. Value of @ref INTLEVEL register.
* @sa setINTLEVEL()
*/
+//M20150401 : Type explict declaration
+/*
#define getINTLEVEL() \
((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1)))
+*/
+#define getINTLEVEL() \
+ (((uint16_t)WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1)))
/**
* @ingroup Common_register_access_function
@@ -1355,22 +1375,21 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
(WIZCHIP_READ(IR) & 0xF0)
/**
* @ingroup Common_register_access_function
- * @brief Set @ref IMR register
- * @param (uint8_t)imr Value to set @ref IMR register.
+ * @brief Set @ref _IMR_ register
+ * @param (uint8_t)imr Value to set @ref _IMR_ register.
* @sa getIMR()
*/
#define setIMR(imr) \
- WIZCHIP_WRITE(IMR, imr)
+ WIZCHIP_WRITE(_IMR_, imr)
/**
* @ingroup Common_register_access_function
- * @brief Get @ref IMR register
- * @return uint8_t. Value of @ref IMR register.
+ * @brief Get @ref _IMR_ register
+ * @return uint8_t. Value of @ref _IMR_ register.
* @sa setIMR()
*/
#define getIMR() \
- WIZCHIP_READ(IMR)
-
+ WIZCHIP_READ(_IMR_)
/**
* @ingroup Common_register_access_function
@@ -1409,41 +1428,47 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
/**
* @ingroup Common_register_access_function
- * @brief Set @ref RTR register
- * @param (uint16_t)rtr Value to set @ref RTR register.
+ * @brief Set @ref _RTR_ register
+ * @param (uint16_t)rtr Value to set @ref _RTR_ register.
* @sa getRTR()
*/
#define setRTR(rtr) {\
- WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \
- WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(RTR,1), (uint8_t) rtr); \
+ WIZCHIP_WRITE(_RTR_, (uint8_t)(rtr >> 8)); \
+ WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(_RTR_,1), (uint8_t) rtr); \
}
/**
* @ingroup Common_register_access_function
- * @brief Get @ref RTR register
- * @return uint16_t. Value of @ref RTR register.
+ * @brief Get @ref _RTR_ register
+ * @return uint16_t. Value of @ref _RTR_ register.
* @sa setRTR()
*/
+//M20150401 : Type explict declaration
+/*
#define getRTR() \
- ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(RTR,1)))
+ ((WIZCHIP_READ(_RTR_) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(_RTR_,1)))
+*/
+#define getRTR() \
+ (((uint16_t)WIZCHIP_READ(_RTR_) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(_RTR_,1)))
+
/**
* @ingroup Common_register_access_function
- * @brief Set @ref RCR register
- * @param (uint8_t)rcr Value to set @ref RCR register.
+ * @brief Set @ref _RCR_ register
+ * @param (uint8_t)rcr Value to set @ref _RCR_ register.
* @sa getRCR()
*/
#define setRCR(rcr) \
- WIZCHIP_WRITE(RCR, rcr)
+ WIZCHIP_WRITE(_RCR_, rcr)
/**
* @ingroup Common_register_access_function
- * @brief Get @ref RCR register
- * @return uint8_t. Value of @ref RCR register.
+ * @brief Get @ref _RCR_ register
+ * @return uint8_t. Value of @ref _RCR_ register.
* @sa setRCR()
*/
#define getRCR() \
- WIZCHIP_READ(RCR)
+ WIZCHIP_READ(_RCR_)
//================================================== test done ===========================================================
@@ -1485,7 +1510,7 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
/**
* @ingroup Common_register_access_function
- * @brief Set PHAR address
+ * @brief Set @ref PHAR address
* @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes.
* @sa getPHAR()
*/
@@ -1494,7 +1519,7 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
/**
* @ingroup Common_register_access_function
- * @brief Get local IP address
+ * @brief Get @ref PHAR address
* @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes.
* @sa setPHAR()
*/
@@ -1519,8 +1544,13 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @sa setPSID()
*/
//uint16_t getPSID(void);
+//M20150401 : Type explict declaration
+/*
#define getPSID() \
((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1)))
+*/
+#define getPSID() \
+ (((uint16_t)WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1)))
/**
* @ingroup Common_register_access_function
@@ -1539,24 +1569,39 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @return uint16_t. Value of @ref PMRU register.
* @sa setPMRU()
*/
+//M20150401 : Type explict declaration
+/*
#define getPMRU() \
((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1)))
+*/
+#define getPMRU() \
+ (((uint16_t)WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1)))
/**
* @ingroup Common_register_access_function
* @brief Get unreachable IP address
* @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes.
*/
+//M20150401 : Size Error of UIPR (6 -> 4)
+/*
#define getUIPR(uipr) \
WIZCHIP_READ_BUF(UIPR,uipr,6)
+*/
+#define getUIPR(uipr) \
+ WIZCHIP_READ_BUF(UIPR,uipr,4)
/**
* @ingroup Common_register_access_function
* @brief Get @ref UPORTR register
* @return uint16_t. Value of @ref UPORTR register.
*/
+//M20150401 : Type explict declaration
+/*
#define getUPORTR() \
((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1)))
+*/
+#define getUPORTR() \
+ (((uint16_t)WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1)))
/**
* @ingroup Common_register_access_function
@@ -1697,8 +1742,13 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @return uint16_t. Value of @ref Sn_PORT.
* @sa setSn_PORT()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_PORT(sn) \
((WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1)))
+*/
+#define getSn_PORT(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1735,7 +1785,7 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @brief Get @ref Sn_DIPR register
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes.
- * @sa SetSn_DIPR()
+ * @sa setSn_DIPR()
*/
#define getSn_DIPR(sn, dipr) \
WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4)
@@ -1759,8 +1809,13 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @return uint16_t. Value of @ref Sn_DPORT.
* @sa setSn_DPORT()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_DPORT(sn) \
((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1)))
+*/
+#define getSn_DPORT(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1781,8 +1836,13 @@ void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len);
* @return uint16_t. Value of @ref Sn_MSSR.
* @sa setSn_MSSR()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_MSSR(sn) \
((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1)))
+*/
+#define getSn_MSSR(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1881,8 +1941,13 @@ uint16_t getSn_TX_FSR(uint8_t sn);
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @return uint16_t. Value of @ref Sn_TX_RD.
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_TX_RD(sn) \
((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1)))
+*/
+#define getSn_TX_RD(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1903,8 +1968,13 @@ uint16_t getSn_TX_FSR(uint8_t sn);
* @return uint16_t. Value of @ref Sn_TX_WR.
* @sa setSn_TX_WR()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_TX_WR(sn) \
((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1)))
+*/
+#define getSn_TX_WR(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1)))
/**
@@ -1932,11 +2002,16 @@ uint16_t getSn_RX_RSR(uint8_t sn);
* @ingroup Socket_register_access_function
* @brief Get @ref Sn_RX_RD register
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
- * @regurn uint16_t. Value of @ref Sn_RX_RD.
+ * @return uint16_t. Value of @ref Sn_RX_RD.
* @sa setSn_RX_RD()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_RX_RD(sn) \
((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1)))
+*/
+#define getSn_RX_RD(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1944,9 +2019,13 @@ uint16_t getSn_RX_RSR(uint8_t sn);
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @return uint16_t. Value of @ref Sn_RX_WR.
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_RX_WR(sn) \
((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1)))
-
+*/
+#define getSn_RX_WR(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1967,8 +2046,13 @@ uint16_t getSn_RX_RSR(uint8_t sn);
* @return uint16_t. Value of @ref Sn_FRAG.
* @sa setSn_FRAG()
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_FRAG(sn) \
((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1)))
+*/
+#define getSn_FRAG(sn) \
+ (((uint16_t)WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1)))
/**
* @ingroup Socket_register_access_function
@@ -1996,21 +2080,32 @@ uint16_t getSn_RX_RSR(uint8_t sn);
// Sn_TXBUF & Sn_RXBUF IO function //
/////////////////////////////////////
/**
+ * @brief Socket_register_access_function
* @brief Gets the max buffer size of socket sn passed as parameter.
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @return uint16_t. Value of Socket n RX max buffer size.
*/
+//M20150401 : Type explict declaration
+/*
#define getSn_RxMAX(sn) \
(getSn_RXBUF_SIZE(sn) << 10)
+*/
+#define getSn_RxMAX(sn) \
+ (((uint16_t)getSn_RXBUF_SIZE(sn)) << 10)
/**
+ * @brief Socket_register_access_function
* @brief Gets the max buffer size of socket sn passed as parameters.
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @return uint16_t. Value of Socket n TX max buffer size.
*/
-//uint16_t getSn_TxMAX(uint8_t sn);
+//M20150401 : Type explict declaration
+/*
#define getSn_TxMAX(sn) \
(getSn_TXBUF_SIZE(sn) << 10)
+*/
+#define getSn_TxMAX(sn) \
+ (((uint16_t)getSn_TXBUF_SIZE(sn)) << 10)
/**
* @ingroup Basic_IO_function
@@ -2021,7 +2116,6 @@ uint16_t getSn_RX_RSR(uint8_t sn);
* and updates the Tx write pointer register.
* This function is being called by send() and sendto() function also.
*
- * @note User should read upper byte first and lower byte later to get proper value.
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @param wizdata Pointer buffer to write data
* @param len Data length
@@ -2038,7 +2132,6 @@ void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len);
* to wizdata(pointer variable) of the length of len(variable) bytes.
* This function is being called by recv() also.
*
- * @note User should read upper byte first and lower byte later to get proper value.
* @param (uint8_t)sn Socket number. It should be 0 ~ 7.
* @param wizdata Pointer buffer to read data
* @param len Data length
@@ -2055,4 +2148,8 @@ void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len);
*/
void wiz_recv_ignore(uint8_t sn, uint16_t len);
+/// @cond DOXY_APPLY_CODE
+#endif
+/// @endcond
+
#endif // _W5500_H_
diff --git a/WIZ550S2E_App/src/Ethernet/socket.c b/WIZ550S2E_App/src/Ethernet/socket.c
index e1637d3..ae93b56 100644
--- a/WIZ550S2E_App/src/Ethernet/socket.c
+++ b/WIZ550S2E_App/src/Ethernet/socket.c
@@ -6,6 +6,10 @@
//! \version 1.0.3
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2014/05/01> V1.0.3. Refer to M20140501
//! 1. Implicit type casting -> Explicit type casting.
//! 2. replace 0x01 with PACK_REMAINED in recvfrom()
@@ -51,18 +55,31 @@
//*****************************************************************************
#include "socket.h"
-#define SOCK_ANY_PORT_NUM 0xC000;
+//M20150401 : Typing Error
+//#define SOCK_ANY_PORT_NUM 0xC000;
+#define SOCK_ANY_PORT_NUM 0xC000
static uint16_t sock_any_port = SOCK_ANY_PORT_NUM;
static uint16_t sock_io_mode = 0;
static uint16_t sock_is_sending = 0;
+
static uint16_t sock_remained_size[_WIZCHIP_SOCK_NUM_] = {0,0,};
-static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,};
+
+//M20150601 : For extern decleation
+//static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,};
+uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,};
+//
#if _WIZCHIP_ == 5200
static uint16_t sock_next_rd[_WIZCHIP_SOCK_NUM_] ={0,};
#endif
+//A20150601 : For integrating with W5300
+#if _WIZCHIP_ == 5300
+ uint8_t sock_remained_byte[_WIZCHIP_SOCK_NUM_] = {0,}; // set by wiz_recv_data()
+#endif
+
+
#define CHECK_SOCKNUM() \
do{ \
if(sn > _WIZCHIP_SOCK_NUM_) return SOCKERR_SOCKNUM; \
@@ -91,6 +108,16 @@ int8_t socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
switch(protocol)
{
case Sn_MR_TCP :
+ {
+ //M20150601 : Fixed the warning - taddr will never be NULL
+ /*
+ uint8_t taddr[4];
+ getSIPR(taddr);
+ */
+ uint32_t taddr;
+ getSIPR((uint8_t*)&taddr);
+ if(taddr == 0) return SOCKERR_SOCKINIT;
+ }
case Sn_MR_UDP :
case Sn_MR_MACRAW :
break;
@@ -102,7 +129,9 @@ int8_t socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
default :
return SOCKERR_SOCKMODE;
}
- if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG;
+ //M20150601 : For SF_TCP_ALIGN & W5300
+ //if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG;
+ if((flag & 0x04) != 0) return SOCKERR_SOCKFLAG;
#if _WIZCHIP_ == 5200
if(flag & 0x10) return SOCKERR_SOCKFLAG;
#endif
@@ -112,7 +141,13 @@ int8_t socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
switch(protocol)
{
case Sn_MR_TCP:
- if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG;
+ //M20150601 : For SF_TCP_ALIGN & W5300
+ #if _WIZCHIP_ == 5300
+ if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK|SF_TCP_ALIGN))==0) return SOCKERR_SOCKFLAG;
+ #else
+ if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG;
+ #endif
+
break;
case Sn_MR_UDP:
if(flag & SF_IGMP_VER2)
@@ -131,7 +166,12 @@ int8_t socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
}
}
close(sn);
- setSn_MR(sn, (protocol | (flag & 0xF0)));
+ //M20150601
+ #if _WIZCHIP_ == 5300
+ setSn_MR(sn, ((uint16_t)(protocol | (flag & 0xF0))) | (((uint16_t)(flag & 0x02)) << 7) );
+ #else
+ setSn_MR(sn, (protocol | (flag & 0xF0)));
+ #endif
if(!port)
{
port = sock_any_port++;
@@ -140,10 +180,16 @@ int8_t socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
setSn_PORT(sn,port);
setSn_CR(sn,Sn_CR_OPEN);
while(getSn_CR(sn));
+ //A20150401 : For release the previous sock_io_mode
+ sock_io_mode &= ~(1 < sn
+ //if( ((getSn_MR(s)& 0x0F) == Sn_MR_TCP) && (getSn_TX_FSR(s) != getSn_TxMAX(s)) )
+ if( ((getSn_MR(sn)& 0x0F) == Sn_MR_TCP) && (getSn_TX_FSR(sn) != getSn_TxMAX(sn)) )
+ {
+ uint8 destip[4] = {0, 0, 0, 1};
+ // TODO
+ // You can wait for completing to sending data;
+ // wait about 1 second;
+ // if you have completed to send data, skip the code of erratum 1
+ // ex> wait_1s();
+ // if (getSn_TX_FSR(s) == getSn_TxMAX(s)) continue;
+ //
+ //M20160503 : The socket() of close() calls close() itself again. It occures a infinite loop - close()->socket()->close()->socket()-> ~
+ //socket(s,Sn_MR_UDP,0x3000,0);
+ //sendto(s,destip,1,destip,0x3000); // send the dummy data to an unknown destination(0.0.0.1).
+ setSn_MR(sn,Sn_MR_UDP);
+ setSn_PORTR(sn, 0x3000);
+ setSn_CR(sn,Sn_CR_OPEN);
+ while(getSn_CR(sn) != 0);
+ while(getSn_SR(sn) != SOCK_UDP);
+ sendto(sn,destip,1,destip,0x3000); // send the dummy data to an unknown destination(0.0.0.1).
+ };
+#endif
setSn_CR(sn,Sn_CR_CLOSE);
/* wait to process the command... */
while( getSn_CR(sn) );
/* clear all interrupt of the socket. */
setSn_IR(sn, 0xFF);
+ //A20150401 : Release the sock_io_mode of socket n.
+ sock_io_mode &= ~(1< sock_remained_size[sn]) len = sock_remained_size[sn];
+ recvsize = len;
+ if(sock_pack_info[sn] & PACK_FIFOBYTE)
+ {
+ *buf = sock_remained_byte[sn];
+ buf++;
+ sock_pack_info[sn] &= ~(PACK_FIFOBYTE);
+ recvsize -= 1;
+ sock_remained_size[sn] -= 1;
+ }
+ if(recvsize != 0)
+ {
+ wiz_recv_data(sn, buf, recvsize);
+ setSn_CR(sn,Sn_CR_RECV);
+ while(getSn_CR(sn));
+ }
+ sock_remained_size[sn] -= recvsize;
+ if(sock_remained_size[sn] != 0)
+ {
+ sock_pack_info[sn] |= PACK_REMAINED;
+ if(recvsize & 0x1) sock_pack_info[sn] |= PACK_FIFOBYTE;
+ }
+ else sock_pack_info[sn] = PACK_COMPLETED;
+ if(getSn_MR(sn) & Sn_MR_ALIGN) sock_remained_size[sn] = 0;
+ //len = recvsize;
+#else
+ if(recvsize < len) len = recvsize;
wiz_recv_data(sn, buf, len);
setSn_CR(sn,Sn_CR_RECV);
while(getSn_CR(sn));
- return len;
+#endif
+
+ //M20150409 : Explicit Type Casting
+ //return len;
+ return (int32_t)len;
}
int32_t sendto(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port)
{
uint8_t tmp = 0;
uint16_t freesize = 0;
+ uint32_t taddr;
+
CHECK_SOCKNUM();
switch(getSn_MR(sn) & 0x0F)
{
case Sn_MR_UDP:
+//A170105 #if about W5500
+#if _WIZCHIP_ != 5500
+ case Sn_MR_IPRAW:
+#endif
case Sn_MR_MACRAW:
break;
default:
@@ -363,19 +508,25 @@ int32_t sendto(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t
CHECK_SOCKDATA();
//M20140501 : For avoiding fatal error on memory align mismatched
//if(*((uint32_t*)addr) == 0) return SOCKERR_IPINVALID;
- {
- uint32_t taddr;
+ //{
+ //uint32_t taddr;
taddr = ((uint32_t)addr[0]) & 0x000000FF;
taddr = (taddr << 8) + ((uint32_t)addr[1] & 0x000000FF);
taddr = (taddr << 8) + ((uint32_t)addr[2] & 0x000000FF);
taddr = (taddr << 8) + ((uint32_t)addr[3] & 0x000000FF);
- }
+ //}
//
- if(*((uint32_t*)addr) == 0) return SOCKERR_IPINVALID;
- if(port == 0) return SOCKERR_PORTZERO;
+ //if(*((uint32_t*)addr) == 0) return SOCKERR_IPINVALID;
+ if((taddr == 0)&(getSn_MR(sn)&Sn_MR_MACRAW != Sn_MR_MACRAW)) return SOCKERR_IPINVALID;
+ if((port == 0)&(getSn_MR(sn)&Sn_MR_MACRAW != Sn_MR_MACRAW)) return SOCKERR_PORTZERO;
tmp = getSn_SR(sn);
+
+//A170105 #if about W5500
+#if _WIZCHIP_ == 5500
if(tmp != SOCK_MACRAW && tmp != SOCK_UDP) return SOCKERR_SOCKSTATUS;
-
+#else
+ if(tmp != SOCK_MACRAW && tmp != SOCK_UDP && tmp != SOCK_IPRAW) return SOCKERR_SOCKSTATUS;
+#endif
setSn_DIPR(sn,addr);
setSn_DPORT(sn,port);
freesize = getSn_TxMAX(sn);
@@ -389,18 +540,24 @@ int32_t sendto(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t
};
wiz_send_data(sn, buf, len);
- #if _WIZCHIP_ == 5200 // for W5200 ARP errata
- setSUBR(0);
+ #if _WIZCHIP_ < 5500 //M20150401 : for WIZCHIP Errata #4, #5 (ARP errata)
+ getSIPR((uint8_t*)&taddr);
+ if(taddr == 0)
+ {
+ getSUBR((uint8_t*)&taddr);
+ setSUBR((uint8_t*)"\x00\x00\x00\x00");
+ }
+ else taddr = 0;
#endif
+//A20150601 : For W5300
+#if _WIZCHIP_ == 5300
+ setSn_TX_WRSR(sn, len);
+#endif
+//
setSn_CR(sn,Sn_CR_SEND);
/* wait to process the command... */
while(getSn_CR(sn));
- #if _WIZCHIP_ == 5200 // for W5200 ARP errata
- setSUBR((uint8_t*)"\x00\x00\x00\x00");
- #endif
-
- if( (sock_io_mode & (1< 1514)
{
close(sn);
@@ -514,7 +731,9 @@ int32_t recvfrom(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16
addr[2] = head[2];
addr[3] = head[3];
sock_remained_size[sn] = head[4];
- sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5];
+ //M20150401 : For Typing Error
+ //sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5];
+ sock_remained_size[sn] = (sock_remained_size[sn] << 8) + head[5];
sock_pack_info[sn] = PACK_FIRST;
}
//
@@ -534,11 +753,23 @@ int32_t recvfrom(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16
/* wait to process the command... */
while(getSn_CR(sn)) ;
sock_remained_size[sn] -= pack_len;
- //M20140501 : replace 0x01 with PACK_REMAINED
+ //M20150601 :
//if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= 0x01;
- if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= PACK_REMAINED;
+ if(sock_remained_size[sn] != 0)
+ {
+ sock_pack_info[sn] |= PACK_REMAINED;
+ #if _WIZCHIP_ == 5300
+ if(pack_len & 0x01) sock_pack_info[sn] |= PACK_FIFOBYTE;
+ #endif
+ }
+ else sock_pack_info[sn] = PACK_COMPLETED;
+#if _WIZCHIP_ == 5300
+ pack_len = len;
+#endif
//
- return pack_len;
+ //M20150409 : Explicit Type Casting
+ //return pack_len;
+ return (int32_t)pack_len;
}
@@ -573,12 +804,15 @@ int8_t ctlsocket(uint8_t sn, ctlsock_type cstype, void* arg)
case CS_GET_INTERRUPT:
*((uint8_t*)arg) = getSn_IR(sn);
break;
+ #if _WIZCHIP_ != 5100
case CS_SET_INTMASK:
if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG;
setSn_IMR(sn,*(uint8_t*)arg);
break;
case CS_GET_INTMASK:
*((uint8_t*)arg) = getSn_IMR(sn);
+ break;
+ #endif
default:
return SOCKERR_ARG;
}
@@ -654,6 +888,7 @@ int8_t getsockopt(uint8_t sn, sockopt_type sotype, void* arg)
break;
case SO_MSS:
*(uint8_t*) arg = getSn_MSSR(sn);
+ break;
case SO_DESTIP:
getSn_DIPR(sn, (uint8_t*)arg);
break;
diff --git a/WIZ550S2E_App/src/Ethernet/socket.h b/WIZ550S2E_App/src/Ethernet/socket.h
index 414f5f0..0129adb 100644
--- a/WIZ550S2E_App/src/Ethernet/socket.h
+++ b/WIZ550S2E_App/src/Ethernet/socket.h
@@ -6,6 +6,10 @@
//! \version 1.0.2
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2014/05/01> V1.0.2. Refer to M20140501
//! 1. Modify the comment : SO_REMAINED -> PACK_REMAINED
//! 2. Add the comment as zero byte udp data reception in getsockopt().
@@ -85,14 +89,14 @@
#define SOCKET uint8_t ///< SOCKET type define for legacy driver
-#define SOCK_OK 1 ///< Result is OK about socket process.
-#define SOCK_BUSY -1 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode.
+#define SOCK_OK 1 ///< Result is OK about socket process.
+#define SOCK_BUSY 0 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode.
#define SOCK_FATAL -1000 ///< Result is fatal error about socket process.
#define SOCK_ERROR 0
#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number
#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option
-#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized
+#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized or SIPR is Zero IP address when Sn_MR_TCP
#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed.
#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation.
#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag
@@ -109,16 +113,21 @@
/*
* SOCKET FLAG
*/
-#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In \ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet
-#define SF_IGMP_VER2 (Sn_MR_MC) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2.
-#define SF_TCP_NODELAY (Sn_MR_ND) ///< In \ref Sn_MR_TCP, Use to nodelayed ack.
-#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In \ref Sn_MR_UDP, Enable multicast mode.
+#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In @ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet
+#define SF_IGMP_VER2 (Sn_MR_MC) ///< In @ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2.
+#define SF_TCP_NODELAY (Sn_MR_ND) ///< In @ref Sn_MR_TCP, Use to nodelayed ack.
+#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In @ref Sn_MR_UDP, Enable multicast mode.
#if _WIZCHIP_ == 5500
- #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In \ref Sn_MR_UDP or \ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500
- #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In \ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500
- #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In \ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500
- #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500
+ #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In @ref Sn_MR_UDP or @ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500
+ #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In @ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500
+ #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In @ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500
+ #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In @ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500
+#endif
+
+//A201505 : For W5300
+#if _WIZCHIP_ == 5300
+ #define SF_TCP_ALIGN 0x02 ///< Valid only \ref Sn_MR_TCP and W5300, refer to \ref Sn_MR_ALIGN
#endif
#define SF_IO_NONBLOCK 0x01 ///< Socket nonblock io mode. It used parameter in \ref socket().
@@ -126,9 +135,12 @@
/*
* UDP & MACRAW Packet Infomation
*/
-#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet.
-#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received.
-#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet.
+#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet. (When W5300, This flag can be applied)
+#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received. (When W5300, This flag can be applied)
+#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet. (When W5300, This flag can be applied)
+//A20150601 : For Integrating with W5300
+#define PACK_FIFOBYTE 0x02 ///< Valid only W5300, It indicate to have read already the Sn_RX_FIFOR.
+//
/**
* @ingroup WIZnet_socket_APIs
@@ -337,7 +349,9 @@ typedef enum
SIK_RECEIVED = (1 << 2), ///< data received
SIK_TIMEOUT = (1 << 3), ///< timeout occurred
SIK_SENT = (1 << 4), ///< send ok
- SIK_ALL = 0x1F, ///< all interrupt
+ //M20150410 : Remove the comma of last member
+ //SIK_ALL = 0x1F, ///< all interrupt
+ SIK_ALL = 0x1F ///< all interrupt
}sockint_kind;
/**
@@ -352,8 +366,10 @@ typedef enum
CS_GET_MAXRXBUF, ///< get the size of socket buffer allocated in RX memory
CS_CLR_INTERRUPT, ///< clear the interrupt of socket with @ref sockint_kind
CS_GET_INTERRUPT, ///< get the socket interrupt. refer to @ref sockint_kind
- CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind
- CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind
+#if _WIZCHIP_ > 5100
+ CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind, Not supported in W5100
+ CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind, Not supported in W5100
+#endif
}ctlsock_type;
@@ -364,15 +380,15 @@ typedef enum
typedef enum
{
SO_FLAG, ///< Valid only in getsockopt(), For set flag of socket refer to flag in @ref socket().
- SO_TTL, ///< Set/Get TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() )
- SO_TOS, ///< Set/Get TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() )
- SO_MSS, ///< Set/Get MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() )
- SO_DESTIP, ///< Set/Get the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() )
- SO_DESTPORT, ///< Set/Get the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() )
+ SO_TTL, ///< Set TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() )
+ SO_TOS, ///< Set TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() )
+ SO_MSS, ///< Set MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() )
+ SO_DESTIP, ///< Set the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() )
+ SO_DESTPORT, ///< Set the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() )
#if _WIZCHIP_ != 5100
- SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode
+ SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode, Not supported in W5100
#if _WIZCHIP_ > 5200
- SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode
+ SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode, Not supported in W5100, W5200
#endif
#endif
SO_SENDBUF, ///< Valid only in getsockopt. Get the free data size of Socekt TX buffer. @ref Sn_TX_FSR, @ref getSn_TX_FSR()
diff --git a/WIZ550S2E_App/src/Ethernet/wizchip_conf.c b/WIZ550S2E_App/src/Ethernet/wizchip_conf.c
index 2917b75..c1ba3c2 100644
--- a/WIZ550S2E_App/src/Ethernet/wizchip_conf.c
+++ b/WIZ550S2E_App/src/Ethernet/wizchip_conf.c
@@ -5,8 +5,12 @@
//! \version 1.0.1
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2014/05/01> V1.0.1 Refer to M20140501
-//! 1. Explicit type casting in wizchip_bus_readbyte() & wizchip_bus_writebyte()
+//! 1. Explicit type casting in wizchip_bus_readdata() & wizchip_bus_writedata()
// Issued by Mathias ClauBen.
//! uint32_t type converts into ptrdiff_t first. And then recoverting it into uint8_t*
//! For remove the warning when pointer type size is not 32bit.
@@ -49,77 +53,101 @@
//
#include "wizchip_conf.h"
+
+/////////////
+//M20150401 : Remove ; in the default callback function such as wizchip_cris_enter(), wizchip_cs_select() and etc.
+/////////////
+
/**
* @brief Default function to enable interrupt.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_cris_enter(void) {};
+//void wizchip_cris_enter(void) {};
+void wizchip_cris_enter(void) {}
+
/**
* @brief Default function to disable interrupt.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_cris_exit(void) {};
+//void wizchip_cris_exit(void) {};
+void wizchip_cris_exit(void) {}
+
/**
* @brief Default function to select chip.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_cs_select(void) {};
+//void wizchip_cs_select(void) {};
+void wizchip_cs_select(void) {}
+
/**
* @brief Default function to deselect chip.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_cs_deselect(void) {};
+//void wizchip_cs_deselect(void) {};
+void wizchip_cs_deselect(void) {}
+
/**
* @brief Default function to read in direct or indirect interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
- //M20140501 : Explict pointer type casting
-//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *) AddrSel); };
-uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); };
+ //M20150601 : Rename the function for integrating with W5300
+//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); }
+iodata_t wizchip_bus_readdata(uint32_t AddrSel) { return * ((volatile iodata_t *)((ptrdiff_t) AddrSel)); }
+
/**
* @brief Default function to write in direct or indirect interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-
-//M20140501 : Explict pointer type casting
-//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*) AddrSel) = wb; };
-void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; };
+//M20150601 : Rename the function for integrating with W5300
+//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; }
+void wizchip_bus_writedata(uint32_t AddrSel, iodata_t wb) { *((volatile iodata_t*)((ptrdiff_t)AddrSel)) = wb; }
/**
* @brief Default function to read in SPI interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-uint8_t wizchip_spi_readbyte(void) {return 0;};
+//uint8_t wizchip_spi_readbyte(void) {return 0;};
+uint8_t wizchip_spi_readbyte(void) {return 0;}
+
/**
* @brief Default function to write in SPI interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_spi_writebyte(uint8_t wb) {};
+//void wizchip_spi_writebyte(uint8_t wb) {};
+void wizchip_spi_writebyte(uint8_t wb) {}
/**
* @brief Default function to burst read in SPI interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_spi_readburst(uint8_t* pBuf, uint16_t len) {};
+//void wizchip_spi_readburst(uint8_t* pBuf, uint16_t len) {};
+void wizchip_spi_readburst(uint8_t* pBuf, uint16_t len) {}
+
/**
* @brief Default function to burst write in SPI interface.
* @note This function help not to access wrong address. If you do not describe this function or register any functions,
* null function is called.
*/
-void wizchip_spi_writeburst(uint8_t* pBuf, uint16_t len) {};
+//void wizchip_spi_writeburst(uint8_t* pBuf, uint16_t len) {};
+void wizchip_spi_writeburst(uint8_t* pBuf, uint16_t len) {}
/**
* @\ref _WIZCHIP instance
*/
+//
+//M20150401 : For a compiler didnot support a member of structure
+// Replace the assignment of struct members with the assingment of array
+//
+/*
_WIZCHIP WIZCHIP =
{
.id = _WIZCHIP_ID_,
@@ -133,6 +161,24 @@ _WIZCHIP WIZCHIP =
// .IF.SPI._read_byte = wizchip_spi_readbyte,
// .IF.SPI._write_byte = wizchip_spi_writebyte
};
+*/
+_WIZCHIP WIZCHIP =
+ {
+ _WIZCHIP_IO_MODE_,
+ _WIZCHIP_ID_ ,
+ wizchip_cris_enter,
+ wizchip_cris_exit,
+ wizchip_cs_select,
+ wizchip_cs_deselect,
+ //M20150601 : Rename the function
+ //wizchip_bus_readbyte,
+ //wizchip_bus_writebyte
+ wizchip_bus_readdata,
+ wizchip_bus_writedata,
+// wizchip_spi_readbyte,
+// wizchip_spi_writebyte
+ };
+
static uint8_t _DNS_[4]; // DNS server ip address
static dhcp_mode _DHCP_; // DHCP mode
@@ -165,10 +211,13 @@ void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void))
}
}
-void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb))
+//M20150515 : For integrating with W5300
+//void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb))
+void reg_wizchip_bus_cbfunc(iodata_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, iodata_t wb))
{
while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_BUS_));
-
+ //M20150601 : Rename call back function for integrating with W5300
+ /*
if(!bus_rb || !bus_wb)
{
WIZCHIP.IF.BUS._read_byte = wizchip_bus_readbyte;
@@ -179,6 +228,17 @@ void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint
WIZCHIP.IF.BUS._read_byte = bus_rb;
WIZCHIP.IF.BUS._write_byte = bus_wb;
}
+ */
+ if(!bus_rb || !bus_wb)
+ {
+ WIZCHIP.IF.BUS._read_data = wizchip_bus_readdata;
+ WIZCHIP.IF.BUS._write_data = wizchip_bus_writedata;
+ }
+ else
+ {
+ WIZCHIP.IF.BUS._read_data = bus_rb;
+ WIZCHIP.IF.BUS._write_data = bus_wb;
+ }
}
void reg_wizchip_spi_cbfunc(uint8_t (*spi_rb)(void), void (*spi_wb)(uint8_t wb))
@@ -216,7 +276,9 @@ void reg_wizchip_spiburst_cbfunc(void (*spi_rb)(uint8_t* pBuf, uint16_t len), vo
int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg)
{
+#if _WIZCHIP_ == 5200 || _WIZCHIP_ == 5500
uint8_t tmp = 0;
+#endif
uint8_t* ptmp[2] = {0,0};
switch(cwtype)
{
@@ -242,7 +304,9 @@ int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg)
case CW_GET_INTRMASK:
*((intr_kind*)arg) = wizchip_getinterruptmask();
break;
- #if _WIZCHIP_ > 5100
+ //M20150601 : This can be supported by W5200, W5500
+ //#if _WIZCHIP_ > 5100
+ #if (_WIZCHIP_ == 5200 || _WIZCHIP_ == 5500)
case CW_SET_INTRTIME:
setINTLEVEL(*(uint16_t*)arg);
break;
@@ -273,6 +337,7 @@ int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg)
case CW_SET_PHYPOWMODE:
return wizphy_setphypmode(*(uint8_t*)arg);
#endif
+ #if _WIZCHIP_ == 5200 || _WIZCHIP_ == 5500
case CW_GET_PHYPOWMODE:
tmp = wizphy_getphypmode();
if((int8_t)tmp == -1) return -1;
@@ -283,6 +348,7 @@ int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg)
if((int8_t)tmp == -1) return -1;
*(uint8_t*)arg = tmp;
break;
+ #endif
default:
return -1;
}
@@ -322,10 +388,21 @@ void wizchip_sw_reset(void)
{
uint8_t gw[4], sn[4], sip[4];
uint8_t mac[6];
+//A20150601
+#if _WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_BUS_INDIR_
+ uint16_t mr = (uint16_t)getMR();
+ setMR(mr | MR_IND);
+#endif
+//
getSHAR(mac);
getGAR(gw); getSUBR(sn); getSIPR(sip);
setMR(MR_RST);
getMR(); // for delay
+//A2015051 : For indirect bus mode
+#if _WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_BUS_INDIR_
+ setMR(mr | MR_IND);
+#endif
+//
setSHAR(mac);
setGAR(gw);
setSUBR(sn);
@@ -340,18 +417,44 @@ int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize)
if(txsize)
{
tmp = 0;
+ //M20150601 : For integrating with W5300
+ #if _WIZCHIP_ == 5300
+ for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
+ {
+ if(txsize[i] >= 64) return -1; //No use 64KB even if W5300 support max 64KB memory allocation
+ tmp += txsize[i];
+ if(tmp > 128) return -1;
+ }
+ if(tmp % 8) return -1;
+ #else
for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
+ {
tmp += txsize[i];
- if(tmp > 16) return -1;
+ if(tmp > 16) return -1;
+ }
+ #endif
for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
setSn_TXBUF_SIZE(i, txsize[i]);
}
if(rxsize)
{
tmp = 0;
+ #if _WIZCHIP_ == 5300
+ for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
+ {
+ if(rxsize[i] >= 64) return -1; //No use 64KB even if W5300 support max 64KB memory allocation
+ tmp += rxsize[i];
+ if(tmp > 128) return -1;
+ }
+ if(tmp % 8) return -1;
+ #else
for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
+ {
tmp += rxsize[i];
- if(tmp > 16) return -1;
+ if(tmp > 16) return -1;
+ }
+ #endif
+
for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++)
setSn_RXBUF_SIZE(i, rxsize[i]);
}
@@ -376,6 +479,9 @@ void wizchip_clrinterrupt(intr_kind intr)
#if _WIZCHIP_ == 5100
ir |= sir;
setIR(ir);
+//A20150601 : For integrating with W5300
+#elif _WIZCHIP_ == 5300
+ setIR( ((((uint16_t)ir) << 8) | (((uint16_t)sir) & 0x00FF)) );
#else
setIR(ir);
setSIR(sir);
@@ -389,13 +495,20 @@ intr_kind wizchip_getinterrupt(void)
uint16_t ret = 0;
#if _WIZCHIP_ == 5100
ir = getIR();
- sir = ir 0x0F;
+ sir = ir & 0x0F;
+//A20150601 : For integrating with W5300
+#elif _WIZCHIP_ == 5300
+ ret = getIR();
+ ir = (uint8_t)(ret >> 8);
+ sir = (uint8_t)ret;
#else
ir = getIR();
sir = getSIR();
#endif
-#if _WIZCHIP_ < 5500
+//M20150601 : For Integrating with W5300
+//#if _WIZCHIP_ < 5500
+#if _WIZCHIP_ < 5200
ir &= ~(1<<4); // IK_WOL
#endif
#if _WIZCHIP_ == 5200
@@ -417,13 +530,13 @@ void wizchip_setinterruptmask(intr_kind intr)
imr &= ~(1 << 6);
#endif
-#if _WIZCHIP_ < 5200
- simr &= 0x0F;
-#endif
-
#if _WIZCHIP_ == 5100
+ simr &= 0x0F;
imr |= simr;
setIMR(imr);
+//A20150601 : For integrating with W5300
+#elif _WIZCHIP_ == 5300
+ setIMR( ((((uint16_t)imr) << 8) | (((uint16_t)simr) & 0x00FF)) );
#else
setIMR(imr);
setSIMR(simr);
@@ -437,7 +550,12 @@ intr_kind wizchip_getinterruptmask(void)
uint16_t ret = 0;
#if _WIZCHIP_ == 5100
imr = getIMR();
- simr = imr 0x0F;
+ simr = imr & 0x0F;
+//A20150601 : For integrating with W5300
+#elif _WIZCHIP_ == 5300
+ ret = getIMR();
+ imr = (uint8_t)(ret >> 8);
+ simr = (uint8_t)ret;
#else
imr = getIMR();
simr = getSIMR();
diff --git a/WIZ550S2E_App/src/Ethernet/wizchip_conf.h b/WIZ550S2E_App/src/Ethernet/wizchip_conf.h
index e3ac6bf..d6e4723 100644
--- a/WIZ550S2E_App/src/Ethernet/wizchip_conf.h
+++ b/WIZ550S2E_App/src/Ethernet/wizchip_conf.h
@@ -5,6 +5,10 @@
//! \version 1.0.0
//! \date 2013/10/21
//! \par Revision history
+//! <2015/02/05> Notice
+//! The version history is not updated after this point.
+//! Download the latest version directly from GitHub. Please visit the our GitHub repository for ioLibrary.
+//! >> https://github.com/Wiznet/ioLibrary_Driver
//! <2013/10/21> 1st Release
//! \author MidnightCow
//! \copyright
@@ -53,10 +57,12 @@
#include
/**
* @brief Select WIZCHIP.
- * @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n
+ * @todo You should select one, \b 5100, \b 5200, \b 5300, \b 5500 or etc. \n\n
* ex> #define \_WIZCHIP_ 5500
*/
-#define _WIZCHIP_ 5500 // 5100, 5200, 5500
+#ifndef _WIZCHIP_
+#define _WIZCHIP_ 5500 // 5100, 5200, 5300, 5500
+#endif
#define _WIZCHIP_IO_MODE_NONE_ 0x0000
#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */
@@ -79,19 +85,27 @@
* @brief Define interface mode.
* @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
*/
-
// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_
// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
+//A20150401 : Indclude W5100.h file
+ #include "W5100/w5100.h"
+
#elif (_WIZCHIP_ == 5200)
#define _WIZCHIP_ID_ "W5200\0"
/**
* @brief Define interface mode.
* @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
*/
+#ifndef _WIZCHIP_IO_MODE_
// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_
+#endif
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
#include "W5200/w5200.h"
#elif (_WIZCHIP_ == 5500)
#define _WIZCHIP_ID_ "W5500\0"
@@ -109,10 +123,42 @@
* ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_
*
*/
+#ifndef _WIZCHIP_IO_MODE_
//#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_
#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_
+#endif
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
#include "W5500/w5500.h"
-#else
+#elif ( _WIZCHIP_ == 5300)
+ #define _WIZCHIP_ID_ "W5300\0"
+/**
+ * @brief Define interface mode.
+ * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
+ */
+#ifndef _WIZCHIP_IO_MODE_
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
+#endif
+
+//A20150601 : Define the unit and bus width of IO DATA.
+ /**
+ * @brief Select the data width 8 or 16 bits.
+ * @todo you should select the bus width. Select one of 8 or 16.
+ */
+ #ifndef _WIZCHIP_IO_BUS_WIDTH_
+ #define _WIZCHIP_IO_BUS_WIDTH_ 8 // 16
+ #endif
+ #if _WIZCHIP_IO_BUS_WIDTH_ == 8
+ typedef uint8_t iodata_t;
+ #elif _WIZCHIP_IO_BUS_WIDTH_ == 16
+ typedef uint16_t iodata_t;
+ #else
+ #error "Unknown _WIZCHIP_IO_BUS_WIDTH_. It should be 8 or 16."
+ #endif
+//
+ #include "W5300/w5300.h"
+#else
#error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!"
#endif
@@ -126,9 +172,13 @@
* @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n
* ex> #define \_WIZCHIP_IO_BASE_ 0x00008000
*/
-#define _WIZCHIP_IO_BASE_ 0x00000000 //
+#ifndef _WIZCHIP_IO_BASE_
+#define _WIZCHIP_IO_BASE_ 0x00000000 // 0x8000
+#endif
-#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS
+//M20150401 : Typing Error
+//#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS
+#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_
#ifndef _WIZCHIP_IO_BASE_
#error "You should be define _WIZCHIP_IO_BASE to fit your system memory map."
#endif
@@ -161,7 +211,7 @@ typedef struct __WIZCHIP
void (*_exit) (void); ///< critial section exit
}CRIS;
/**
- * The set of @ref\_WIZCHIP_ select control callback func.
+ * The set of @ref \_WIZCHIP_ select control callback func.
*/
struct _CS
{
@@ -175,12 +225,19 @@ typedef struct __WIZCHIP
{
/**
* For BUS interface IO
- */
+ */
+ //M20156501 : Modify the function name for integrating with W5300
+ //struct
+ //{
+ // uint8_t (*_read_byte) (uint32_t AddrSel);
+ // void (*_write_byte) (uint32_t AddrSel, uint8_t wb);
+ //}BUS;
struct
{
- uint8_t (*_read_byte) (uint32_t AddrSel);
- void (*_write_byte) (uint32_t AddrSel, uint8_t wb);
+ iodata_t (*_read_data) (uint32_t AddrSel);
+ void (*_write_data) (uint32_t AddrSel, iodata_t wb);
}BUS;
+
/**
* For SPI interface IO
*/
@@ -189,7 +246,7 @@ typedef struct __WIZCHIP
uint8_t (*_read_byte) (void);
void (*_write_byte) (uint8_t wb);
void (*_read_burst) (uint8_t* pBuf, uint16_t len);
- void (*_write_burst) (uint8_t* pBuf, uint16_t len);
+ void (*_write_burst) (uint8_t* pBuf, uint16_t len);
}SPI;
// To be added
//
@@ -214,15 +271,19 @@ typedef enum
CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt.
CW_GET_ID, ///< Gets WIZCHIP name.
-#if _WIZCHIP_ == 5500
- CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5000
+//D20150601 : For no modification your application code
+//#if _WIZCHIP_ == 5500
+ CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5500
CW_SET_PHYCONF, ///< When PHY configured by internal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000
- CW_GET_PHYCONF, ///< Get PHY operation mode in internal register. Valid Only W5000
- CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5000
- CW_SET_PHYPOWMODE, ///< Set PHY power mode as normal and down when PHYSTATUS.OPMD == 1. Valid Only W5000
-#endif
- CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal
- CW_GET_PHYLINK ///< Get PHY Link status
+ CW_GET_PHYCONF, ///< Get PHY operation mode in internal register. Valid Only W5500
+ CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5500
+ CW_SET_PHYPOWMODE, ///< Set PHY power mode as normal and down when PHYSTATUS.OPMD == 1. Valid Only W5500
+//#endif
+//D20150601 : For no modification your application code
+//#if _WIZCHIP_ == 5200 || _WIZCHIP_ == 5500
+ CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal, Valid Only W5100, W5200
+ CW_GET_PHYLINK ///< Get PHY Link status, Valid Only W5100, W5200
+//#endif
}ctlwizchip_type;
/**
@@ -247,8 +308,10 @@ typedef enum
*/
typedef enum
{
-#if _WIZCHIP_ > 5200
+#if _WIZCHIP_ == 5500
IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500.
+#elif _WIZCHIP_ == 5300
+ IK_FMTU = (1 << 4), ///< Received a ICMP message (Fragment MTU)
#endif
IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected
@@ -385,7 +448,9 @@ void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void));
*or register your functions.
*@note If you do not describe or register, null function is called.
*/
-void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb));
+//M20150601 : For integrating with W5300
+//void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb));
+void reg_wizchip_bus_cbfunc(iodata_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, iodata_t wb));
/**
*@brief Registers call back function for SPI interface.
@@ -543,17 +608,17 @@ netmode_type wizchip_getnetmode(void);
/**
* @ingroup extra_functions
- * @brief Set retry time value(@ref RTR) and retry count(@ref RCR).
- * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission.
- * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout.
+ * @brief Set retry time value(@ref _RTR_) and retry count(@ref _RCR_).
+ * @details @ref _RTR_ configures the retransmission timeout period and @ref _RCR_ configures the number of time of retransmission.
+ * @param nettime @ref _RTR_ value and @ref _RCR_ value. Refer to @ref wiz_NetTimeout.
*/
void wizchip_settimeout(wiz_NetTimeout* nettime);
/**
* @ingroup extra_functions
- * @brief Get retry time value(@ref RTR) and retry count(@ref RCR).
- * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission.
- * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout.
+ * @brief Get retry time value(@ref _RTR_) and retry count(@ref _RCR_).
+ * @details @ref _RTR_ configures the retransmission timeout period and @ref _RCR_ configures the number of time of retransmission.
+ * @param nettime @ref _RTR_ value and @ref _RCR_ value. Refer to @ref wiz_NetTimeout.
*/
void wizchip_gettimeout(wiz_NetTimeout* nettime);
diff --git a/WIZ550S2E_App/src/Internet/DHCP/dhcp.c b/WIZ550S2E_App/src/Internet/DHCP/dhcp.c
index aa7732f..e583747 100644
--- a/WIZ550S2E_App/src/Internet/DHCP/dhcp.c
+++ b/WIZ550S2E_App/src/Internet/DHCP/dhcp.c
@@ -51,9 +51,6 @@
#include "socket.h"
#include "dhcp.h"
-#if 1 // 2014.05.30 sskim
-#include "ConfigData.h"
-#endif
/* If you want to display debug & procssing message, Define _DHCP_DEBUG_ in dhcp.h */
@@ -382,16 +379,10 @@ void send_DHCP_DISCOVER(void)
pDHCPMSG->OPT[k++] = 0; // fill zero length of hostname
for(i = 0 ; HOST_NAME[i] != 0; i++)
pDHCPMSG->OPT[k++] = HOST_NAME[i];
-#if 0 // 2014.05.29 sskim
pDHCPMSG->OPT[k++] = DHCP_CHADDR[3];
pDHCPMSG->OPT[k++] = DHCP_CHADDR[4];
pDHCPMSG->OPT[k++] = DHCP_CHADDR[5];
pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname
-#else
- sprintf((char *)(pDHCPMSG->OPT + k), "%02X%02X%02X", DHCP_CHADDR[3], DHCP_CHADDR[4], DHCP_CHADDR[5]);
- k += 6;
- pDHCPMSG->OPT[k - (i+6+1)] = i+6; // length of hostname
-#endif
pDHCPMSG->OPT[k++] = dhcpParamRequest;
pDHCPMSG->OPT[k++] = 0x06; // length of request
@@ -487,17 +478,11 @@ void send_DHCP_REQUEST(void)
pDHCPMSG->OPT[k++] = 0; // length of hostname
for(i = 0 ; HOST_NAME[i] != 0; i++)
pDHCPMSG->OPT[k++] = HOST_NAME[i];
-#if 0 // 2014.05.29 sskim
pDHCPMSG->OPT[k++] = DHCP_CHADDR[3];
pDHCPMSG->OPT[k++] = DHCP_CHADDR[4];
pDHCPMSG->OPT[k++] = DHCP_CHADDR[5];
pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname
-#else
- sprintf((char *)(pDHCPMSG->OPT + k), "%02X%02X%02X", DHCP_CHADDR[3], DHCP_CHADDR[4], DHCP_CHADDR[5]);
- k += 6;
- pDHCPMSG->OPT[k - (i+6+1)] = i+6; // length of hostname
-#endif
-
+
pDHCPMSG->OPT[k++] = dhcpParamRequest;
pDHCPMSG->OPT[k++] = 0x08;
pDHCPMSG->OPT[k++] = subnetMask;
@@ -589,7 +574,7 @@ int8_t parseDHCPMSG(void)
uint8_t * p;
uint8_t * e;
- uint8_t type = 0;
+ uint8_t type;
uint8_t opt_len;
if((len = getSn_RX_RSR(DHCP_SOCKET)) > 0)
@@ -659,6 +644,9 @@ int8_t parseDHCPMSG(void)
dhcp_lease_time = (dhcp_lease_time << 8) + *p++;
dhcp_lease_time = (dhcp_lease_time << 8) + *p++;
dhcp_lease_time = (dhcp_lease_time << 8) + *p++;
+ #ifdef _DHCP_DEBUG_
+ dhcp_lease_time = 10;
+ #endif
break;
case dhcpServerIdentifier :
p++;
@@ -907,7 +895,6 @@ void DHCP_init(uint8_t s, uint8_t * buf)
{
uint8_t zeroip[4] = {0,0,0,0};
getSHAR(DHCP_CHADDR);
-#if 0 // 2014.05.30 sskim
if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00)
{
// assing temporary mac address, you should be set SHAR before call this function.
@@ -919,20 +906,6 @@ void DHCP_init(uint8_t s, uint8_t * buf)
DHCP_CHADDR[5] = 0x00;
setSHAR(DHCP_CHADDR);
}
-#else
- if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00)
- {
- S2E_Packet *value = get_S2E_Packet_pointer();
- // assing temporary mac address, you should be set SHAR before call this function.
- DHCP_CHADDR[0] = value->network_info_common.mac[0];
- DHCP_CHADDR[1] = value->network_info_common.mac[1];
- DHCP_CHADDR[2] = value->network_info_common.mac[2];
- DHCP_CHADDR[3] = value->network_info_common.mac[3];
- DHCP_CHADDR[4] = value->network_info_common.mac[4];
- DHCP_CHADDR[5] = value->network_info_common.mac[5];
- setSHAR(DHCP_CHADDR);
- }
-#endif
DHCP_SOCKET = s; // SOCK_DHCP
pDHCPMSG = (RIP_MSG*)buf;
diff --git a/WIZ550S2E_App/src/Internet/DNS/dns.c b/WIZ550S2E_App/src/Internet/DNS/dns.c
index ace78b2..d4e5806 100644
--- a/WIZ550S2E_App/src/Internet/DNS/dns.c
+++ b/WIZ550S2E_App/src/Internet/DNS/dns.c
@@ -352,7 +352,7 @@ int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns)
if (tmp & 0x0100) pdhdr->rd = 1;
if (tmp & 0x0080) pdhdr->ra = 1;
- pdhdr->rcode = tmp & 0x0f;
+ pdhdr->rcode = tmp & 0xf;
pdhdr->qdcount = get16(&msg[4]);
pdhdr->ancount = get16(&msg[6]);
pdhdr->nscount = get16(&msg[8]);
@@ -366,6 +366,9 @@ int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns)
for (i = 0; i < pdhdr->qdcount; i++)
{
cp = dns_question(msg, cp);
+ #ifdef _DNS_DEUBG_
+ printf("MAX_DOMAIN_NAME is too small, it should be redfine in dns.h"
+ #endif
if(!cp) return -1;
}
@@ -373,6 +376,9 @@ int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns)
for (i = 0; i < pdhdr->ancount; i++)
{
cp = dns_answer(msg, cp, ip_from_dns);
+ #ifdef _DNS_DEUBG_
+ printf("MAX_DOMAIN_NAME is too small, it should be redfine in dns.h"
+ #endif
if(!cp) return -1;
}
@@ -495,66 +501,52 @@ void DNS_init(uint8_t s, uint8_t * buf)
/* DNS CLIENT RUN */
int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns)
{
- int8_t ret = 0;
+ int8_t ret;
struct dhdr dhp;
uint8_t ip[4];
uint16_t len, port;
int8_t ret_check_timeout;
- uint8_t tmp;
- // Socket open
- if(getSn_SR(DNS_SOCKET) == SOCK_CLOSED) {
- socket(DNS_SOCKET, Sn_MR_UDP, 7777, SF_IO_NONBLOCK);
+ // Socket open
+ socket(DNS_SOCKET, Sn_MR_UDP, 0, 0);
#ifdef _DNS_DEBUG_
- printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
- printf("> Domain : %s\r\n", name);
+ printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
#endif
+
+ len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE);
+ sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
- len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE);
- sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
- }
-
- tmp = getSn_IR(DNS_SOCKET);
- if(tmp & Sn_IR_SENDOK)
- {
- setSn_IR(DNS_SOCKET, Sn_IR_SENDOK);
- }
- else if(tmp & Sn_IR_TIMEOUT)
- {
- setSn_IR(DNS_SOCKET, Sn_IR_TIMEOUT);
- }
-
- if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0)
+ while (1)
{
- if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE;
- len = recvfrom(DNS_SOCKET, pDNSMSG, len, ip, &port);
-#ifdef _DNS_DEBUG_
- printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len);
-#endif
- ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns);
- if(ret == 1) {
- close(DNS_SOCKET);
+ if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0)
+ {
+ if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE;
+ len = recvfrom(DNS_SOCKET, pDNSMSG, len, ip, &port);
+ #ifdef _DNS_DEBUG_
+ printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len);
+ #endif
+ ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns);
+ break;
}
- }
- // Check Timeout
- ret_check_timeout = check_DNS_timeout();
- if (ret_check_timeout < 0) {
+ // Check Timeout
+ ret_check_timeout = check_DNS_timeout();
+ if (ret_check_timeout < 0) {
#ifdef _DNS_DEBUG_
- printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
+ printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
#endif
- ret = -1; // timeout occurred
- close(DNS_SOCKET);
- }
- else if (ret_check_timeout == 0) {
+ return 0; // timeout occurred
+ }
+ else if (ret_check_timeout == 0) {
#ifdef _DNS_DEBUG_
- printf("> DNS Timeout\r\n");
+ printf("> DNS Timeout\r\n");
#endif
- sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
+ sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
+ }
}
-
+ close(DNS_SOCKET);
// Return value
// 0 > : failed / 1 - success
return ret;
diff --git a/WIZ550S2E_App/src/Internet/DNS/dns.h b/WIZ550S2E_App/src/Internet/DNS/dns.h
index 9e6fbb2..023e37d 100644
--- a/WIZ550S2E_App/src/Internet/DNS/dns.h
+++ b/WIZ550S2E_App/src/Internet/DNS/dns.h
@@ -64,7 +64,7 @@
* @todo SHOULD BE defined it equal as or greater than your Domain name lenght + null character(1)
* @note SHOULD BE careful to stack overflow because it is allocated 1.5 times as MAX_DOMAIN_NAME in stack.
*/
-#define MAX_DOMAIN_NAME 32 // for example "www.google.com"
+#define MAX_DOMAIN_NAME 16 // for example "www.google.com"
#define MAX_DNS_RETRY 2 ///< Requery Count
#define DNS_WAIT_TIME 3 ///< Wait response time. unit 1s.
diff --git a/WIZ550S2E_App/src/Internet/FTPClient/ftpc.c b/WIZ550S2E_App/src/Internet/FTPClient/ftpc.c
new file mode 100644
index 0000000..baef916
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPClient/ftpc.c
@@ -0,0 +1,584 @@
+#include "ftpc.h"
+
+un_l2cval remote_ip;
+uint16_t remote_port;
+un_l2cval local_ip;
+uint16_t local_port;
+uint8_t connect_state_control_ftpc = 0;
+uint8_t connect_state_data_ftpc = 0;
+uint8_t gModeActivePassiveflag = 0;
+uint8_t FTP_destip[4] = {192, 168, 10, 230}; // For FTP client examples; destination network info
+uint16_t FTP_destport = 21; // For FTP client examples; destination network info
+uint8_t gMenuStart = 0;
+uint8_t gDataSockReady = 0;
+uint8_t gDataPutGetStart = 0;
+static uint8_t gMsgBuf[20]={0,};
+
+struct ftpc ftpc;
+struct Command Command;
+
+void ftpc_init(uint8_t * src_ip)
+{
+ ftpc.dsock_mode = ACTIVE_MODE;
+
+ local_ip.cVal[0] = src_ip[0];
+ local_ip.cVal[1] = src_ip[1];
+ local_ip.cVal[2] = src_ip[2];
+ local_ip.cVal[3] = src_ip[3];
+ local_port = 35000;
+ strcpy(ftpc.workingdir, "/");
+ socket(CTRL_SOCK, Sn_MR_TCP, FTP_destport, 0x0);
+}
+uint8_t ftpc_run(uint8_t * dbuf)
+{
+#ifndef Need_UARTGetCharBlocking_func
+ uint16_t size = 0;
+ long ret = 0;
+ uint32_t send_byte, recv_byte;
+ uint32_t blocklen;
+ uint32_t remain_filesize;
+ uint32_t remain_datasize;
+ uint8_t msg_c;
+ uint8_t dat[50]={0,};
+ uint32_t totalSize = 0, availableSize = 0;
+
+ switch(getSn_SR(CTRL_SOCK))
+ {
+ case SOCK_ESTABLISHED :
+ if(!connect_state_control_ftpc){
+ printf("%d:FTP Connected\r\n", CTRL_SOCK);
+ strcpy(ftpc.workingdir, "/");
+ connect_state_control_ftpc = 1;
+ }
+ if(gMenuStart){
+ gMenuStart = 0;
+ printf("\r\n----------------------------------------\r\n");
+ printf("Press menu key\r\n");
+ printf("----------------------------------------\r\n");
+ printf("1> View FTP Server Directory\r\n");
+ printf("2> View My Directory\r\n");
+ printf("3> Sets the type of file to be transferred. Current state : %s\r\n", (ftpc.type==ASCII_TYPE)?"Ascii":"Binary");
+ printf("4> Sets Data Connection. Current state : %s\r\n", (ftpc.dsock_mode==ACTIVE_MODE)?"Active":"Passive");
+ printf("5> Put File to Server\r\n");
+ printf("6> Get File from Server\r\n");
+#if defined(F_FILESYSTEM)
+ printf("7> Delete My File\r\n");
+#endif
+ printf("----------------------------------------\r\n");
+ while(1){
+ msg_c=ftp_getc();
+ if(msg_c=='1'){
+ if(ftpc.dsock_mode==PASSIVE_MODE){
+ sprintf(dat,"PASV\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_dir;
+ break;
+ }
+ else{
+ wiz_NetInfo gWIZNETINFO;
+ ctlnetwork(CN_GET_NETINFO, (void*) &gWIZNETINFO);
+ sprintf(dat,"PORT %d,%d,%d,%d,%d,%d\r\n", gWIZNETINFO.ip[0], gWIZNETINFO.ip[1], gWIZNETINFO.ip[2], gWIZNETINFO.ip[3], (uint8_t)(local_port>>8), (uint8_t)(local_port&0x00ff));
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_dir;
+
+ gModeActivePassiveflag = 1;
+ break;
+ }
+ break;
+ }
+ else if(msg_c=='5'){
+ if(ftpc.dsock_mode==PASSIVE_MODE){
+ sprintf(dat,"PASV\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_put;
+ break;
+ }
+ else{
+ wiz_NetInfo gWIZNETINFO;
+ ctlnetwork(CN_GET_NETINFO, (void*) &gWIZNETINFO);
+ sprintf(dat,"PORT %d,%d,%d,%d,%d,%d\r\n", gWIZNETINFO.ip[0], gWIZNETINFO.ip[1], gWIZNETINFO.ip[2], gWIZNETINFO.ip[3], (uint8_t)(local_port>>8), (uint8_t)(local_port&0x00ff));
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_put;
+
+ gModeActivePassiveflag = 1;
+ break;
+ }
+ }
+ else if(msg_c=='6'){
+ if(ftpc.dsock_mode==PASSIVE_MODE){
+ sprintf(dat,"PASV\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_get;
+ break;
+ }
+ else{
+ wiz_NetInfo gWIZNETINFO;
+ ctlnetwork(CN_GET_NETINFO, (void*) &gWIZNETINFO);
+ sprintf(dat,"PORT %d,%d,%d,%d,%d,%d\r\n", gWIZNETINFO.ip[0], gWIZNETINFO.ip[1], gWIZNETINFO.ip[2], gWIZNETINFO.ip[3], (uint8_t)(local_port>>8), (uint8_t)(local_port&0x00ff));
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ Command.First = f_get;
+
+ gModeActivePassiveflag = 1;
+ break;
+ }
+ }
+ else if(msg_c=='2'){
+#if defined(F_FILESYSTEM)
+ scan_files(ftpc.workingdir, dbuf, (int *)&size);
+ printf("\r\n%s\r\n", dbuf);
+#else
+ if (strncmp(ftpc.workingdir, "/$Recycle.Bin", sizeof("/$Recycle.Bin")) != 0)
+ size = sprintf(dbuf, "drwxr-xr-x 1 ftp ftp 0 Dec 31 2014 $Recycle.Bin\r\n-rwxr-xr-x 1 ftp ftp 512 Dec 31 2014 test.txt\r\n");
+ printf("\r\n%s\r\n", dbuf);
+#endif
+ gMenuStart = 1;
+ break;
+ }
+ else if(msg_c=='3'){
+ printf("1> ASCII\r\n");
+ printf("2> BINARY\r\n");
+ while(1){
+ msg_c=ftp_getc();
+ if(msg_c=='1'){
+ sprintf(dat,"TYPE %c\r\n", TransferAscii);
+ ftpc.type = ASCII_TYPE;
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ }
+ else if(msg_c=='2'){
+ sprintf(dat,"TYPE %c\r\n", TransferBinary);
+ ftpc.type = IMAGE_TYPE;
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ }
+ else{
+ printf("\r\nRetry...\r\n");
+ }
+ }
+ break;
+ }
+ else if(msg_c=='4'){
+ printf("1> ACTIVE\r\n");
+ printf("2> PASSIVE\r\n");
+ while(1){
+ msg_c=ftp_getc();
+ if(msg_c=='1'){
+ ftpc.dsock_mode=ACTIVE_MODE;
+ break;
+ }
+ else if(msg_c=='2'){
+ ftpc.dsock_mode=PASSIVE_MODE;
+ break;
+ }
+ else{
+ printf("\r\nRetry...\r\n");
+ }
+ }
+ gMenuStart = 1;
+ break;
+ }
+#if defined(F_FILESYSTEM)
+ else if(msg_c=='7'){
+ printf(">del filename?");
+ sprintf(ftpc.filename, "/%s\r\n", User_Keyboard_MSG());
+ if (f_unlink((const char *)ftpc.filename) != 0){
+ printf("\r\nCould not delete.\r\n");
+ }
+ else{
+ printf("\r\nDeleted.\r\n");
+ }
+ gMenuStart = 1;
+ break;
+ }
+#endif
+ else{
+ printf("\r\nRetry...\r\n");
+ }
+ }
+ }
+ if(gDataSockReady){
+ gDataSockReady = 0;
+ switch(Command.First){
+ case f_dir:
+ sprintf(dat,"LIST\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ case f_put:
+ printf(">put file name?");
+ sprintf(dat,"STOR %s\r\n", User_Keyboard_MSG());
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ case f_get:
+ printf(">get file name?");
+ sprintf(dat,"RETR %s\r\n", User_Keyboard_MSG());
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ default:
+ printf("Command.First = default\r\n");
+ break;
+ }
+ }
+ if((size = getSn_RX_RSR(CTRL_SOCK)) > 0){ // Don't need to check SOCKERR_BUSY because it doesn't not occur.
+ memset(dbuf, 0, _MAX_SS);
+ if(size > _MAX_SS) size = _MAX_SS - 1;
+ ret = recv(CTRL_SOCK,dbuf,size);
+ dbuf[ret] = '\0';
+ if(ret != size)
+ {
+ if(ret==SOCK_BUSY) return 0;
+ if(ret < 0){
+ printf("%d:recv() error:%ld\r\n",CTRL_SOCK,ret);
+ close(CTRL_SOCK);
+ return ret;
+ }
+ }
+ printf("Rcvd Command: %s\r\n", dbuf);
+ proc_ftpc((char *)dbuf);
+ }
+ break;
+ case SOCK_CLOSE_WAIT :
+ printf("%d:CloseWait\r\n",CTRL_SOCK);
+ if((ret=disconnect(CTRL_SOCK)) != SOCK_OK) return ret;
+ printf("%d:Closed\r\n",CTRL_SOCK);
+ break;
+ case SOCK_CLOSED :
+ printf("%d:FTPStart\r\n",CTRL_SOCK);
+ if((ret=socket(CTRL_SOCK, Sn_MR_TCP, FTP_destport, 0x0)) != CTRL_SOCK){
+ printf("%d:socket() error:%ld\r\n", CTRL_SOCK, ret);
+ close(CTRL_SOCK);
+ return ret;
+ }
+ break;
+ case SOCK_INIT :
+ printf("%d:Opened\r\n",CTRL_SOCK);
+ if((ret = connect(CTRL_SOCK, FTP_destip, FTP_destport)) != SOCK_OK){
+ printf("%d:Connect error\r\n",CTRL_SOCK);
+ return ret;
+ }
+ connect_state_control_ftpc = 0;
+ printf("%d:Connectting...\r\n",CTRL_SOCK);
+ break;
+ default :
+ break;
+ }
+
+ switch(getSn_SR(DATA_SOCK)){
+ case SOCK_ESTABLISHED :
+ if(!connect_state_data_ftpc){
+ printf("%d:FTP Data socket Connected\r\n", DATA_SOCK);
+ connect_state_data_ftpc = 1;
+ }
+ if(gDataPutGetStart){
+ switch(Command.Second){
+ case s_dir:
+ printf("dir waiting...\r\n");
+ if((size = getSn_RX_RSR(DATA_SOCK)) > 0){ // Don't need to check SOCKERR_BUSY because it doesn't not occur.
+ printf("ok\r\n");
+ memset(dbuf, 0, _MAX_SS);
+ if(size > _MAX_SS) size = _MAX_SS - 1;
+ ret = recv(DATA_SOCK,dbuf,size);
+ dbuf[ret] = '\0';
+ if(ret != size){
+ if(ret==SOCK_BUSY) return 0;
+ if(ret < 0){
+ printf("%d:recv() error:%ld\r\n",CTRL_SOCK,ret);
+ close(DATA_SOCK);
+ return ret;
+ }
+ }
+ printf("Rcvd Data:\n\r%s\n\r", dbuf);
+ gDataPutGetStart = 0;
+ Command.Second = s_nocmd;
+ }
+ break;
+ case s_put:
+ printf("put waiting...\r\n");
+ if(strlen(ftpc.workingdir) == 1)
+ sprintf(ftpc.filename, "/%s", (uint8_t *)gMsgBuf);
+ else
+ sprintf(ftpc.filename, "%s/%s", ftpc.workingdir, (uint8_t *)gMsgBuf);
+#if defined(F_FILESYSTEM)
+ ftpc.fr = f_open(&(ftpc.fil), (const char *)ftpc.filename, FA_READ);
+ if(ftpc.fr == FR_OK){
+ remain_filesize = ftpc.fil.fsize;
+ printf("f_open return FR_OK\r\n");
+ do{
+ memset(dbuf, 0, _MAX_SS);
+ if(remain_filesize > _MAX_SS)
+ send_byte = _MAX_SS;
+ else
+ send_byte = remain_filesize;
+ ftpc.fr = f_read(&(ftpc.fil), (void *)dbuf, send_byte , (UINT *)&blocklen);
+ if(ftpc.fr != FR_OK){
+ break;
+ }
+ printf("#");
+ send(DATA_SOCK, dbuf, blocklen);
+ remain_filesize -= blocklen;
+ }while(remain_filesize != 0);
+ printf("\r\nFile read finished\r\n");
+ ftpc.fr = f_close(&(ftpc.fil));
+ }
+ else{
+ printf("File Open Error: %d\r\n", ftpc.fr);
+ ftpc.fr = f_close(&(ftpc.fil));
+ }
+#else
+ remain_filesize = strlen(ftpc.filename);
+ do{
+ memset(dbuf, 0, _MAX_SS);
+ blocklen = sprintf(dbuf, "%s", ftpc.filename);
+ printf("########## dbuf:%s\r\n", dbuf);
+ send(DATA_SOCK, dbuf, blocklen);
+ remain_filesize -= blocklen;
+ }while(remain_filesize != 0);
+#endif
+ gDataPutGetStart = 0;
+ Command.Second = s_nocmd;
+ disconnect(DATA_SOCK);
+ break;
+ case s_get:
+ printf("get waiting...\r\n");
+ if(strlen(ftpc.workingdir) == 1)
+ sprintf(ftpc.filename, "/%s", (uint8_t *)gMsgBuf);
+ else
+ sprintf(ftpc.filename, "%s/%s", ftpc.workingdir, (uint8_t *)gMsgBuf);
+#if defined(F_FILESYSTEM)
+ ftpc.fr = f_open(&(ftpc.fil), (const char *)ftpc.filename, FA_CREATE_ALWAYS | FA_WRITE);
+ if(ftpc.fr == FR_OK){
+ printf("f_open return FR_OK\r\n");
+ while(1){
+ if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
+ while(1){
+ memset(dbuf, 0, _MAX_SS);
+ if(remain_datasize > _MAX_SS) recv_byte = _MAX_SS;
+ else recv_byte = remain_datasize;
+ ret = recv(DATA_SOCK, dbuf, recv_byte);
+ ftpc.fr = f_write(&(ftpc.fil), (const void *)dbuf, (UINT)ret, (UINT *)&blocklen);
+ remain_datasize -= blocklen;
+ if(ftpc.fr != FR_OK){
+ printf("f_write failed\r\n");
+ break;
+ }
+ if(remain_datasize <= 0) break;
+ }
+ if(ftpc.fr != FR_OK){
+ printf("f_write failed\r\n");
+ break;
+ }
+ printf("#");
+ }
+ else{
+ if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED) break;
+ }
+ }
+ printf("\r\nFile write finished\r\n");
+ ftpc.fr = f_close(&(ftpc.fil));
+ gDataPutGetStart = 0;
+ }else{
+ printf("File Open Error: %d\r\n", ftpc.fr);
+ }
+#else
+ while(1){
+ if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
+ while(1){
+ memset(dbuf, 0, _MAX_SS);
+ if(remain_datasize > _MAX_SS)
+ recv_byte = _MAX_SS;
+ else
+ recv_byte = remain_datasize;
+ ret = recv(DATA_SOCK, dbuf, recv_byte);
+ printf("########## dbuf:%s\r\n", dbuf);
+ remain_datasize -= ret;
+ if(remain_datasize <= 0)
+ break;
+ }
+ }else{
+ if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED)
+ break;
+ }
+ }
+ gDataPutGetStart = 0;
+ Command.Second = s_nocmd;
+#endif
+ break;
+ default:
+ printf("Command.Second = default\r\n");
+ break;
+ }
+ }
+ break;
+ case SOCK_CLOSE_WAIT :
+ printf("%d:CloseWait\r\n",DATA_SOCK);
+ if((ret=disconnect(DATA_SOCK)) != SOCK_OK) return ret;
+ printf("%d:Closed\r\n",DATA_SOCK);
+ break;
+ case SOCK_CLOSED :
+ if(ftpc.dsock_state == DATASOCK_READY){
+ if(ftpc.dsock_mode == PASSIVE_MODE){
+ printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, local_port);
+ if((ret=socket(DATA_SOCK, Sn_MR_TCP, local_port, 0x0)) != DATA_SOCK){
+ printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
+ close(DATA_SOCK);
+ return ret;
+ }
+ local_port++;
+ if(local_port > 50000)
+ local_port = 35000;
+ }else{
+ printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, local_port);
+ if((ret=socket(DATA_SOCK, Sn_MR_TCP, local_port, 0x0)) != DATA_SOCK){
+ printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
+ close(DATA_SOCK);
+ return ret;
+ }
+ local_port++;
+ if(local_port > 50000)
+ local_port = 35000;
+ }
+ ftpc.dsock_state = DATASOCK_START;
+ }
+ break;
+
+ case SOCK_INIT :
+ printf("%d:Opened\r\n",DATA_SOCK);
+ if(ftpc.dsock_mode == ACTIVE_MODE){
+ if( (ret = listen(DATA_SOCK)) != SOCK_OK){
+ printf("%d:Listen error\r\n",DATA_SOCK);
+ return ret;
+ }
+ gDataSockReady = 1;
+ printf("%d:Listen ok\r\n",DATA_SOCK);
+ }else{
+ if((ret = connect(DATA_SOCK, remote_ip.cVal, remote_port)) != SOCK_OK){
+ printf("%d:Connect error\r\n", DATA_SOCK);
+ return ret;
+ }
+ gDataSockReady = 1;
+ }
+ connect_state_data_ftpc = 0;
+ break;
+ default :
+ break;
+ }
+#endif
+ return 0;
+}
+
+char proc_ftpc(char * buf)
+{
+ uint16_t Responses;
+ uint8_t dat[30]={0,};
+
+ Responses =(buf[0]-'0')*100+(buf[1]-'0')*10+(buf[2]-'0');
+
+ switch(Responses){
+ case R_220: /* Service ready for new user. */
+ printf("\r\nInput your User ID > ");
+ sprintf(dat,"USER %s\r\n", User_Keyboard_MSG());
+ printf("\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+
+ case R_331: /* User name okay, need password. */
+ printf("\r\nInput your Password > ");
+ sprintf(dat,"PASS %s\r\n", User_Keyboard_MSG());
+ printf("\r\n");
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ case R_230: /* User logged in, proceed */
+ printf("\r\nUser logged in, proceed\r\n");
+
+ sprintf(dat,"TYPE %c\r\n", TransferAscii);
+ ftpc.type = ASCII_TYPE;
+ send(CTRL_SOCK, (uint8_t *)dat, strlen(dat));
+ break;
+ case R_200:
+ if((ftpc.dsock_mode==ACTIVE_MODE)&&gModeActivePassiveflag){
+ ftpc.dsock_state = DATASOCK_READY;
+ gModeActivePassiveflag = 0;
+ }
+ else{
+ gMenuStart = 1;
+ }
+ break;
+ case R_150:
+ switch(Command.First){
+ case f_dir:
+ Command.First = f_nocmd;
+ Command.Second = s_dir;
+ gDataPutGetStart = 1;
+ break;
+ case f_get:
+ Command.First = f_nocmd;
+ Command.Second = s_get;
+ gDataPutGetStart = 1;
+ break;
+ case f_put:
+ Command.First = f_nocmd;
+ Command.Second = s_put;
+ gDataPutGetStart = 1;
+ break;
+ default :
+ printf("Command.First = default\r\n");
+ break;
+ }
+ break;
+ case R_226:
+ gMenuStart = 1;
+ break;
+ case R_227:
+ if (pportc(buf) == -1){
+ printf("Bad port syntax\r\n");
+ }
+ else{
+ printf("Go Open Data Sock...\r\n ");
+ ftpc.dsock_mode = PASSIVE_MODE;
+ ftpc.dsock_state = DATASOCK_READY;
+ }
+ break;
+ default:
+ printf("\r\nDefault Status = %d\r\n",(uint16_t)Responses);
+ gDataSockReady = 1;
+ break;
+ }
+ return 1;
+}
+int pportc(char * arg)
+{
+ int i;
+ char* tok=0;
+ strtok(arg,"(");
+ for (i = 0; i < 4; i++)
+ {
+ if(i==0) tok = strtok(NULL,",\r\n");
+ else tok = strtok(NULL,",");
+ remote_ip.cVal[i] = (uint8_t)atoi(tok, 10);
+ if (!tok){
+ printf("bad pport : %s\r\n", arg);
+ return -1;
+ }
+ }
+ remote_port = 0;
+ for (i = 0; i < 2; i++){
+ tok = strtok(NULL,",\r\n");
+ remote_port <<= 8;
+ remote_port += atoi(tok, 10);
+ if (!tok){
+ printf("bad pport : %s\r\n", arg);
+ return -1;
+ }
+ }
+ printf("ip : %d.%d.%d.%d, port : %d\r\n", remote_ip.cVal[0], remote_ip.cVal[1], remote_ip.cVal[2], remote_ip.cVal[3], remote_port);
+ return 0;
+}
+uint8_t* User_Keyboard_MSG()
+{
+ uint8_t i=0;
+ do{
+ gMsgBuf[i] = ftp_getc();
+ i++;
+ }while(gMsgBuf[i-1]!=0x0d);
+ gMsgBuf[i-1]=0;
+ return gMsgBuf;
+}
diff --git a/WIZ550S2E_App/src/Internet/FTPClient/ftpc.h b/WIZ550S2E_App/src/Internet/FTPClient/ftpc.h
new file mode 100644
index 0000000..124ee29
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPClient/ftpc.h
@@ -0,0 +1,119 @@
+#ifndef _FTPC_H_
+#define _FTPC_H_
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include "stdio_private.h"
+#include "socket.h"
+
+#define F_APP_FTPC
+
+/* If your target support a file system, you have to activate this feature and implement. */
+//#define F_FILESYSTEM
+
+/* Change to your Chipset Uart function, you have to activate this feature and implement.
+ * Change!! -> Board_UARTGetCharBlocking()
+ * Below is an example of a function of lpc_chip library. */
+//#define ftp_getc() Board_UARTGetCharBlocking()
+
+#ifdef F_FILESYSTEM
+#include "ff.h"
+#endif
+
+#ifndef ftp_getc()
+#define Need_UARTGetCharBlocking_func
+#else
+/* Change library
+ * Change!! -> board_api.h,
+ * Below is an example of a function of lpc_chip library. */
+#include "board_api.h"
+#endif
+
+
+#define LINELEN 100
+#ifndef F_FILESYSTEM
+#define _MAX_SS 512
+#endif
+
+#define CTRL_SOCK 2
+#define DATA_SOCK 3
+
+/* FTP Responses */
+#define R_150 150 /* File status ok; opening data conn */
+#define R_200 200 /* 'Generic' command ok */
+#define R_220 220 /* Service ready for new user. */
+#define R_226 226 /* Closing data connection. File transfer/abort successful */
+#define R_227 227 /* Entering passive mode (h1,h2,h3,h4,p1,p2) */
+#define R_230 230 /* User logged in, proceed */
+#define R_331 331 /* User name okay, need password. */
+
+#define TransferAscii 'A'
+#define TransferBinary 'I'
+
+enum ftpc_type {
+ ASCII_TYPE,
+ IMAGE_TYPE,
+};
+
+enum ftpc_datasock_state{
+ DATASOCK_IDLE,
+ DATASOCK_READY,
+ DATASOCK_START
+};
+
+enum ftpc_datasock_mode{
+ PASSIVE_MODE,
+ ACTIVE_MODE
+};
+enum CommandFirst {
+ f_nocmd,
+ f_dir,
+ f_put,
+ f_get,
+};
+enum CommandSecond {
+ s_nocmd,
+ s_dir,
+ s_put,
+ s_get,
+};
+struct Command {
+ enum CommandFirst First;
+ enum CommandSecond Second;
+};
+struct ftpc {
+ uint8_t control; /* Control stream */
+ uint8_t data; /* Data stream */
+
+ enum ftpc_type type; /* Transfer type */
+
+ enum ftpc_datasock_state dsock_state;
+ enum ftpc_datasock_mode dsock_mode;
+
+ char workingdir[LINELEN];
+ char filename[LINELEN];
+
+#ifdef F_FILESYSTEM
+ FIL fil; // FatFs File objects
+ FRESULT fr; // FatFs function common result code
+#endif
+};
+
+#ifndef un_I2cval
+typedef union _un_l2cval {
+ uint32_t lVal;
+ uint8_t cVal[4];
+}un_l2cval;
+#endif
+
+void ftpc_init(uint8_t * src_ip);
+uint8_t ftpc_run(uint8_t * dbuf);
+char proc_ftpc(char * buf);
+int pportc(char * arg);
+uint8_t* User_Keyboard_MSG();
+
+#endif // _FTPC_H_
diff --git a/WIZ550S2E_App/src/Internet/FTPClient/stdio_private.h b/WIZ550S2E_App/src/Internet/FTPClient/stdio_private.h
new file mode 100644
index 0000000..26b6d87
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPClient/stdio_private.h
@@ -0,0 +1,67 @@
+/* Copyright (c) 2002, Joerg Wunsch
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
+*/
+
+/* $Id: stdio_private.h,v 1.6 2003/01/07 22:17:24 joerg_wunsch Exp $ */
+
+#include
+#include
+
+struct __file {
+ char *buf; /* buffer pointer */
+ unsigned char unget; /* ungetc() buffer */
+ uint8_t flags; /* flags, see below */
+#define __SRD 0x0001 /* OK to read */
+#define __SWR 0x0002 /* OK to write */
+#define __SSTR 0x0004 /* this is an sprintf/snprintf string */
+#define __SPGM 0x0008 /* fmt string is in progmem */
+#define __SERR 0x0010 /* found error */
+#define __SEOF 0x0020 /* found EOF */
+#define __SUNGET 0x040 /* ungetc() happened */
+#if 0
+/* possible future extensions, will require uint16_t flags */
+#define __SRW 0x0080 /* open for reading & writing */
+#define __SLBF 0x0100 /* line buffered */
+#define __SNBF 0x0200 /* unbuffered */
+#define __SMBF 0x0400 /* buf is from malloc */
+#endif
+ int size; /* size of buffer */
+ int len; /* characters read or written so far */
+ int (*put)(char); /* function to write one char to device */
+ int (*get)(void); /* function to read one char from device */
+};
+
+/* values for PRINTF_LEVEL */
+#define PRINTF_MIN 1
+#define PRINTF_STD 2
+#define PRINTF_FLT 3
+
+/* values for SCANF_LEVEL */
+#define SCANF_MIN 1
+#define SCANF_STD 2
+#define SCANF_FLT 3
diff --git a/WIZ550S2E_App/src/Internet/FTPServer/ftpd.c b/WIZ550S2E_App/src/Internet/FTPServer/ftpd.c
new file mode 100644
index 0000000..178c116
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPServer/ftpd.c
@@ -0,0 +1,980 @@
+/*
+* Wiznet.
+* (c) Copyright 2002, Wiznet.
+*
+* Filename : ftpd.c
+* Version : 1.0
+* Programmer(s) :
+* Created : 2003/01/28
+* Description : FTP daemon. (AVR-GCC Compiler)
+*/
+
+
+#include
+#include
+#include
+#include
+#include
+#include "stdio_private.h"
+#include "socket.h"
+#include "ftpd.h"
+
+/* Command table */
+static char *commands[] = {
+ "user",
+ "acct",
+ "pass",
+ "type",
+ "list",
+ "cwd",
+ "dele",
+ "name",
+ "quit",
+ "retr",
+ "stor",
+ "port",
+ "nlst",
+ "pwd",
+ "xpwd",
+ "mkd",
+ "xmkd",
+ "xrmd",
+ "rmd ",
+ "stru",
+ "mode",
+ "syst",
+ "xmd5",
+ "xcwd",
+ "feat",
+ "pasv",
+ "size",
+ "mlsd",
+ "appe",
+ NULL
+};
+
+#if 0
+/* Response messages */
+char banner[] = "220 %s FTP version %s ready.\r\n";
+char badcmd[] = "500 Unknown command '%s'\r\n";
+char binwarn[] = "100 Warning: type is ASCII and %s appears to be binary\r\n";
+char unsupp[] = "500 Unsupported command or option\r\n";
+char givepass[] = "331 Enter PASS command\r\n";
+char logged[] = "230 Logged in\r\n";
+char typeok[] = "200 Type %s OK\r\n";
+char only8[] = "501 Only logical bytesize 8 supported\r\n";
+char deleok[] = "250 File deleted\r\n";
+char mkdok[] = "200 MKD ok\r\n";
+char delefail[] = "550 Delete failed: %s\r\n";
+char pwdmsg[] = "257 \"%s\" is current directory\r\n";
+char badtype[] = "501 Unknown type \"%s\"\r\n";
+char badport[] = "501 Bad port syntax\r\n";
+char unimp[] = "502 Command does not implemented yet.\r\n";
+char bye[] = "221 Goodbye!\r\n";
+char nodir[] = "553 Can't read directory \"%s\": %s\r\n";
+char cantopen[] = "550 Can't read file \"%s\": %s\r\n";
+char sending[] = "150 Opening data connection for %s (%d.%d.%d.%d,%d)\r\n";
+char cantmake[] = "553 Can't create \"%s\": %s\r\n";
+char writerr[] = "552 Write error: %s\r\n";
+char portok[] = "200 PORT command successful.\r\n";
+char rxok[] = "226 Transfer complete.\r\n";
+char txok[] = "226 Transfer complete.\r\n";
+char noperm[] = "550 Permission denied\r\n";
+char noconn[] = "425 Data connection reset\r\n";
+char lowmem[] = "421 System overloaded, try again later\r\n";
+char notlog[] = "530 Please log in with USER and PASS\r\n";
+char userfirst[] = "503 Login with USER first.\r\n";
+char okay[] = "200 Ok\r\n";
+char syst[] = "215 %s Type: L%d Version: %s\r\n";
+char sizefail[] = "550 File not found\r\n";
+#endif
+
+un_l2cval remote_ip;
+uint16_t remote_port;
+un_l2cval local_ip;
+uint16_t local_port;
+uint8_t connect_state_control = 0;
+uint8_t connect_state_data = 0;
+
+struct ftpd ftp;
+
+int current_year = 2014;
+int current_month = 12;
+int current_day = 31;
+int current_hour = 10;
+int current_min = 10;
+int current_sec = 30;
+
+int fsprintf(uint8_t s, const char *format, ...)
+{
+ int i;
+/*
+ char buf[LINELEN];
+ FILE f;
+ va_list ap;
+
+ f.flags = __SWR | __SSTR;
+ f.buf = buf;
+ f.size = INT_MAX;
+ va_start(ap, format);
+ i = vfprintf(&f, format, ap);
+ va_end(ap);
+ buf[f.len] = 0;
+
+ send(s, (uint8_t *)buf, strlen(buf));
+*/
+ return i;
+}
+
+void ftpd_init(uint8_t * src_ip)
+{
+ ftp.state = FTPS_NOT_LOGIN;
+ ftp.current_cmd = NO_CMD;
+ ftp.dsock_mode = ACTIVE_MODE;
+
+ local_ip.cVal[0] = src_ip[0];
+ local_ip.cVal[1] = src_ip[1];
+ local_ip.cVal[2] = src_ip[2];
+ local_ip.cVal[3] = src_ip[3];
+ local_port = 35000;
+
+ strcpy(ftp.workingdir, "/");
+
+ socket(CTRL_SOCK, Sn_MR_TCP, IPPORT_FTP, 0x0);
+}
+
+uint8_t ftpd_run(uint8_t * dbuf)
+{
+ uint16_t size = 0, i;
+ long ret = 0;
+ uint32_t blocklen, send_byte, recv_byte;
+ uint32_t remain_filesize;
+ uint32_t remain_datasize;
+#if defined(F_FILESYSTEM)
+ //FILINFO fno;
+#endif
+
+ //memset(dbuf, 0, sizeof(_MAX_SS));
+
+ switch(getSn_SR(CTRL_SOCK))
+ {
+ case SOCK_ESTABLISHED :
+ if(!connect_state_control)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:FTP Connected\r\n", CTRL_SOCK);
+#endif
+ //fsprintf(CTRL_SOCK, banner, HOSTNAME, VERSION);
+ strcpy(ftp.workingdir, "/");
+ sprintf((char *)dbuf, "220 %s FTP version %s ready.\r\n", HOSTNAME, VERSION);
+ ret = send(CTRL_SOCK, (uint8_t *)dbuf, strlen((const char *)dbuf));
+ if(ret < 0)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:send() error:%ld\r\n",CTRL_SOCK,ret);
+#endif
+ close(CTRL_SOCK);
+ return ret;
+ }
+ connect_state_control = 1;
+ }
+
+#if defined(_FTP_DEBUG_)
+ //printf("ftp socket %d\r\n", CTRL_SOCK);
+#endif
+
+ if((size = getSn_RX_RSR(CTRL_SOCK)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
+ {
+#if defined(_FTP_DEBUG_)
+ printf("size: %d\r\n", size);
+#endif
+
+ memset(dbuf, 0, _MAX_SS);
+
+ if(size > _MAX_SS) size = _MAX_SS - 1;
+
+ ret = recv(CTRL_SOCK,dbuf,size);
+ dbuf[ret] = '\0';
+ if(ret != size)
+ {
+ if(ret==SOCK_BUSY) return 0;
+ if(ret < 0)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:recv() error:%ld\r\n",CTRL_SOCK,ret);
+#endif
+ close(CTRL_SOCK);
+ return ret;
+ }
+ }
+#if defined(_FTP_DEBUG_)
+ printf("Rcvd Command: %s", dbuf);
+#endif
+ proc_ftpd((char *)dbuf);
+ }
+ break;
+
+ case SOCK_CLOSE_WAIT :
+#if defined(_FTP_DEBUG_)
+ printf("%d:CloseWait\r\n",CTRL_SOCK);
+#endif
+ if((ret=disconnect(CTRL_SOCK)) != SOCK_OK) return ret;
+#if defined(_FTP_DEBUG_)
+ printf("%d:Closed\r\n",CTRL_SOCK);
+#endif
+ break;
+
+ case SOCK_CLOSED :
+#if defined(_FTP_DEBUG_)
+ printf("%d:FTPStart\r\n",CTRL_SOCK);
+#endif
+ if((ret=socket(CTRL_SOCK, Sn_MR_TCP, IPPORT_FTP, 0x0)) != CTRL_SOCK)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:socket() error:%ld\r\n", CTRL_SOCK, ret);
+#endif
+ close(CTRL_SOCK);
+ return ret;
+ }
+ break;
+
+ case SOCK_INIT :
+#if defined(_FTP_DEBUG_)
+ printf("%d:Opened\r\n",CTRL_SOCK);
+#endif
+ //strcpy(ftp.workingdir, "/");
+ if( (ret = listen(CTRL_SOCK)) != SOCK_OK)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:Listen error\r\n",CTRL_SOCK);
+#endif
+ return ret;
+ }
+ connect_state_control = 0;
+
+#if defined(_FTP_DEBUG_)
+ printf("%d:Listen ok\r\n",CTRL_SOCK);
+#endif
+ break;
+
+ default :
+ break;
+ }
+
+#if 1
+ switch(getSn_SR(DATA_SOCK))
+ {
+ case SOCK_ESTABLISHED :
+ if(!connect_state_data)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:FTP Data socket Connected\r\n", DATA_SOCK);
+#endif
+ connect_state_data = 1;
+ }
+
+ switch(ftp.current_cmd)
+ {
+ case LIST_CMD:
+ case MLSD_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("previous size: %d\r\n", size);
+#endif
+#if defined(F_FILESYSTEM)
+ scan_files(ftp.workingdir, dbuf, (int *)&size);
+#endif
+#if defined(_FTP_DEBUG_)
+ printf("returned size: %d\r\n", size);
+ printf("%s\r\n", dbuf);
+#endif
+#if !defined(F_FILESYSTEM)
+ if (strncmp(ftp.workingdir, "/$Recycle.Bin", sizeof("/$Recycle.Bin")) != 0)
+ size = sprintf(dbuf, "drwxr-xr-x 1 ftp ftp 0 Dec 31 2014 $Recycle.Bin\r\n-rwxr-xr-x 1 ftp ftp 512 Dec 31 2014 test.txt\r\n");
+#endif
+ size = strlen(dbuf);
+ send(DATA_SOCK, dbuf, size);
+ ftp.current_cmd = NO_CMD;
+ disconnect(DATA_SOCK);
+ size = sprintf(dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.workingdir);
+ send(CTRL_SOCK, dbuf, size);
+ break;
+
+ case RETR_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("filename to retrieve : %s %d\r\n", ftp.filename, strlen(ftp.filename));
+#endif
+#if defined(F_FILESYSTEM)
+ ftp.fr = f_open(&(ftp.fil), (const char *)ftp.filename, FA_READ);
+ //print_filedsc(&(ftp.fil));
+ if(ftp.fr == FR_OK){
+ remain_filesize = ftp.fil.fsize;
+#if defined(_FTP_DEBUG_)
+ printf("f_open return FR_OK\r\n");
+#endif
+ do{
+#if defined(_FTP_DEBUG_)
+ //printf("remained file size: %d\r\n", ftp.fil.fsize);
+#endif
+ memset(dbuf, 0, _MAX_SS);
+
+ if(remain_filesize > _MAX_SS)
+ send_byte = _MAX_SS;
+ else
+ send_byte = remain_filesize;
+
+ ftp.fr = f_read(&(ftp.fil), dbuf, send_byte , &blocklen);
+ if(ftp.fr != FR_OK)
+ break;
+#if defined(_FTP_DEBUG_)
+ printf("#");
+ //printf("----->fsize:%d recv:%d len:%d \r\n", remain_filesize, send_byte, blocklen);
+ //printf("----->fn:%s data:%s \r\n", ftp.filename, dbuf);
+#endif
+ send(DATA_SOCK, dbuf, blocklen);
+ remain_filesize -= blocklen;
+ }while(remain_filesize != 0);
+#if defined(_FTP_DEBUG_)
+ printf("\r\nFile read finished\r\n");
+#endif
+ ftp.fr = f_close(&(ftp.fil));
+ }else{
+#if defined(_FTP_DEBUG_)
+ printf("File Open Error: %d\r\n", ftp.fr);
+#endif
+ }
+#else
+ remain_filesize = strlen(ftp.filename);
+
+ do{
+ memset(dbuf, 0, _MAX_SS);
+
+ blocklen = sprintf(dbuf, "%s", ftp.filename);
+
+ printf("########## dbuf:%s\r\n", dbuf);
+
+ send(DATA_SOCK, dbuf, blocklen);
+ remain_filesize -= blocklen;
+ }while(remain_filesize != 0);
+
+#endif
+ ftp.current_cmd = NO_CMD;
+ disconnect(DATA_SOCK);
+ size = sprintf(dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.filename);
+ send(CTRL_SOCK, dbuf, size);
+ break;
+
+ case STOR_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("filename to store : %s %d\r\n", ftp.filename, strlen(ftp.filename));
+#endif
+#if defined(F_FILESYSTEM)
+ ftp.fr = f_open(&(ftp.fil), (const char *)ftp.filename, FA_CREATE_ALWAYS | FA_WRITE);
+ //print_filedsc(&(ftp.fil));
+ if(ftp.fr == FR_OK){
+#if defined(_FTP_DEBUG_)
+ printf("f_open return FR_OK\r\n");
+#endif
+ while(1){
+ if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
+ while(1){
+ memset(dbuf, 0, _MAX_SS);
+
+ if(remain_datasize > _MAX_SS)
+ recv_byte = _MAX_SS;
+ else
+ recv_byte = remain_datasize;
+
+ ret = recv(DATA_SOCK, dbuf, recv_byte);
+#if defined(_FTP_DEBUG_)
+ //printf("----->fn:%s data:%s \r\n", ftp.filename, dbuf);
+#endif
+
+ ftp.fr = f_write(&(ftp.fil), dbuf, (UINT)ret, &blocklen);
+#if defined(_FTP_DEBUG_)
+ //printf("----->dsize:%d recv:%d len:%d \r\n", remain_datasize, ret, blocklen);
+#endif
+ remain_datasize -= blocklen;
+
+ if(ftp.fr != FR_OK){
+#if defined(_FTP_DEBUG_)
+ printf("f_write failed\r\n");
+#endif
+ break;
+ }
+
+ if(remain_datasize <= 0)
+ break;
+ }
+
+ if(ftp.fr != FR_OK){
+#if defined(_FTP_DEBUG_)
+ printf("f_write failed\r\n");
+#endif
+ break;
+ }
+
+#if defined(_FTP_DEBUG_)
+ printf("#");
+#endif
+ }else{
+ if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED)
+ break;
+ }
+ }
+#if defined(_FTP_DEBUG_)
+ printf("\r\nFile write finished\r\n");
+#endif
+ ftp.fr = f_close(&(ftp.fil));
+ }else{
+#if defined(_FTP_DEBUG_)
+ printf("File Open Error: %d\r\n", ftp.fr);
+#endif
+ }
+
+ //fno.fdate = (WORD)(((current_year - 1980) << 9) | (current_month << 5) | current_day);
+ //fno.ftime = (WORD)((current_hour << 11) | (current_min << 5) | (current_sec >> 1));
+ //f_utime((const char *)ftp.filename, &fno);
+#else
+ while(1){
+ if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
+ while(1){
+ memset(dbuf, 0, _MAX_SS);
+
+ if(remain_datasize > _MAX_SS)
+ recv_byte = _MAX_SS;
+ else
+ recv_byte = remain_datasize;
+
+ ret = recv(DATA_SOCK, dbuf, recv_byte);
+
+ printf("########## dbuf:%s\r\n", dbuf);
+
+ remain_datasize -= ret;
+
+ if(remain_datasize <= 0)
+ break;
+ }
+ }else{
+ if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED)
+ break;
+ }
+ }
+#endif
+ ftp.current_cmd = NO_CMD;
+ disconnect(DATA_SOCK);
+ size = sprintf(dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.filename);
+ send(CTRL_SOCK, dbuf, size);
+ break;
+
+ case NO_CMD:
+ default:
+ break;
+ }
+ break;
+
+ case SOCK_CLOSE_WAIT :
+#if defined(_FTP_DEBUG_)
+ printf("%d:CloseWait\r\n",DATA_SOCK);
+#endif
+ if((ret=disconnect(DATA_SOCK)) != SOCK_OK) return ret;
+#if defined(_FTP_DEBUG_)
+ printf("%d:Closed\r\n",DATA_SOCK);
+#endif
+ break;
+
+ case SOCK_CLOSED :
+ if(ftp.dsock_state == DATASOCK_READY)
+ {
+ if(ftp.dsock_mode == PASSIVE_MODE){
+#if defined(_FTP_DEBUG_)
+ printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, local_port);
+#endif
+ if((ret=socket(DATA_SOCK, Sn_MR_TCP, local_port, 0x0)) != DATA_SOCK)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
+#endif
+ close(DATA_SOCK);
+ return ret;
+ }
+
+ local_port++;
+ if(local_port > 50000)
+ local_port = 35000;
+ }else{
+#if defined(_FTP_DEBUG_)
+ printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, IPPORT_FTPD);
+#endif
+ if((ret=socket(DATA_SOCK, Sn_MR_TCP, IPPORT_FTPD, 0x0)) != DATA_SOCK)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
+#endif
+ close(DATA_SOCK);
+ return ret;
+ }
+ }
+
+ ftp.dsock_state = DATASOCK_START;
+ }
+ break;
+
+ case SOCK_INIT :
+#if defined(_FTP_DEBUG_)
+ printf("%d:Opened\r\n",DATA_SOCK);
+#endif
+ if(ftp.dsock_mode == PASSIVE_MODE){
+ if( (ret = listen(DATA_SOCK)) != SOCK_OK)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:Listen error\r\n",DATA_SOCK);
+#endif
+ return ret;
+ }
+
+#if defined(_FTP_DEBUG_)
+ printf("%d:Listen ok\r\n",DATA_SOCK);
+#endif
+ }else{
+ if((ret = connect(DATA_SOCK, remote_ip.cVal, remote_port)) != SOCK_OK){
+#if defined(_FTP_DEBUG_)
+ printf("%d:Connect error\r\n", DATA_SOCK);
+#endif
+ return ret;
+ }
+ }
+ connect_state_data = 0;
+ break;
+
+ default :
+ break;
+ }
+#endif
+
+ return 0;
+}
+
+char proc_ftpd(char * buf)
+{
+ char **cmdp, *cp, *arg, *tmpstr;
+ char sendbuf[200];
+ int slen;
+ long ret;
+
+
+ /* Translate first word to lower case */
+ for (cp = buf; *cp != ' ' && *cp != '\0'; cp++)
+ *cp = tolower(*cp);
+
+ /* Find command in table; if not present, return syntax error */
+ for (cmdp = commands; *cmdp != NULL; cmdp++)
+ if (strncmp(*cmdp, buf, strlen(*cmdp)) == 0)
+ break;
+
+ if (*cmdp == NULL)
+ {
+ //fsprintf(CTRL_SOCK, badcmd, buf);
+ slen = sprintf(sendbuf, "500 Unknown command '%s'\r\n", buf);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ return 0;
+ }
+ /* Allow only USER, PASS and QUIT before logging in */
+ if (ftp.state == FTPS_NOT_LOGIN)
+ {
+ switch(cmdp - commands)
+ {
+ case USER_CMD:
+ case PASS_CMD:
+ case QUIT_CMD:
+ break;
+ default:
+ //fsprintf(CTRL_SOCK, notlog);
+ slen = sprintf(sendbuf, "530 Please log in with USER and PASS\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ return 0;
+ }
+ }
+
+ arg = &buf[strlen(*cmdp)];
+ while(*arg == ' ') arg++;
+
+ /* Execute specific command */
+ switch (cmdp - commands)
+ {
+ case USER_CMD :
+#if defined(_FTP_DEBUG_)
+ printf("USER_CMD : %s", arg);
+#endif
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+ strcpy(ftp.username, arg);
+ //fsprintf(CTRL_SOCK, givepass);
+ slen = sprintf(sendbuf, "331 Enter PASS command\r\n");
+ ret = send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ if(ret < 0)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("%d:send() error:%ld\r\n",CTRL_SOCK,ret);
+#endif
+ close(CTRL_SOCK);
+ return ret;
+ }
+ break;
+
+ case PASS_CMD :
+#if defined(_FTP_DEBUG_)
+ printf("PASS_CMD : %s", arg);
+#endif
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+ ftplogin(arg);
+ break;
+
+ case TYPE_CMD :
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+ switch(arg[0])
+ {
+ case 'A':
+ case 'a': /* Ascii */
+ ftp.type = ASCII_TYPE;
+ //fsprintf(CTRL_SOCK, typeok, arg);
+ slen = sprintf(sendbuf, "200 Type set to %s\r\n", arg);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case 'B':
+ case 'b': /* Binary */
+ case 'I':
+ case 'i': /* Image */
+ ftp.type = IMAGE_TYPE;
+ //fsprintf(CTRL_SOCK, typeok, arg);
+ slen = sprintf(sendbuf, "200 Type set to %s\r\n", arg);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ default: /* Invalid */
+ //fsprintf(CTRL_SOCK, badtype, arg);
+ slen = sprintf(sendbuf, "501 Unknown type \"%s\"\r\n", arg);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+ }
+ break;
+
+ case FEAT_CMD :
+ slen = sprintf(sendbuf, "211-Features:\r\n MDTM\r\n REST STREAM\r\n SIZE\r\n MLST size*;type*;create*;modify*;\r\n MLSD\r\n UTF8\r\n CLNT\r\n MFMT\r\n211 END\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case QUIT_CMD :
+#if defined(_FTP_DEBUG_)
+ printf("QUIT_CMD\r\n");
+#endif
+ //fsprintf(CTRL_SOCK, bye);
+ slen = sprintf(sendbuf, "221 Goodbye!\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ disconnect(CTRL_SOCK);
+ break;
+
+ case RETR_CMD :
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+#if defined(_FTP_DEBUG_)
+ printf("RETR_CMD\r\n");
+#endif
+ if(strlen(ftp.workingdir) == 1)
+ sprintf(ftp.filename, "/%s", arg);
+ else
+ sprintf(ftp.filename, "%s/%s", ftp.workingdir, arg);
+ slen = sprintf(sendbuf, "150 Opening data channel for file downloand from server of \"%s\"\r\n", ftp.filename);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ ftp.current_cmd = RETR_CMD;
+ break;
+
+ case APPE_CMD :
+ case STOR_CMD:
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+#if defined(_FTP_DEBUG_)
+ printf("STOR_CMD\r\n");
+#endif
+ if(strlen(ftp.workingdir) == 1)
+ sprintf(ftp.filename, "/%s", arg);
+ else
+ sprintf(ftp.filename, "%s/%s", ftp.workingdir, arg);
+ slen = sprintf(sendbuf, "150 Opening data channel for file upload to server of \"%s\"\r\n", ftp.filename);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ ftp.current_cmd = STOR_CMD;
+ if((ret = connect(DATA_SOCK, remote_ip.cVal, remote_port)) != SOCK_OK){
+#if defined(_FTP_DEBUG_)
+ printf("%d:Connect error\r\n", DATA_SOCK);
+#endif
+ return ret;
+ }
+ connect_state_data = 0;
+ break;
+
+ case PORT_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("PORT_CMD\r\n");
+#endif
+ if (pport(arg) == -1){
+ //fsprintf(CTRL_SOCK, badport);
+ slen = sprintf(sendbuf, "501 Bad port syntax\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ } else{
+ //fsprintf(CTRL_SOCK, portok);
+ ftp.dsock_mode = ACTIVE_MODE;
+ ftp.dsock_state = DATASOCK_READY;
+ slen = sprintf(sendbuf, "200 PORT command successful.\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ }
+ break;
+
+ case MLSD_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("MLSD_CMD\r\n");
+#endif
+ slen = sprintf(sendbuf, "150 Opening data channel for directory listing of \"%s\"\r\n", ftp.workingdir);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ ftp.current_cmd = MLSD_CMD;
+ break;
+
+ case LIST_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("LIST_CMD\r\n");
+#endif
+ slen = sprintf(sendbuf, "150 Opening data channel for directory listing of \"%s\"\r\n", ftp.workingdir);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ ftp.current_cmd = LIST_CMD;
+ break;
+
+ case NLST_CMD:
+#if defined(_FTP_DEBUG_)
+ printf("NLST_CMD\r\n");
+#endif
+ break;
+
+ case SYST_CMD:
+ slen = sprintf(sendbuf, "215 UNIX emulated by WIZnet\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case PWD_CMD:
+ case XPWD_CMD:
+ slen = sprintf(sendbuf, "257 \"%s\" is current directory.\r\n", ftp.workingdir);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case PASV_CMD:
+ slen = sprintf(sendbuf, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n", local_ip.cVal[0], local_ip.cVal[1], local_ip.cVal[2], local_ip.cVal[3], local_port >> 8, local_port & 0x00ff);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ disconnect(DATA_SOCK);
+ ftp.dsock_mode = PASSIVE_MODE;
+ ftp.dsock_state = DATASOCK_READY;
+#if defined(_FTP_DEBUG_)
+ printf("PASV port: %d\r\n", local_port);
+#endif
+ break;
+
+ case SIZE_CMD:
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+ if(slen > 3)
+ {
+ tmpstr = strrchr(arg, '/');
+ *tmpstr = 0;
+#if defined(F_FILESYSTEM)
+ slen = get_filesize(arg, tmpstr + 1);
+#else
+ slen = _MAX_SS;
+#endif
+ if(slen > 0)
+ slen = sprintf(sendbuf, "213 %d\r\n", slen);
+ else
+ slen = sprintf(sendbuf, "550 File not Found\r\n");
+ }
+ else
+ {
+ slen = sprintf(sendbuf, "550 File not Found\r\n");
+ }
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case CWD_CMD:
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+ if(slen > 3)
+ {
+ arg[slen - 3] = 0x00;
+ tmpstr = strrchr(arg, '/');
+ *tmpstr = 0;
+#if defined(F_FILESYSTEM)
+ slen = get_filesize(arg, tmpstr + 1);
+#else
+ slen = 0;
+#endif
+ *tmpstr = '/';
+ if(slen == 0){
+ slen = sprintf(sendbuf, "213 %d\r\n", slen);
+ strcpy(ftp.workingdir, arg);
+ slen = sprintf(sendbuf, "250 CWD successful. \"%s\" is current directory.\r\n", ftp.workingdir);
+ }
+ else
+ {
+ slen = sprintf(sendbuf, "550 CWD failed. \"%s\"\r\n", arg);
+ }
+ }
+ else
+ {
+ strcpy(ftp.workingdir, arg);
+ slen = sprintf(sendbuf, "250 CWD successful. \"%s\" is current directory.\r\n", ftp.workingdir);
+ }
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case MKD_CMD:
+ case XMKD_CMD:
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+#if defined(F_FILESYSTEM)
+ if (f_mkdir(arg) != 0)
+ {
+ slen = sprintf(sendbuf, "550 Can't create directory. \"%s\"\r\n", arg);
+ }
+ else
+ {
+ slen = sprintf(sendbuf, "257 MKD command successful. \"%s\"\r\n", arg);
+ //strcpy(ftp.workingdir, arg);
+ }
+#else
+ slen = sprintf(sendbuf, "550 Can't create directory. Permission denied\r\n");
+#endif
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case DELE_CMD:
+ slen = strlen(arg);
+ arg[slen - 1] = 0x00;
+ arg[slen - 2] = 0x00;
+#if defined(F_FILESYSTEM)
+ if (f_unlink(arg) != 0)
+ {
+ slen = sprintf(sendbuf, "550 Could not delete. \"%s\"\r\n", arg);
+ }
+ else
+ {
+ slen = sprintf(sendbuf, "250 Deleted. \"%s\"\r\n", arg);
+ }
+#else
+ slen = sprintf(sendbuf, "550 Could not delete. Permission denied\r\n");
+#endif
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ case XCWD_CMD:
+ case ACCT_CMD:
+ case XRMD_CMD:
+ case RMD_CMD:
+ case STRU_CMD:
+ case MODE_CMD:
+ case XMD5_CMD:
+ //fsprintf(CTRL_SOCK, unimp);
+ slen = sprintf(sendbuf, "502 Command does not implemented yet.\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+
+ default: /* Invalid */
+ //fsprintf(CTRL_SOCK, badcmd, arg);
+ slen = sprintf(sendbuf, "500 Unknown command \'%s\'\r\n", arg);
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ break;
+ }
+
+ return 1;
+}
+
+
+char ftplogin(char * pass)
+{
+ char sendbuf[100];
+ int slen = 0;
+
+ //memset(sendbuf, 0, DATA_BUF_SIZE);
+
+#if defined(_FTP_DEBUG_)
+ printf("%s logged in\r\n", ftp.username);
+#endif
+ //fsprintf(CTRL_SOCK, logged);
+ slen = sprintf(sendbuf, "230 Logged on\r\n");
+ send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
+ ftp.state = FTPS_LOGIN;
+
+ return 1;
+}
+
+int pport(char * arg)
+{
+ int i;
+ char* tok=0;
+
+ for (i = 0; i < 4; i++)
+ {
+ if(i==0) tok = strtok(arg,",\r\n");
+ else tok = strtok(NULL,",");
+ remote_ip.cVal[i] = (uint8_t)atoi(tok, 10);
+ if (!tok)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("bad pport : %s\r\n", arg);
+#endif
+ return -1;
+ }
+ }
+ remote_port = 0;
+ for (i = 0; i < 2; i++)
+ {
+ tok = strtok(NULL,",\r\n");
+ remote_port <<= 8;
+ remote_port += atoi(tok, 10);
+ if (!tok)
+ {
+#if defined(_FTP_DEBUG_)
+ printf("bad pport : %s\r\n", arg);
+#endif
+ return -1;
+ }
+ }
+#if defined(_FTP_DEBUG_)
+ printf("ip : %d.%d.%d.%d, port : %d\r\n", remote_ip.cVal[0], remote_ip.cVal[1], remote_ip.cVal[2], remote_ip.cVal[3], remote_port);
+#endif
+
+ return 0;
+}
+
+#if defined(F_FILESYSTEM)
+void print_filedsc(FIL *fil)
+{
+#if defined(_FTP_DEBUG_)
+ printf("File System pointer : %08X\r\n", fil->fs);
+ printf("File System mount ID : %d\r\n", fil->id);
+ printf("File status flag : %08X\r\n", fil->flag);
+ printf("File System pads : %08X\r\n", fil->err);
+ printf("File read write pointer : %08X\r\n", fil->fptr);
+ printf("File size : %08X\r\n", fil->fsize);
+ printf("File start cluster : %08X\r\n", fil->sclust);
+ printf("current cluster : %08X\r\n", fil->clust);
+ printf("current data sector : %08X\r\n", fil->dsect);
+ printf("dir entry sector : %08X\r\n", fil->dir_sect);
+ printf("dir entry pointer : %08X\r\n", fil->dir_ptr);
+#endif
+}
+#endif
diff --git a/WIZ550S2E_App/src/Internet/FTPServer/ftpd.h b/WIZ550S2E_App/src/Internet/FTPServer/ftpd.h
new file mode 100644
index 0000000..53256bc
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPServer/ftpd.h
@@ -0,0 +1,145 @@
+#ifndef _FTPD_H_
+#define _FTPD_H_
+
+/*
+* Wiznet.
+* (c) Copyright 2002, Wiznet.
+*
+* Filename : ftpd.h
+* Version : 1.0
+* Programmer(s) :
+* Created : 2003/01/28
+* Description : Header file of FTP daemon. (AVR-GCC Compiler)
+*/
+
+#include
+
+//#define F_FILESYSTEM // If your target support a file system, you have to activate this feature and implement.
+
+#if defined(F_FILESYSTEM)
+#include "ff.h"
+#endif
+
+#define F_APP_FTP
+#define _FTP_DEBUG_
+
+
+#define LINELEN 100
+//#define DATA_BUF_SIZE 100
+#if !defined(F_FILESYSTEM)
+#define _MAX_SS 512
+#endif
+
+#define CTRL_SOCK 2
+#define DATA_SOCK 3
+
+#define IPPORT_FTPD 20 /* FTP Data port */
+#define IPPORT_FTP 21 /* FTP Control port */
+
+#define HOSTNAME "iinChip"
+#define VERSION "1.0"
+
+#define FILENAME "a.txt"
+
+/* FTP commands */
+enum ftp_cmd {
+ USER_CMD,
+ ACCT_CMD,
+ PASS_CMD,
+ TYPE_CMD,
+ LIST_CMD,
+ CWD_CMD,
+ DELE_CMD,
+ NAME_CMD,
+ QUIT_CMD,
+ RETR_CMD,
+ STOR_CMD,
+ PORT_CMD,
+ NLST_CMD,
+ PWD_CMD,
+ XPWD_CMD,
+ MKD_CMD,
+ XMKD_CMD,
+ XRMD_CMD,
+ RMD_CMD,
+ STRU_CMD,
+ MODE_CMD,
+ SYST_CMD,
+ XMD5_CMD,
+ XCWD_CMD,
+ FEAT_CMD,
+ PASV_CMD,
+ SIZE_CMD,
+ MLSD_CMD,
+ APPE_CMD,
+ NO_CMD,
+};
+
+enum ftp_type {
+ ASCII_TYPE,
+ IMAGE_TYPE,
+ LOGICAL_TYPE
+};
+
+enum ftp_state {
+ FTPS_NOT_LOGIN,
+ FTPS_LOGIN
+};
+
+enum datasock_state{
+ DATASOCK_IDLE,
+ DATASOCK_READY,
+ DATASOCK_START
+};
+
+enum datasock_mode{
+ PASSIVE_MODE,
+ ACTIVE_MODE
+};
+
+struct ftpd {
+ uint8_t control; /* Control stream */
+ uint8_t data; /* Data stream */
+
+ enum ftp_type type; /* Transfer type */
+ enum ftp_state state;
+
+ enum ftp_cmd current_cmd;
+
+ enum datasock_state dsock_state;
+ enum datasock_mode dsock_mode;
+
+ char username[LINELEN]; /* Arg to USER command */
+ char workingdir[LINELEN];
+ char filename[LINELEN];
+
+#if defined(F_FILESYSTEM)
+ FIL fil; // FatFs File objects
+ FRESULT fr; // FatFs function common result code
+#endif
+
+};
+
+#ifndef un_I2cval
+typedef union _un_l2cval {
+ uint32_t lVal;
+ uint8_t cVal[4];
+}un_l2cval;
+#endif
+
+void ftpd_init(uint8_t * src_ip);
+uint8_t ftpd_run(uint8_t * dbuf);
+char proc_ftpd(char * buf);
+char ftplogin(char * pass);
+int pport(char * arg);
+
+int sendit(char * command);
+int recvit(char * command);
+
+long sendfile(uint8_t s, char * command);
+long recvfile(uint8_t s);
+
+#if defined(F_FILESYSTEM)
+void print_filedsc(FIL *fil);
+#endif
+#endif // _FTPD_H_
diff --git a/WIZ550S2E_App/src/Internet/FTPServer/stdio_private.h b/WIZ550S2E_App/src/Internet/FTPServer/stdio_private.h
new file mode 100644
index 0000000..26b6d87
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/FTPServer/stdio_private.h
@@ -0,0 +1,67 @@
+/* Copyright (c) 2002, Joerg Wunsch
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
+*/
+
+/* $Id: stdio_private.h,v 1.6 2003/01/07 22:17:24 joerg_wunsch Exp $ */
+
+#include
+#include
+
+struct __file {
+ char *buf; /* buffer pointer */
+ unsigned char unget; /* ungetc() buffer */
+ uint8_t flags; /* flags, see below */
+#define __SRD 0x0001 /* OK to read */
+#define __SWR 0x0002 /* OK to write */
+#define __SSTR 0x0004 /* this is an sprintf/snprintf string */
+#define __SPGM 0x0008 /* fmt string is in progmem */
+#define __SERR 0x0010 /* found error */
+#define __SEOF 0x0020 /* found EOF */
+#define __SUNGET 0x040 /* ungetc() happened */
+#if 0
+/* possible future extensions, will require uint16_t flags */
+#define __SRW 0x0080 /* open for reading & writing */
+#define __SLBF 0x0100 /* line buffered */
+#define __SNBF 0x0200 /* unbuffered */
+#define __SMBF 0x0400 /* buf is from malloc */
+#endif
+ int size; /* size of buffer */
+ int len; /* characters read or written so far */
+ int (*put)(char); /* function to write one char to device */
+ int (*get)(void); /* function to read one char from device */
+};
+
+/* values for PRINTF_LEVEL */
+#define PRINTF_MIN 1
+#define PRINTF_STD 2
+#define PRINTF_FLT 3
+
+/* values for SCANF_LEVEL */
+#define SCANF_MIN 1
+#define SCANF_STD 2
+#define SCANF_FLT 3
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.c
new file mode 100644
index 0000000..ee78d1a
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.c
@@ -0,0 +1,583 @@
+/*******************************************************************************
+ * Copyright (c) 2014, 2015 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+#include "MQTTClient.h"
+
+static void NewMessageData(MessageData* md, MQTTString* aTopicName, MQTTMessage* aMessage) {
+ md->topicName = aTopicName;
+ md->message = aMessage;
+}
+
+
+static int getNextPacketId(MQTTClient *c) {
+ return c->next_packetid = (c->next_packetid == MAX_PACKET_ID) ? 1 : c->next_packetid + 1;
+}
+
+
+static int sendPacket(MQTTClient* c, int length, Timer* timer)
+{
+ int rc = FAILURE,
+ sent = 0;
+
+ while (sent < length && !TimerIsExpired(timer))
+ {
+ rc = c->ipstack->mqttwrite(c->ipstack, &c->buf[sent], length, TimerLeftMS(timer));
+ if (rc < 0) // there was an error writing the data
+ break;
+ sent += rc;
+ }
+ if (sent == length)
+ {
+ TimerCountdown(&c->ping_timer, c->keepAliveInterval); // record the fact that we have successfully sent the packet
+ rc = SUCCESSS;
+ }
+ else
+ rc = FAILURE;
+ return rc;
+}
+
+
+void MQTTClientInit(MQTTClient* c, Network* network, unsigned int command_timeout_ms,
+ unsigned char* sendbuf, size_t sendbuf_size, unsigned char* readbuf, size_t readbuf_size)
+{
+ int i;
+ c->ipstack = network;
+
+ for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i)
+ c->messageHandlers[i].topicFilter = 0;
+ c->command_timeout_ms = command_timeout_ms;
+ c->buf = sendbuf;
+ c->buf_size = sendbuf_size;
+ c->readbuf = readbuf;
+ c->readbuf_size = readbuf_size;
+ c->isconnected = 0;
+ c->ping_outstanding = 0;
+ c->defaultMessageHandler = NULL;
+ c->next_packetid = 1;
+ TimerInit(&c->ping_timer);
+#if defined(MQTT_TASK)
+ MutexInit(&c->mutex);
+#endif
+}
+
+
+static int decodePacket(MQTTClient* c, int* value, int timeout)
+{
+ unsigned char i;
+ int multiplier = 1;
+ int len = 0;
+ const int MAX_NO_OF_REMAINING_LENGTH_BYTES = 4;
+
+ *value = 0;
+ do
+ {
+ int rc = MQTTPACKET_READ_ERROR;
+
+ if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES)
+ {
+ rc = MQTTPACKET_READ_ERROR; /* bad data */
+ goto exit;
+ }
+ rc = c->ipstack->mqttread(c->ipstack, &i, 1, timeout);
+ if (rc != 1)
+ goto exit;
+ *value += (i & 127) * multiplier;
+ multiplier *= 128;
+ } while ((i & 128) != 0);
+exit:
+ return len;
+}
+
+
+static int readPacket(MQTTClient* c, Timer* timer)
+{
+ int rc = FAILURE;
+ MQTTHeader header = {0};
+ int len = 0;
+ int rem_len = 0;
+
+ /* 1. read the header byte. This has the packet type in it */
+ if (c->ipstack->mqttread(c->ipstack, c->readbuf, 1, TimerLeftMS(timer)) != 1)
+ goto exit;
+
+ len = 1;
+ /* 2. read the remaining length. This is variable in itself */
+ decodePacket(c, &rem_len, TimerLeftMS(timer));
+ len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */
+
+ /* 3. read the rest of the buffer using a callback to supply the rest of the data */
+ if (rem_len > 0 && (c->ipstack->mqttread(c->ipstack, c->readbuf + len, rem_len, TimerLeftMS(timer)) != rem_len))
+ goto exit;
+
+ header.byte = c->readbuf[0];
+ rc = header.bits.type;
+exit:
+ return rc;
+}
+
+
+// assume topic filter and name is in correct format
+// # can only be at end
+// + and # can only be next to separator
+static char isTopicMatched(char* topicFilter, MQTTString* topicName)
+{
+ char* curf = topicFilter;
+ char* curn = topicName->lenstring.data;
+ char* curn_end = curn + topicName->lenstring.len;
+
+ while (*curf && curn < curn_end)
+ {
+ if (*curn == '/' && *curf != '/')
+ break;
+ if (*curf != '+' && *curf != '#' && *curf != *curn)
+ break;
+ if (*curf == '+')
+ { // skip until we meet the next separator, or end of string
+ char* nextpos = curn + 1;
+ while (nextpos < curn_end && *nextpos != '/')
+ nextpos = ++curn + 1;
+ }
+ else if (*curf == '#')
+ curn = curn_end - 1; // skip until end of string
+ curf++;
+ curn++;
+ };
+
+ return (curn == curn_end) && (*curf == '\0');
+}
+
+
+int deliverMessage(MQTTClient* c, MQTTString* topicName, MQTTMessage* message)
+{
+ int i;
+ int rc = FAILURE;
+
+ // we have to find the right message handler - indexed by topic
+ for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i)
+ {
+ if (c->messageHandlers[i].topicFilter != 0 && (MQTTPacket_equals(topicName, (char*)c->messageHandlers[i].topicFilter) ||
+ isTopicMatched((char*)c->messageHandlers[i].topicFilter, topicName)))
+ {
+ if (c->messageHandlers[i].fp != NULL)
+ {
+ MessageData md;
+ NewMessageData(&md, topicName, message);
+ c->messageHandlers[i].fp(&md);
+ rc = SUCCESSS;
+ }
+ }
+ }
+
+ if (rc == FAILURE && c->defaultMessageHandler != NULL)
+ {
+ MessageData md;
+ NewMessageData(&md, topicName, message);
+ c->defaultMessageHandler(&md);
+ rc = SUCCESSS;
+ }
+
+ return rc;
+}
+
+
+int keepalive(MQTTClient* c)
+{
+ int rc = FAILURE;
+
+ if (c->keepAliveInterval == 0)
+ {
+ rc = SUCCESSS;
+ goto exit;
+ }
+
+ if (TimerIsExpired(&c->ping_timer))
+ {
+ if (!c->ping_outstanding)
+ {
+ Timer timer;
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, 1000);
+ int len = MQTTSerialize_pingreq(c->buf, c->buf_size);
+ if (len > 0 && (rc = sendPacket(c, len, &timer)) == SUCCESSS) // send the ping packet
+ c->ping_outstanding = 1;
+ }
+ }
+
+exit:
+ return rc;
+}
+
+
+int cycle(MQTTClient* c, Timer* timer)
+{
+ // read the socket, see what work is due
+ unsigned short packet_type = readPacket(c, timer);
+
+ int len = 0,
+ rc = SUCCESSS;
+
+ switch (packet_type)
+ {
+ case CONNACK:
+ case PUBACK:
+ case SUBACK:
+ break;
+ case PUBLISH:
+ {
+ MQTTString topicName;
+ MQTTMessage msg;
+ int intQoS;
+ if (MQTTDeserialize_publish(&msg.dup, &intQoS, &msg.retained, &msg.id, &topicName,
+ (unsigned char**)&msg.payload, (int*)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1)
+ goto exit;
+ msg.qos = (enum QoS)intQoS;
+ deliverMessage(c, &topicName, &msg);
+ if (msg.qos != QOS0)
+ {
+ if (msg.qos == QOS1)
+ len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
+ else if (msg.qos == QOS2)
+ len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);
+ if (len <= 0)
+ rc = FAILURE;
+ else
+ rc = sendPacket(c, len, timer);
+ if (rc == FAILURE)
+ goto exit; // there was a problem
+ }
+ break;
+ }
+ case PUBREC:
+ {
+ unsigned short mypacketid;
+ unsigned char dup, type;
+ if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
+ rc = FAILURE;
+ else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREL, 0, mypacketid)) <= 0)
+ rc = FAILURE;
+ else if ((rc = sendPacket(c, len, timer)) != SUCCESSS) // send the PUBREL packet
+ rc = FAILURE; // there was a problem
+ if (rc == FAILURE)
+ goto exit; // there was a problem
+ break;
+ }
+ case PUBCOMP:
+ break;
+ case PINGRESP:
+ c->ping_outstanding = 0;
+ break;
+ }
+ keepalive(c);
+exit:
+ if (rc == SUCCESSS)
+ rc = packet_type;
+ return rc;
+}
+
+
+int MQTTYield(MQTTClient* c, int timeout_ms)
+{
+ int rc = SUCCESSS;
+ Timer timer;
+
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, timeout_ms);
+
+ do
+ {
+ if (cycle(c, &timer) == FAILURE)
+ {
+ rc = FAILURE;
+ break;
+ }
+ } while (!TimerIsExpired(&timer));
+
+ return rc;
+}
+
+
+void MQTTRun(void* parm)
+{
+ Timer timer;
+ MQTTClient* c = (MQTTClient*)parm;
+
+ TimerInit(&timer);
+
+ while (1)
+ {
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ TimerCountdownMS(&timer, 500); /* Don't wait too long if no traffic is incoming */
+ cycle(c, &timer);
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+ }
+}
+
+
+#if defined(MQTT_TASK)
+int MQTTStartTask(MQTTClient* client)
+{
+ return ThreadStart(&client->thread, &MQTTRun, client);
+}
+#endif
+
+
+int waitfor(MQTTClient* c, int packet_type, Timer* timer)
+{
+ int rc = FAILURE;
+
+ do
+ {
+ if (TimerIsExpired(timer))
+ break; // we timed out
+ }
+ while ((rc = cycle(c, timer)) != packet_type);
+
+ return rc;
+}
+
+
+int MQTTConnect(MQTTClient* c, MQTTPacket_connectData* options)
+{
+ Timer connect_timer;
+ int rc = FAILURE;
+ MQTTPacket_connectData default_options = MQTTPacket_connectData_initializer;
+ int len = 0;
+
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ if (c->isconnected) /* don't send connect packet again if we are already connected */
+ goto exit;
+
+ TimerInit(&connect_timer);
+ TimerCountdownMS(&connect_timer, c->command_timeout_ms);
+
+ if (options == 0)
+ options = &default_options; /* set default options if none were supplied */
+
+ c->keepAliveInterval = options->keepAliveInterval;
+ TimerCountdown(&c->ping_timer, c->keepAliveInterval);
+ if ((len = MQTTSerialize_connect(c->buf, c->buf_size, options)) <= 0)
+ goto exit;
+ if ((rc = sendPacket(c, len, &connect_timer)) != SUCCESSS) // send the connect packet
+ goto exit; // there was a problem
+
+ // this will be a blocking call, wait for the connack
+ if (waitfor(c, CONNACK, &connect_timer) == CONNACK)
+ {
+ unsigned char connack_rc = 255;
+ unsigned char sessionPresent = 0;
+ if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, c->readbuf, c->readbuf_size) == 1)
+ rc = connack_rc;
+ else
+ rc = FAILURE;
+ }
+ else
+ rc = FAILURE;
+
+exit:
+ if (rc == SUCCESSS)
+ c->isconnected = 1;
+
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+
+ return rc;
+}
+
+
+int MQTTSubscribe(MQTTClient* c, const char* topicFilter, enum QoS qos, messageHandler messageHandler)
+{
+ int rc = FAILURE;
+ Timer timer;
+ int len = 0;
+ MQTTString topic = MQTTString_initializer;
+ topic.cstring = (char *)topicFilter;
+
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ if (!c->isconnected)
+ goto exit;
+
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, c->command_timeout_ms);
+
+ len = MQTTSerialize_subscribe(c->buf, c->buf_size, 0, getNextPacketId(c), 1, &topic, (int*)&qos);
+ if (len <= 0)
+ goto exit;
+ if ((rc = sendPacket(c, len, &timer)) != SUCCESSS) // send the subscribe packet
+ goto exit; // there was a problem
+
+ if (waitfor(c, SUBACK, &timer) == SUBACK) // wait for suback
+ {
+ int count = 0, grantedQoS = -1;
+ unsigned short mypacketid;
+ if (MQTTDeserialize_suback(&mypacketid, 1, &count, &grantedQoS, c->readbuf, c->readbuf_size) == 1)
+ rc = grantedQoS; // 0, 1, 2 or 0x80
+ if (rc != 0x80)
+ {
+ int i;
+ for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i)
+ {
+ if (c->messageHandlers[i].topicFilter == 0)
+ {
+ c->messageHandlers[i].topicFilter = topicFilter;
+ c->messageHandlers[i].fp = messageHandler;
+ rc = 0;
+ break;
+ }
+ }
+ }
+ }
+ else
+ rc = FAILURE;
+
+exit:
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+ return rc;
+}
+
+
+int MQTTUnsubscribe(MQTTClient* c, const char* topicFilter)
+{
+ int rc = FAILURE;
+ Timer timer;
+ MQTTString topic = MQTTString_initializer;
+ topic.cstring = (char *)topicFilter;
+ int len = 0;
+
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ if (!c->isconnected)
+ goto exit;
+
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, c->command_timeout_ms);
+
+ if ((len = MQTTSerialize_unsubscribe(c->buf, c->buf_size, 0, getNextPacketId(c), 1, &topic)) <= 0)
+ goto exit;
+ if ((rc = sendPacket(c, len, &timer)) != SUCCESSS) // send the subscribe packet
+ goto exit; // there was a problem
+
+ if (waitfor(c, UNSUBACK, &timer) == UNSUBACK)
+ {
+ unsigned short mypacketid; // should be the same as the packetid above
+ if (MQTTDeserialize_unsuback(&mypacketid, c->readbuf, c->readbuf_size) == 1)
+ rc = 0;
+ }
+ else
+ rc = FAILURE;
+
+exit:
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+ return rc;
+}
+
+
+int MQTTPublish(MQTTClient* c, const char* topicName, MQTTMessage* message)
+{
+ int rc = FAILURE;
+ Timer timer;
+ MQTTString topic = MQTTString_initializer;
+ topic.cstring = (char *)topicName;
+ int len = 0;
+
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ if (!c->isconnected)
+ goto exit;
+
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, c->command_timeout_ms);
+
+ if (message->qos == QOS1 || message->qos == QOS2)
+ message->id = getNextPacketId(c);
+
+ len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id,
+ topic, (unsigned char*)message->payload, message->payloadlen);
+ if (len <= 0)
+ goto exit;
+ if ((rc = sendPacket(c, len, &timer)) != SUCCESSS) // send the subscribe packet
+ goto exit; // there was a problem
+
+ if (message->qos == QOS1)
+ {
+ if (waitfor(c, PUBACK, &timer) == PUBACK)
+ {
+ unsigned short mypacketid;
+ unsigned char dup, type;
+ if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
+ rc = FAILURE;
+ }
+ else
+ rc = FAILURE;
+ }
+ else if (message->qos == QOS2)
+ {
+ if (waitfor(c, PUBCOMP, &timer) == PUBCOMP)
+ {
+ unsigned short mypacketid;
+ unsigned char dup, type;
+ if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
+ rc = FAILURE;
+ }
+ else
+ rc = FAILURE;
+ }
+
+exit:
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+ return rc;
+}
+
+
+int MQTTDisconnect(MQTTClient* c)
+{
+ int rc = FAILURE;
+ Timer timer; // we might wait for incomplete incoming publishes to complete
+ int len = 0;
+
+#if defined(MQTT_TASK)
+ MutexLock(&c->mutex);
+#endif
+ TimerInit(&timer);
+ TimerCountdownMS(&timer, c->command_timeout_ms);
+
+ len = MQTTSerialize_disconnect(c->buf, c->buf_size);
+ if (len > 0)
+ rc = sendPacket(c, len, &timer); // send the disconnect packet
+
+ c->isconnected = 0;
+
+#if defined(MQTT_TASK)
+ MutexUnlock(&c->mutex);
+#endif
+ return rc;
+}
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.h
new file mode 100644
index 0000000..2b51318
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTClient.h
@@ -0,0 +1,182 @@
+/*******************************************************************************
+ * Copyright (c) 2014, 2015 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation
+ * Ian Craggs - documentation and platform specific header
+ *******************************************************************************/
+
+#if !defined(__MQTT_CLIENT_C_)
+#define __MQTT_CLIENT_C_
+
+#if defined(__cplusplus)
+ extern "C" {
+#endif
+
+#if defined(WIN32_DLL) || defined(WIN64_DLL)
+ #define DLLImport __declspec(dllimport)
+ #define DLLExport __declspec(dllexport)
+#elif defined(LINUX_SO)
+ #define DLLImport extern
+ #define DLLExport __attribute__ ((visibility ("default")))
+#else
+ #define DLLImport
+ #define DLLExport
+#endif
+
+#include "MQTTPacket.h"
+#include "stdio.h"
+#include "mqtt_interface.h"
+
+#define MAX_PACKET_ID 65535 /* according to the MQTT specification - do not change! */
+
+#if !defined(MAX_MESSAGE_HANDLERS)
+#define MAX_MESSAGE_HANDLERS 5 /* redefinable - how many subscriptions do you want? */
+#endif
+
+enum QoS { QOS0, QOS1, QOS2 };
+
+/* all failure return codes must be negative */
+enum returnCode { BUFFER_OVERFLOW = -2, FAILURE = -1, SUCCESSS = 0 };
+
+/* The Platform specific header must define the Network and Timer structures and functions
+ * which operate on them.
+ *
+typedef struct Network
+{
+ int (*mqttread)(Network*, unsigned char* read_buffer, int, int);
+ int (*mqttwrite)(Network*, unsigned char* send_buffer, int, int);
+} Network;*/
+
+/* The Timer structure must be defined in the platform specific header,
+ * and have the following functions to operate on it. */
+extern void TimerInit(Timer*);
+extern char TimerIsExpired(Timer*);
+extern void TimerCountdownMS(Timer*, unsigned int);
+extern void TimerCountdown(Timer*, unsigned int);
+extern int TimerLeftMS(Timer*);
+
+typedef struct MQTTMessage
+{
+ enum QoS qos;
+ unsigned char retained;
+ unsigned char dup;
+ unsigned short id;
+ void *payload;
+ size_t payloadlen;
+} MQTTMessage;
+
+typedef struct MessageData
+{
+ MQTTMessage* message;
+ MQTTString* topicName;
+} MessageData;
+
+typedef void (*messageHandler)(MessageData*);
+
+typedef struct MQTTClient
+{
+ unsigned int next_packetid,
+ command_timeout_ms;
+ size_t buf_size,
+ readbuf_size;
+ unsigned char *buf,
+ *readbuf;
+ unsigned int keepAliveInterval;
+ char ping_outstanding;
+ int isconnected;
+
+ struct MessageHandlers
+ {
+ const char* topicFilter;
+ void (*fp) (MessageData*);
+ } messageHandlers[MAX_MESSAGE_HANDLERS]; /* Message handlers are indexed by subscription topic */
+
+ void (*defaultMessageHandler) (MessageData*);
+
+ Network* ipstack;
+ Timer ping_timer;
+#if defined(MQTT_TASK)
+ Mutex mutex;
+ Thread thread;
+#endif
+} MQTTClient;
+
+#define DefaultClient {0, 0, 0, 0, NULL, NULL, 0, 0, 0}
+
+
+/**
+ * Create an MQTT client object
+ * @param client
+ * @param network
+ * @param command_timeout_ms
+ * @param
+ */
+DLLExport void MQTTClientInit(MQTTClient* client, Network* network, unsigned int command_timeout_ms,
+ unsigned char* sendbuf, size_t sendbuf_size, unsigned char* readbuf, size_t readbuf_size);
+
+/** MQTT Connect - send an MQTT connect packet down the network and wait for a Connack
+ * The nework object must be connected to the network endpoint before calling this
+ * @param options - connect options
+ * @return success code
+ */
+DLLExport int MQTTConnect(MQTTClient* client, MQTTPacket_connectData* options);
+
+/** MQTT Publish - send an MQTT publish packet and wait for all acks to complete for all QoSs
+ * @param client - the client object to use
+ * @param topic - the topic to publish to
+ * @param message - the message to send
+ * @return success code
+ */
+DLLExport int MQTTPublish(MQTTClient* client, const char*, MQTTMessage*);
+
+/** MQTT Subscribe - send an MQTT subscribe packet and wait for suback before returning.
+ * @param client - the client object to use
+ * @param topicFilter - the topic filter to subscribe to
+ * @param message - the message to send
+ * @return success code
+ */
+DLLExport int MQTTSubscribe(MQTTClient* client, const char* topicFilter, enum QoS, messageHandler);
+
+/** MQTT Subscribe - send an MQTT unsubscribe packet and wait for unsuback before returning.
+ * @param client - the client object to use
+ * @param topicFilter - the topic filter to unsubscribe from
+ * @return success code
+ */
+DLLExport int MQTTUnsubscribe(MQTTClient* client, const char* topicFilter);
+
+/** MQTT Disconnect - send an MQTT disconnect packet and close the connection
+ * @param client - the client object to use
+ * @return success code
+ */
+DLLExport int MQTTDisconnect(MQTTClient* client);
+
+/** MQTT Yield - MQTT background
+ * @param client - the client object to use
+ * @param time - the time, in milliseconds, to yield for
+ * @return success code
+ */
+DLLExport int MQTTYield(MQTTClient* client, int time);
+
+#if defined(MQTT_TASK)
+/** MQTT start background thread for a client. After this, MQTTYield should not be called.
+* @param client - the client object to use
+* @return success code
+*/
+DLLExport int MQTTStartTask(MQTTClient* client);
+#endif
+
+#if defined(__cplusplus)
+ }
+#endif
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnect.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnect.h
new file mode 100644
index 0000000..db90251
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnect.h
@@ -0,0 +1,136 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Xiang Rong - 442039 Add makefile to Embedded C client
+ *******************************************************************************/
+
+#ifndef MQTTCONNECT_H_
+#define MQTTCONNECT_H_
+
+#if !defined(DLLImport)
+ #define DLLImport
+#endif
+#if !defined(DLLExport)
+ #define DLLExport
+#endif
+
+
+typedef union
+{
+ unsigned char all; /**< all connect flags */
+#if defined(REVERSED)
+ struct
+ {
+ unsigned int username : 1; /**< 3.1 user name */
+ unsigned int password : 1; /**< 3.1 password */
+ unsigned int willRetain : 1; /**< will retain setting */
+ unsigned int willQoS : 2; /**< will QoS value */
+ unsigned int will : 1; /**< will flag */
+ unsigned int cleansession : 1; /**< clean session flag */
+ unsigned int : 1; /**< unused */
+ } bits;
+#else
+ struct
+ {
+ unsigned int : 1; /**< unused */
+ unsigned int cleansession : 1; /**< cleansession flag */
+ unsigned int will : 1; /**< will flag */
+ unsigned int willQoS : 2; /**< will QoS value */
+ unsigned int willRetain : 1; /**< will retain setting */
+ unsigned int password : 1; /**< 3.1 password */
+ unsigned int username : 1; /**< 3.1 user name */
+ } bits;
+#endif
+} MQTTConnectFlags; /**< connect flags byte */
+
+
+
+/**
+ * Defines the MQTT "Last Will and Testament" (LWT) settings for
+ * the connect packet.
+ */
+typedef struct
+{
+ /** The eyecatcher for this structure. must be MQTW. */
+ char struct_id[4];
+ /** The version number of this structure. Must be 0 */
+ int struct_version;
+ /** The LWT topic to which the LWT message will be published. */
+ MQTTString topicName;
+ /** The LWT payload. */
+ MQTTString message;
+ /**
+ * The retained flag for the LWT message (see MQTTAsync_message.retained).
+ */
+ unsigned char retained;
+ /**
+ * The quality of service setting for the LWT message (see
+ * MQTTAsync_message.qos and @ref qos).
+ */
+ char qos;
+} MQTTPacket_willOptions;
+
+
+#define MQTTPacket_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 0, {NULL, {0, NULL}}, {NULL, {0, NULL}}, 0, 0 }
+
+
+typedef struct
+{
+ /** The eyecatcher for this structure. must be MQTC. */
+ char struct_id[4];
+ /** The version number of this structure. Must be 0 */
+ int struct_version;
+ /** Version of MQTT to be used. 3 = 3.1 4 = 3.1.1
+ */
+ unsigned char MQTTVersion;
+ MQTTString clientID;
+ unsigned short keepAliveInterval;
+ unsigned char cleansession;
+ unsigned char willFlag;
+ MQTTPacket_willOptions will;
+ MQTTString username;
+ MQTTString password;
+} MQTTPacket_connectData;
+
+typedef union
+{
+ unsigned char all; /**< all connack flags */
+#if defined(REVERSED)
+ struct
+ {
+ unsigned int sessionpresent : 1; /**< session present flag */
+ unsigned int : 7; /**< unused */
+ } bits;
+#else
+ struct
+ {
+ unsigned int : 7; /**< unused */
+ unsigned int sessionpresent : 1; /**< session present flag */
+ } bits;
+#endif
+} MQTTConnackFlags; /**< connack flags byte */
+
+#define MQTTPacket_connectData_initializer { {'M', 'Q', 'T', 'C'}, 0, 4, {NULL, {0, NULL}}, 60, 1, 0, \
+ MQTTPacket_willOptions_initializer, {NULL, {0, NULL}}, {NULL, {0, NULL}} }
+
+DLLExport int MQTTSerialize_connect(unsigned char* buf, int buflen, MQTTPacket_connectData* options);
+DLLExport int MQTTDeserialize_connect(MQTTPacket_connectData* data, unsigned char* buf, int len);
+
+DLLExport int MQTTSerialize_connack(unsigned char* buf, int buflen, unsigned char connack_rc, unsigned char sessionPresent);
+DLLExport int MQTTDeserialize_connack(unsigned char* sessionPresent, unsigned char* connack_rc, unsigned char* buf, int buflen);
+
+DLLExport int MQTTSerialize_disconnect(unsigned char* buf, int buflen);
+DLLExport int MQTTSerialize_pingreq(unsigned char* buf, int buflen);
+
+#endif /* MQTTCONNECT_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectClient.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectClient.c
new file mode 100644
index 0000000..5f3cc29
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectClient.c
@@ -0,0 +1,214 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+/**
+ * Determines the length of the MQTT connect packet that would be produced using the supplied connect options.
+ * @param options the options to be used to build the connect packet
+ * @return the length of buffer needed to contain the serialized version of the packet
+ */
+int MQTTSerialize_connectLength(MQTTPacket_connectData* options)
+{
+ int len = 0;
+
+ FUNC_ENTRY;
+
+ if (options->MQTTVersion == 3)
+ len = 12; /* variable depending on MQTT or MQIsdp */
+ else if (options->MQTTVersion == 4)
+ len = 10;
+
+ len += MQTTstrlen(options->clientID)+2;
+ if (options->willFlag)
+ len += MQTTstrlen(options->will.topicName)+2 + MQTTstrlen(options->will.message)+2;
+ if (options->username.cstring || options->username.lenstring.data)
+ len += MQTTstrlen(options->username)+2;
+ if (options->password.cstring || options->password.lenstring.data)
+ len += MQTTstrlen(options->password)+2;
+
+ FUNC_EXIT_RC(len);
+ return len;
+}
+
+
+/**
+ * Serializes the connect options into the buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param len the length in bytes of the supplied buffer
+ * @param options the options to be used to build the connect packet
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_connect(unsigned char* buf, int buflen, MQTTPacket_connectData* options)
+{
+ unsigned char *ptr = buf;
+ MQTTHeader header = {0};
+ MQTTConnectFlags flags = {0};
+ int len = 0;
+ int rc = -1;
+
+ FUNC_ENTRY;
+ if (MQTTPacket_len(len = MQTTSerialize_connectLength(options)) > buflen)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+
+ header.byte = 0;
+ header.bits.type = CONNECT;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, len); /* write remaining length */
+
+ if (options->MQTTVersion == 4)
+ {
+ writeCString(&ptr, "MQTT");
+ writeChar(&ptr, (char) 4);
+ }
+ else
+ {
+ writeCString(&ptr, "MQIsdp");
+ writeChar(&ptr, (char) 3);
+ }
+
+ flags.all = 0;
+ flags.bits.cleansession = options->cleansession;
+ flags.bits.will = (options->willFlag) ? 1 : 0;
+ if (flags.bits.will)
+ {
+ flags.bits.willQoS = options->will.qos;
+ flags.bits.willRetain = options->will.retained;
+ }
+
+ if (options->username.cstring || options->username.lenstring.data)
+ flags.bits.username = 1;
+ if (options->password.cstring || options->password.lenstring.data)
+ flags.bits.password = 1;
+
+ writeChar(&ptr, flags.all);
+ writeInt(&ptr, options->keepAliveInterval);
+ writeMQTTString(&ptr, options->clientID);
+ if (options->willFlag)
+ {
+ writeMQTTString(&ptr, options->will.topicName);
+ writeMQTTString(&ptr, options->will.message);
+ }
+ if (flags.bits.username)
+ writeMQTTString(&ptr, options->username);
+ if (flags.bits.password)
+ writeMQTTString(&ptr, options->password);
+
+ rc = ptr - buf;
+
+ exit: FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Deserializes the supplied (wire) buffer into connack data - return code
+ * @param sessionPresent the session present flag returned (only for MQTT 3.1.1)
+ * @param connack_rc returned integer value of the connack return code
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param len the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success, 0 is failure
+ */
+int MQTTDeserialize_connack(unsigned char* sessionPresent, unsigned char* connack_rc, unsigned char* buf, int buflen)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = 0;
+ int mylen;
+ MQTTConnackFlags flags = {0};
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != CONNACK)
+ goto exit;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+ if (enddata - curdata < 2)
+ goto exit;
+
+ flags.all = readChar(&curdata);
+ *sessionPresent = flags.bits.sessionpresent;
+ *connack_rc = readChar(&curdata);
+
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes a 0-length packet into the supplied buffer, ready for writing to a socket
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer, to avoid overruns
+ * @param packettype the message type
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_zero(unsigned char* buf, int buflen, unsigned char packettype)
+{
+ MQTTHeader header = {0};
+ int rc = -1;
+ unsigned char *ptr = buf;
+
+ FUNC_ENTRY;
+ if (buflen < 2)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+ header.byte = 0;
+ header.bits.type = packettype;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, 0); /* write remaining length */
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes a disconnect packet into the supplied buffer, ready for writing to a socket
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer, to avoid overruns
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_disconnect(unsigned char* buf, int buflen)
+{
+ return MQTTSerialize_zero(buf, buflen, DISCONNECT);
+}
+
+
+/**
+ * Serializes a disconnect packet into the supplied buffer, ready for writing to a socket
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer, to avoid overruns
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_pingreq(unsigned char* buf, int buflen)
+{
+ return MQTTSerialize_zero(buf, buflen, PINGREQ);
+}
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectServer.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectServer.c
new file mode 100644
index 0000000..07c7cb5
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTConnectServer.c
@@ -0,0 +1,148 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "StackTrace.h"
+#include "MQTTPacket.h"
+#include
+
+#define min(a, b) ((a < b) ? a : b)
+
+
+/**
+ * Validates MQTT protocol name and version combinations
+ * @param protocol the MQTT protocol name as an MQTTString
+ * @param version the MQTT protocol version number, as in the connect packet
+ * @return correct MQTT combination? 1 is true, 0 is false
+ */
+int MQTTPacket_checkVersion(MQTTString* protocol, int version)
+{
+ int rc = 0;
+
+ if (version == 3 && memcmp(protocol->lenstring.data, "MQIsdp",
+ min(6, protocol->lenstring.len)) == 0)
+ rc = 1;
+ else if (version == 4 && memcmp(protocol->lenstring.data, "MQTT",
+ min(4, protocol->lenstring.len)) == 0)
+ rc = 1;
+ return rc;
+}
+
+
+/**
+ * Deserializes the supplied (wire) buffer into connect data structure
+ * @param data the connect data structure to be filled out
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param len the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success, 0 is failure
+ */
+int MQTTDeserialize_connect(MQTTPacket_connectData* data, unsigned char* buf, int len)
+{
+ MQTTHeader header = {0};
+ MQTTConnectFlags flags = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = &buf[len];
+ int rc = 0;
+ MQTTString Protocol;
+ int version;
+ int mylen = 0;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != CONNECT)
+ goto exit;
+
+ curdata += MQTTPacket_decodeBuf(curdata, &mylen); /* read remaining length */
+
+ if (!readMQTTLenString(&Protocol, &curdata, enddata) ||
+ enddata - curdata < 0) /* do we have enough data to read the protocol version byte? */
+ goto exit;
+
+ version = (int)readChar(&curdata); /* Protocol version */
+ /* If we don't recognize the protocol version, we don't parse the connect packet on the
+ * basis that we don't know what the format will be.
+ */
+ if (MQTTPacket_checkVersion(&Protocol, version))
+ {
+ flags.all = readChar(&curdata);
+ data->cleansession = flags.bits.cleansession;
+ data->keepAliveInterval = readInt(&curdata);
+ if (!readMQTTLenString(&data->clientID, &curdata, enddata))
+ goto exit;
+ data->willFlag = flags.bits.will;
+ if (flags.bits.will)
+ {
+ data->will.qos = flags.bits.willQoS;
+ data->will.retained = flags.bits.willRetain;
+ if (!readMQTTLenString(&data->will.topicName, &curdata, enddata) ||
+ !readMQTTLenString(&data->will.message, &curdata, enddata))
+ goto exit;
+ }
+ if (flags.bits.username)
+ {
+ if (enddata - curdata < 3 || !readMQTTLenString(&data->username, &curdata, enddata))
+ goto exit; /* username flag set, but no username supplied - invalid */
+ if (flags.bits.password &&
+ (enddata - curdata < 3 || !readMQTTLenString(&data->password, &curdata, enddata)))
+ goto exit; /* password flag set, but no password supplied - invalid */
+ }
+ else if (flags.bits.password)
+ goto exit; /* password flag set without username - invalid */
+ rc = 1;
+ }
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes the connack packet into the supplied buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param connack_rc the integer connack return code to be used
+ * @param sessionPresent the MQTT 3.1.1 sessionPresent flag
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_connack(unsigned char* buf, int buflen, unsigned char connack_rc, unsigned char sessionPresent)
+{
+ MQTTHeader header = {0};
+ int rc = 0;
+ unsigned char *ptr = buf;
+ MQTTConnackFlags flags = {0};
+
+ FUNC_ENTRY;
+ if (buflen < 2)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+ header.byte = 0;
+ header.bits.type = CONNACK;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, 2); /* write remaining length */
+
+ flags.all = 0;
+ flags.bits.sessionpresent = sessionPresent;
+ writeChar(&ptr, flags.all);
+ writeChar(&ptr, connack_rc);
+
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTDeserializePublish.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTDeserializePublish.c
new file mode 100644
index 0000000..dafb6a3
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTDeserializePublish.c
@@ -0,0 +1,107 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "StackTrace.h"
+#include "MQTTPacket.h"
+#include
+
+#define min(a, b) ((a < b) ? 1 : 0)
+
+/**
+ * Deserializes the supplied (wire) buffer into publish data
+ * @param dup returned integer - the MQTT dup flag
+ * @param qos returned integer - the MQTT QoS value
+ * @param retained returned integer - the MQTT retained flag
+ * @param packetid returned integer - the MQTT packet identifier
+ * @param topicName returned MQTTString - the MQTT topic in the publish
+ * @param payload returned byte buffer - the MQTT publish payload
+ * @param payloadlen returned integer - the length of the MQTT payload
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success
+ */
+int MQTTDeserialize_publish(unsigned char* dup, int* qos, unsigned char* retained, unsigned short* packetid, MQTTString* topicName,
+ unsigned char** payload, int* payloadlen, unsigned char* buf, int buflen)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = 0;
+ int mylen = 0;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != PUBLISH)
+ goto exit;
+ *dup = header.bits.dup;
+ *qos = header.bits.qos;
+ *retained = header.bits.retain;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+
+ if (!readMQTTLenString(topicName, &curdata, enddata) ||
+ enddata - curdata < 0) /* do we have enough data to read the protocol version byte? */
+ goto exit;
+
+ if (*qos > 0)
+ *packetid = readInt(&curdata);
+
+ *payloadlen = enddata - curdata;
+ *payload = curdata;
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+
+/**
+ * Deserializes the supplied (wire) buffer into an ack
+ * @param packettype returned integer - the MQTT packet type
+ * @param dup returned integer - the MQTT dup flag
+ * @param packetid returned integer - the MQTT packet identifier
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success, 0 is failure
+ */
+int MQTTDeserialize_ack(unsigned char* packettype, unsigned char* dup, unsigned short* packetid, unsigned char* buf, int buflen)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = 0;
+ int mylen;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ *dup = header.bits.dup;
+ *packettype = header.bits.type;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+
+ if (enddata - curdata < 2)
+ goto exit;
+ *packetid = readInt(&curdata);
+
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.c
new file mode 100644
index 0000000..5f78f47
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.c
@@ -0,0 +1,258 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "StackTrace.h"
+#include "MQTTPacket.h"
+
+#include
+
+
+const char* MQTTPacket_names[] =
+{
+ "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL",
+ "PUBCOMP", "SUBSCRIBE", "SUBACK", "UNSUBSCRIBE", "UNSUBACK",
+ "PINGREQ", "PINGRESP", "DISCONNECT"
+};
+
+
+const char* MQTTPacket_getName(unsigned short packetid)
+{
+ return MQTTPacket_names[packetid];
+}
+
+
+int MQTTStringFormat_connect(char* strbuf, int strbuflen, MQTTPacket_connectData* data)
+{
+ int strindex = 0;
+
+ strindex = snprintf(strbuf, strbuflen,
+ "CONNECT MQTT version %d, client id %.*s, clean session %d, keep alive %d",
+ (int)data->MQTTVersion, data->clientID.lenstring.len, data->clientID.lenstring.data,
+ (int)data->cleansession, data->keepAliveInterval);
+ if (data->willFlag)
+ strindex += snprintf(&strbuf[strindex], strbuflen - strindex,
+ ", will QoS %d, will retain %d, will topic %.*s, will message %.*s",
+ data->will.qos, data->will.retained,
+ data->will.topicName.lenstring.len, data->will.topicName.lenstring.data,
+ data->will.message.lenstring.len, data->will.message.lenstring.data);
+ if (data->username.lenstring.data && data->username.lenstring.len > 0)
+ strindex += snprintf(&strbuf[strindex], strbuflen - strindex,
+ ", user name %.*s", data->username.lenstring.len, data->username.lenstring.data);
+ if (data->password.lenstring.data && data->password.lenstring.len > 0)
+ strindex += snprintf(&strbuf[strindex], strbuflen - strindex,
+ ", password %.*s", data->password.lenstring.len, data->password.lenstring.data);
+ return strindex;
+}
+
+
+int MQTTStringFormat_connack(char* strbuf, int strbuflen, unsigned char connack_rc, unsigned char sessionPresent)
+{
+ int strindex = snprintf(strbuf, strbuflen, "CONNACK session present %d, rc %d", sessionPresent, connack_rc);
+ return strindex;
+}
+
+
+int MQTTStringFormat_publish(char* strbuf, int strbuflen, unsigned char dup, int qos, unsigned char retained,
+ unsigned short packetid, MQTTString topicName, unsigned char* payload, int payloadlen)
+{
+ int strindex = snprintf(strbuf, strbuflen,
+ "PUBLISH dup %d, QoS %d, retained %d, packet id %d, topic %.*s, payload length %d, payload %.*s",
+ dup, qos, retained, packetid,
+ (topicName.lenstring.len < 20) ? topicName.lenstring.len : 20, topicName.lenstring.data,
+ payloadlen, (payloadlen < 20) ? payloadlen : 20, payload);
+ return strindex;
+}
+
+
+int MQTTStringFormat_ack(char* strbuf, int strbuflen, unsigned char packettype, unsigned char dup, unsigned short packetid)
+{
+ int strindex = snprintf(strbuf, strbuflen, "%s, packet id %d", MQTTPacket_names[packettype], packetid);
+ if (dup)
+ strindex += snprintf(strbuf + strindex, strbuflen - strindex, ", dup %d", dup);
+ return strindex;
+}
+
+
+int MQTTStringFormat_subscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid, int count,
+ MQTTString topicFilters[], int requestedQoSs[])
+{
+ return snprintf(strbuf, strbuflen,
+ "SUBSCRIBE dup %d, packet id %d count %d topic %.*s qos %d",
+ dup, packetid, count,
+ topicFilters[0].lenstring.len, topicFilters[0].lenstring.data,
+ requestedQoSs[0]);
+}
+
+
+int MQTTStringFormat_suback(char* strbuf, int strbuflen, unsigned short packetid, int count, int* grantedQoSs)
+{
+ return snprintf(strbuf, strbuflen,
+ "SUBACK packet id %d count %d granted qos %d", packetid, count, grantedQoSs[0]);
+}
+
+
+int MQTTStringFormat_unsubscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid,
+ int count, MQTTString topicFilters[])
+{
+ return snprintf(strbuf, strbuflen,
+ "UNSUBSCRIBE dup %d, packet id %d count %d topic %.*s",
+ dup, packetid, count,
+ topicFilters[0].lenstring.len, topicFilters[0].lenstring.data);
+}
+
+
+char* MQTTFormat_toClientString(char* strbuf, int strbuflen, unsigned char* buf, int buflen)
+{
+ int index = 0;
+ int rem_length = 0;
+ MQTTHeader header = {0};
+ int strindex = 0;
+
+ header.byte = buf[index++];
+ index += MQTTPacket_decodeBuf(&buf[index], &rem_length);
+
+ switch (header.bits.type)
+ {
+ case CONNACK:
+ {
+ unsigned char sessionPresent, connack_rc;
+ if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) == 1)
+ strindex = MQTTStringFormat_connack(strbuf, strbuflen, connack_rc, sessionPresent);
+ }
+ break;
+ case PUBLISH:
+ {
+ unsigned char dup, retained, *payload;
+ unsigned short packetid;
+ int qos, payloadlen;
+ MQTTString topicName = MQTTString_initializer;
+ if (MQTTDeserialize_publish(&dup, &qos, &retained, &packetid, &topicName,
+ &payload, &payloadlen, buf, buflen) == 1)
+ strindex = MQTTStringFormat_publish(strbuf, strbuflen, dup, qos, retained, packetid,
+ topicName, payload, payloadlen);
+ }
+ break;
+ case PUBACK:
+ case PUBREC:
+ case PUBREL:
+ case PUBCOMP:
+ {
+ unsigned char packettype, dup;
+ unsigned short packetid;
+ if (MQTTDeserialize_ack(&packettype, &dup, &packetid, buf, buflen) == 1)
+ strindex = MQTTStringFormat_ack(strbuf, strbuflen, packettype, dup, packetid);
+ }
+ break;
+ case SUBACK:
+ {
+ unsigned short packetid;
+ int maxcount = 1, count = 0;
+ int grantedQoSs[1];
+ if (MQTTDeserialize_suback(&packetid, maxcount, &count, grantedQoSs, buf, buflen) == 1)
+ strindex = MQTTStringFormat_suback(strbuf, strbuflen, packetid, count, grantedQoSs);
+ }
+ break;
+ case UNSUBACK:
+ {
+ unsigned short packetid;
+ if (MQTTDeserialize_unsuback(&packetid, buf, buflen) == 1)
+ strindex = MQTTStringFormat_ack(strbuf, strbuflen, UNSUBACK, 0, packetid);
+ }
+ break;
+ case PINGREQ:
+ case PINGRESP:
+ case DISCONNECT:
+ strindex = snprintf(strbuf, strbuflen, "%s", MQTTPacket_names[header.bits.type]);
+ break;
+ }
+ return strbuf;
+}
+
+
+char* MQTTFormat_toServerString(char* strbuf, int strbuflen, unsigned char* buf, int buflen)
+{
+ int index = 0;
+ int rem_length = 0;
+ MQTTHeader header = {0};
+ int strindex = 0;
+
+ header.byte = buf[index++];
+ index += MQTTPacket_decodeBuf(&buf[index], &rem_length);
+
+ switch (header.bits.type)
+ {
+ case CONNECT:
+ {
+ MQTTPacket_connectData data;
+ int rc;
+ if ((rc = MQTTDeserialize_connect(&data, buf, buflen)) == 1)
+ strindex = MQTTStringFormat_connect(strbuf, strbuflen, &data);
+ }
+ break;
+ case PUBLISH:
+ {
+ unsigned char dup, retained, *payload;
+ unsigned short packetid;
+ int qos, payloadlen;
+ MQTTString topicName = MQTTString_initializer;
+ if (MQTTDeserialize_publish(&dup, &qos, &retained, &packetid, &topicName,
+ &payload, &payloadlen, buf, buflen) == 1)
+ strindex = MQTTStringFormat_publish(strbuf, strbuflen, dup, qos, retained, packetid,
+ topicName, payload, payloadlen);
+ }
+ break;
+ case PUBACK:
+ case PUBREC:
+ case PUBREL:
+ case PUBCOMP:
+ {
+ unsigned char packettype, dup;
+ unsigned short packetid;
+ if (MQTTDeserialize_ack(&packettype, &dup, &packetid, buf, buflen) == 1)
+ strindex = MQTTStringFormat_ack(strbuf, strbuflen, packettype, dup, packetid);
+ }
+ break;
+ case SUBSCRIBE:
+ {
+ unsigned char dup;
+ unsigned short packetid;
+ int maxcount = 1, count = 0;
+ MQTTString topicFilters[1];
+ int requestedQoSs[1];
+ if (MQTTDeserialize_subscribe(&dup, &packetid, maxcount, &count,
+ topicFilters, requestedQoSs, buf, buflen) == 1)
+ strindex = MQTTStringFormat_subscribe(strbuf, strbuflen, dup, packetid, count, topicFilters, requestedQoSs);;
+ }
+ break;
+ case UNSUBSCRIBE:
+ {
+ unsigned char dup;
+ unsigned short packetid;
+ int maxcount = 1, count = 0;
+ MQTTString topicFilters[1];
+ if (MQTTDeserialize_unsubscribe(&dup, &packetid, maxcount, &count, topicFilters, buf, buflen) == 1)
+ strindex = MQTTStringFormat_unsubscribe(strbuf, strbuflen, dup, packetid, count, topicFilters);
+ }
+ break;
+ case PINGREQ:
+ case PINGRESP:
+ case DISCONNECT:
+ strindex = snprintf(strbuf, strbuflen, "%s", MQTTPacket_names[header.bits.type]);
+ break;
+ }
+ strbuf[strbuflen] = '\0';
+ return strbuf;
+}
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.h
new file mode 100644
index 0000000..47b0c41
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTFormat.h
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#if !defined(MQTTFORMAT_H)
+#define MQTTFORMAT_H
+
+#include "StackTrace.h"
+#include "MQTTPacket.h"
+
+const char* MQTTPacket_getName(unsigned short packetid);
+int MQTTStringFormat_connect(char* strbuf, int strbuflen, MQTTPacket_connectData* data);
+int MQTTStringFormat_connack(char* strbuf, int strbuflen, unsigned char connack_rc, unsigned char sessionPresent);
+int MQTTStringFormat_publish(char* strbuf, int strbuflen, unsigned char dup, int qos, unsigned char retained,
+ unsigned short packetid, MQTTString topicName, unsigned char* payload, int payloadlen);
+int MQTTStringFormat_ack(char* strbuf, int strbuflen, unsigned char packettype, unsigned char dup, unsigned short packetid);
+int MQTTStringFormat_subscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid, int count,
+ MQTTString topicFilters[], int requestedQoSs[]);
+int MQTTStringFormat_suback(char* strbuf, int strbuflen, unsigned short packetid, int count, int* grantedQoSs);
+int MQTTStringFormat_unsubscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid,
+ int count, MQTTString topicFilters[]);
+char* MQTTFormat_toClientString(char* strbuf, int strbuflen, unsigned char* buf, int buflen);
+char* MQTTFormat_toServerString(char* strbuf, int strbuflen, unsigned char* buf, int buflen);
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.c
new file mode 100644
index 0000000..bd5f90a
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.c
@@ -0,0 +1,410 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Sergio R. Caprile - non-blocking packet read functions for stream transport
+ *******************************************************************************/
+
+#include "StackTrace.h"
+#include "MQTTPacket.h"
+
+#include
+
+/**
+ * Encodes the message length according to the MQTT algorithm
+ * @param buf the buffer into which the encoded data is written
+ * @param length the length to be encoded
+ * @return the number of bytes written to buffer
+ */
+int MQTTPacket_encode(unsigned char* buf, int length)
+{
+ int rc = 0;
+
+ FUNC_ENTRY;
+ do
+ {
+ char d = length % 128;
+ length /= 128;
+ /* if there are more digits to encode, set the top bit of this digit */
+ if (length > 0)
+ d |= 0x80;
+ buf[rc++] = d;
+ } while (length > 0);
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Decodes the message length according to the MQTT algorithm
+ * @param getcharfn pointer to function to read the next character from the data source
+ * @param value the decoded length returned
+ * @return the number of bytes read from the socket
+ */
+int MQTTPacket_decode(int (*getcharfn)(unsigned char*, int), int* value)
+{
+ unsigned char c;
+ int multiplier = 1;
+ int len = 0;
+#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4
+
+ FUNC_ENTRY;
+ *value = 0;
+ do
+ {
+ int rc = MQTTPACKET_READ_ERROR;
+
+ if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES)
+ {
+ rc = MQTTPACKET_READ_ERROR; /* bad data */
+ goto exit;
+ }
+ rc = (*getcharfn)(&c, 1);
+ if (rc != 1)
+ goto exit;
+ *value += (c & 127) * multiplier;
+ multiplier *= 128;
+ } while ((c & 128) != 0);
+exit:
+ FUNC_EXIT_RC(len);
+ return len;
+}
+
+
+int MQTTPacket_len(int rem_len)
+{
+ rem_len += 1; /* header byte */
+
+ /* now remaining_length field */
+ if (rem_len < 128)
+ rem_len += 1;
+ else if (rem_len < 16384)
+ rem_len += 2;
+ else if (rem_len < 2097151)
+ rem_len += 3;
+ else
+ rem_len += 4;
+ return rem_len;
+}
+
+
+static unsigned char* bufptr;
+
+int bufchar(unsigned char* c, int count)
+{
+ int i;
+
+ for (i = 0; i < count; ++i)
+ *c = *bufptr++;
+ return count;
+}
+
+
+int MQTTPacket_decodeBuf(unsigned char* buf, int* value)
+{
+ bufptr = buf;
+ return MQTTPacket_decode(bufchar, value);
+}
+
+
+/**
+ * Calculates an integer from two bytes read from the input buffer
+ * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
+ * @return the integer value calculated
+ */
+int readInt(unsigned char** pptr)
+{
+ unsigned char* ptr = *pptr;
+ int len = 256*(*ptr) + (*(ptr+1));
+ *pptr += 2;
+ return len;
+}
+
+
+/**
+ * Reads one character from the input buffer.
+ * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
+ * @return the character read
+ */
+char readChar(unsigned char** pptr)
+{
+ char c = **pptr;
+ (*pptr)++;
+ return c;
+}
+
+
+/**
+ * Writes one character to an output buffer.
+ * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
+ * @param c the character to write
+ */
+void writeChar(unsigned char** pptr, char c)
+{
+ **pptr = c;
+ (*pptr)++;
+}
+
+
+/**
+ * Writes an integer as 2 bytes to an output buffer.
+ * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
+ * @param anInt the integer to write
+ */
+void writeInt(unsigned char** pptr, int anInt)
+{
+ **pptr = (unsigned char)(anInt / 256);
+ (*pptr)++;
+ **pptr = (unsigned char)(anInt % 256);
+ (*pptr)++;
+}
+
+
+/**
+ * Writes a "UTF" string to an output buffer. Converts C string to length-delimited.
+ * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
+ * @param string the C string to write
+ */
+void writeCString(unsigned char** pptr, const char* string)
+{
+ int len = strlen(string);
+ writeInt(pptr, len);
+ memcpy(*pptr, string, len);
+ *pptr += len;
+}
+
+
+int getLenStringLen(char* ptr)
+{
+ int len = 256*((unsigned char)(*ptr)) + (unsigned char)(*(ptr+1));
+ return len;
+}
+
+
+void writeMQTTString(unsigned char** pptr, MQTTString mqttstring)
+{
+ if (mqttstring.lenstring.len > 0)
+ {
+ writeInt(pptr, mqttstring.lenstring.len);
+ memcpy(*pptr, mqttstring.lenstring.data, mqttstring.lenstring.len);
+ *pptr += mqttstring.lenstring.len;
+ }
+ else if (mqttstring.cstring)
+ writeCString(pptr, mqttstring.cstring);
+ else
+ writeInt(pptr, 0);
+}
+
+
+/**
+ * @param mqttstring the MQTTString structure into which the data is to be read
+ * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
+ * @param enddata pointer to the end of the data: do not read beyond
+ * @return 1 if successful, 0 if not
+ */
+int readMQTTLenString(MQTTString* mqttstring, unsigned char** pptr, unsigned char* enddata)
+{
+ int rc = 0;
+
+ FUNC_ENTRY;
+ /* the first two bytes are the length of the string */
+ if (enddata - (*pptr) > 1) /* enough length to read the integer? */
+ {
+ mqttstring->lenstring.len = readInt(pptr); /* increments pptr to point past length */
+ if (&(*pptr)[mqttstring->lenstring.len] <= enddata)
+ {
+ mqttstring->lenstring.data = (char*)*pptr;
+ *pptr += mqttstring->lenstring.len;
+ rc = 1;
+ }
+ }
+ mqttstring->cstring = NULL;
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Return the length of the MQTTstring - C string if there is one, otherwise the length delimited string
+ * @param mqttstring the string to return the length of
+ * @return the length of the string
+ */
+int MQTTstrlen(MQTTString mqttstring)
+{
+ int rc = 0;
+
+ if (mqttstring.cstring)
+ rc = strlen(mqttstring.cstring);
+ else
+ rc = mqttstring.lenstring.len;
+ return rc;
+}
+
+
+/**
+ * Compares an MQTTString to a C string
+ * @param a the MQTTString to compare
+ * @param bptr the C string to compare
+ * @return boolean - equal or not
+ */
+int MQTTPacket_equals(MQTTString* a, char* bptr)
+{
+ int alen = 0,
+ blen = 0;
+ char *aptr;
+
+ if (a->cstring)
+ {
+ aptr = a->cstring;
+ alen = strlen(a->cstring);
+ }
+ else
+ {
+ aptr = a->lenstring.data;
+ alen = a->lenstring.len;
+ }
+ blen = strlen(bptr);
+
+ return (alen == blen) && (strncmp(aptr, bptr, alen) == 0);
+}
+
+
+/**
+ * Helper function to read packet data from some source into a buffer
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param getfn pointer to a function which will read any number of bytes from the needed source
+ * @return integer MQTT packet type, or -1 on error
+ * @note the whole message must fit into the caller's buffer
+ */
+int MQTTPacket_read(unsigned char* buf, int buflen, int (*getfn)(unsigned char*, int))
+{
+ int rc = -1;
+ MQTTHeader header = {0};
+ int len = 0;
+ int rem_len = 0;
+
+ /* 1. read the header byte. This has the packet type in it */
+ if ((*getfn)(buf, 1) != 1)
+ goto exit;
+
+ len = 1;
+ /* 2. read the remaining length. This is variable in itself */
+ MQTTPacket_decode(getfn, &rem_len);
+ len += MQTTPacket_encode(buf + 1, rem_len); /* put the original remaining length back into the buffer */
+
+ /* 3. read the rest of the buffer using a callback to supply the rest of the data */
+ if((rem_len + len) > buflen)
+ goto exit;
+ if ((*getfn)(buf + len, rem_len) != rem_len)
+ goto exit;
+
+ header.byte = buf[0];
+ rc = header.bits.type;
+exit:
+ return rc;
+}
+
+/**
+ * Decodes the message length according to the MQTT algorithm, non-blocking
+ * @param trp pointer to a transport structure holding what is needed to solve getting data from it
+ * @param value the decoded length returned
+ * @return integer the number of bytes read from the socket, 0 for call again, or -1 on error
+ */
+static int MQTTPacket_decodenb(MQTTTransport *trp)
+{
+ unsigned char c;
+ int rc = MQTTPACKET_READ_ERROR;
+
+ FUNC_ENTRY;
+ if(trp->len == 0){ /* initialize on first call */
+ trp->multiplier = 1;
+ trp->rem_len = 0;
+ }
+ do {
+ int frc;
+ if (++(trp->len) > MAX_NO_OF_REMAINING_LENGTH_BYTES)
+ goto exit;
+ if ((frc=(*trp->getfn)(trp->sck, &c, 1)) == -1)
+ goto exit;
+ if (frc == 0){
+ rc = 0;
+ goto exit;
+ }
+ trp->rem_len += (c & 127) * trp->multiplier;
+ trp->multiplier *= 128;
+ } while ((c & 128) != 0);
+ rc = trp->len;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+/**
+ * Helper function to read packet data from some source into a buffer, non-blocking
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param trp pointer to a transport structure holding what is needed to solve getting data from it
+ * @return integer MQTT packet type, 0 for call again, or -1 on error
+ * @note the whole message must fit into the caller's buffer
+ */
+int MQTTPacket_readnb(unsigned char* buf, int buflen, MQTTTransport *trp)
+{
+ int rc = -1, frc;
+ MQTTHeader header = {0};
+
+ switch(trp->state){
+ default:
+ trp->state = 0;
+ /*FALLTHROUGH*/
+ case 0:
+ /* read the header byte. This has the packet type in it */
+ if ((frc=(*trp->getfn)(trp->sck, buf, 1)) == -1)
+ goto exit;
+ if (frc == 0)
+ return 0;
+ trp->len = 0;
+ ++trp->state;
+ /*FALLTHROUGH*/
+ /* read the remaining length. This is variable in itself */
+ case 1:
+ if((frc=MQTTPacket_decodenb(trp)) == MQTTPACKET_READ_ERROR)
+ goto exit;
+ if(frc == 0)
+ return 0;
+ trp->len = 1 + MQTTPacket_encode(buf + 1, trp->rem_len); /* put the original remaining length back into the buffer */
+ if((trp->rem_len + trp->len) > buflen)
+ goto exit;
+ ++trp->state;
+ /*FALLTHROUGH*/
+ case 2:
+ /* read the rest of the buffer using a callback to supply the rest of the data */
+ if ((frc=(*trp->getfn)(trp->sck, buf + trp->len, trp->rem_len)) == -1)
+ goto exit;
+ if (frc == 0)
+ return 0;
+ trp->rem_len -= frc;
+ trp->len += frc;
+ if(trp->rem_len)
+ return 0;
+
+ header.byte = buf[0];
+ rc = header.bits.type;
+ break;
+ }
+
+exit:
+ trp->state = 0;
+ return rc;
+}
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.h
new file mode 100644
index 0000000..588966d
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPacket.h
@@ -0,0 +1,133 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Xiang Rong - 442039 Add makefile to Embedded C client
+ *******************************************************************************/
+
+#ifndef MQTTPACKET_H_
+#define MQTTPACKET_H_
+
+#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */
+extern "C" {
+#endif
+
+#if defined(WIN32_DLL) || defined(WIN64_DLL)
+ #define DLLImport __declspec(dllimport)
+ #define DLLExport __declspec(dllexport)
+#elif defined(LINUX_SO)
+ #define DLLImport extern
+ #define DLLExport __attribute__ ((visibility ("default")))
+#else
+ #define DLLImport
+ #define DLLExport
+#endif
+
+enum errors
+{
+ MQTTPACKET_BUFFER_TOO_SHORT = -2,
+ MQTTPACKET_READ_ERROR = -1,
+ MQTTPACKET_READ_COMPLETE
+};
+
+enum msgTypes
+{
+ CONNECT = 1, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL,
+ PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK,
+ PINGREQ, PINGRESP, DISCONNECT
+};
+
+/**
+ * Bitfields for the MQTT header byte.
+ */
+typedef union
+{
+ unsigned char byte; /**< the whole byte */
+#if defined(REVERSED)
+ struct
+ {
+ unsigned int type : 4; /**< message type nibble */
+ unsigned int dup : 1; /**< DUP flag bit */
+ unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */
+ unsigned int retain : 1; /**< retained flag bit */
+ } bits;
+#else
+ struct
+ {
+ unsigned int retain : 1; /**< retained flag bit */
+ unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */
+ unsigned int dup : 1; /**< DUP flag bit */
+ unsigned int type : 4; /**< message type nibble */
+ } bits;
+#endif
+} MQTTHeader;
+
+typedef struct
+{
+ int len;
+ char* data;
+} MQTTLenString;
+
+typedef struct
+{
+ char* cstring;
+ MQTTLenString lenstring;
+} MQTTString;
+
+#define MQTTString_initializer {NULL, {0, NULL}}
+
+int MQTTstrlen(MQTTString mqttstring);
+
+#include "MQTTConnect.h"
+#include "MQTTPublish.h"
+#include "MQTTSubscribe.h"
+#include "MQTTUnsubscribe.h"
+#include "MQTTFormat.h"
+
+int MQTTSerialize_ack(unsigned char* buf, int buflen, unsigned char type, unsigned char dup, unsigned short packetid);
+int MQTTDeserialize_ack(unsigned char* packettype, unsigned char* dup, unsigned short* packetid, unsigned char* buf, int buflen);
+
+int MQTTPacket_len(int rem_len);
+int MQTTPacket_equals(MQTTString* a, char* b);
+
+int MQTTPacket_encode(unsigned char* buf, int length);
+int MQTTPacket_decode(int (*getcharfn)(unsigned char*, int), int* value);
+int MQTTPacket_decodeBuf(unsigned char* buf, int* value);
+
+int readInt(unsigned char** pptr);
+char readChar(unsigned char** pptr);
+void writeChar(unsigned char** pptr, char c);
+void writeInt(unsigned char** pptr, int anInt);
+int readMQTTLenString(MQTTString* mqttstring, unsigned char** pptr, unsigned char* enddata);
+void writeCString(unsigned char** pptr, const char* string);
+void writeMQTTString(unsigned char** pptr, MQTTString mqttstring);
+
+DLLExport int MQTTPacket_read(unsigned char* buf, int buflen, int (*getfn)(unsigned char*, int));
+
+typedef struct {
+ int (*getfn)(void *, unsigned char*, int); /* must return -1 for error, 0 for call again, or the number of bytes read */
+ void *sck; /* pointer to whatever the system may use to identify the transport */
+ int multiplier;
+ int rem_len;
+ int len;
+ char state;
+}MQTTTransport;
+
+int MQTTPacket_readnb(unsigned char* buf, int buflen, MQTTTransport *trp);
+
+#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
+}
+#endif
+
+
+#endif /* MQTTPACKET_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPublish.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPublish.h
new file mode 100644
index 0000000..ebe479d
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTPublish.h
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Xiang Rong - 442039 Add makefile to Embedded C client
+ *******************************************************************************/
+
+#ifndef MQTTPUBLISH_H_
+#define MQTTPUBLISH_H_
+
+#if !defined(DLLImport)
+ #define DLLImport
+#endif
+#if !defined(DLLExport)
+ #define DLLExport
+#endif
+
+DLLExport int MQTTSerialize_publish(unsigned char* buf, int buflen, unsigned char dup, int qos, unsigned char retained, unsigned short packetid,
+ MQTTString topicName, unsigned char* payload, int payloadlen);
+
+DLLExport int MQTTDeserialize_publish(unsigned char* dup, int* qos, unsigned char* retained, unsigned short* packetid, MQTTString* topicName,
+ unsigned char** payload, int* payloadlen, unsigned char* buf, int len);
+
+DLLExport int MQTTSerialize_puback(unsigned char* buf, int buflen, unsigned short packetid);
+DLLExport int MQTTSerialize_pubrel(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid);
+DLLExport int MQTTSerialize_pubcomp(unsigned char* buf, int buflen, unsigned short packetid);
+
+#endif /* MQTTPUBLISH_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSerializePublish.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSerializePublish.c
new file mode 100644
index 0000000..77a58b5
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSerializePublish.c
@@ -0,0 +1,169 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Ian Craggs - fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=453144
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+
+/**
+ * Determines the length of the MQTT publish packet that would be produced using the supplied parameters
+ * @param qos the MQTT QoS of the publish (packetid is omitted for QoS 0)
+ * @param topicName the topic name to be used in the publish
+ * @param payloadlen the length of the payload to be sent
+ * @return the length of buffer needed to contain the serialized version of the packet
+ */
+int MQTTSerialize_publishLength(int qos, MQTTString topicName, int payloadlen)
+{
+ int len = 0;
+
+ len += 2 + MQTTstrlen(topicName) + payloadlen;
+ if (qos > 0)
+ len += 2; /* packetid */
+ return len;
+}
+
+
+/**
+ * Serializes the supplied publish data into the supplied buffer, ready for sending
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param dup integer - the MQTT dup flag
+ * @param qos integer - the MQTT QoS value
+ * @param retained integer - the MQTT retained flag
+ * @param packetid integer - the MQTT packet identifier
+ * @param topicName MQTTString - the MQTT topic in the publish
+ * @param payload byte buffer - the MQTT publish payload
+ * @param payloadlen integer - the length of the MQTT payload
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTSerialize_publish(unsigned char* buf, int buflen, unsigned char dup, int qos, unsigned char retained, unsigned short packetid,
+ MQTTString topicName, unsigned char* payload, int payloadlen)
+{
+ unsigned char *ptr = buf;
+ MQTTHeader header = {0};
+ int rem_len = 0;
+ int rc = 0;
+
+ FUNC_ENTRY;
+ if (MQTTPacket_len(rem_len = MQTTSerialize_publishLength(qos, topicName, payloadlen)) > buflen)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+
+ header.bits.type = PUBLISH;
+ header.bits.dup = dup;
+ header.bits.qos = qos;
+ header.bits.retain = retained;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, rem_len); /* write remaining length */;
+
+ writeMQTTString(&ptr, topicName);
+
+ if (qos > 0)
+ writeInt(&ptr, packetid);
+
+ memcpy(ptr, payload, payloadlen);
+ ptr += payloadlen;
+
+ rc = ptr - buf;
+
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+
+/**
+ * Serializes the ack packet into the supplied buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param type the MQTT packet type
+ * @param dup the MQTT dup flag
+ * @param packetid the MQTT packet identifier
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_ack(unsigned char* buf, int buflen, unsigned char packettype, unsigned char dup, unsigned short packetid)
+{
+ MQTTHeader header = {0};
+ int rc = 0;
+ unsigned char *ptr = buf;
+
+ FUNC_ENTRY;
+ if (buflen < 4)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+ header.bits.type = packettype;
+ header.bits.dup = dup;
+ header.bits.qos = (packettype == PUBREL) ? 1 : 0;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, 2); /* write remaining length */
+ writeInt(&ptr, packetid);
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes a puback packet into the supplied buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param packetid integer - the MQTT packet identifier
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_puback(unsigned char* buf, int buflen, unsigned short packetid)
+{
+ return MQTTSerialize_ack(buf, buflen, PUBACK, 0, packetid);
+}
+
+
+/**
+ * Serializes a pubrel packet into the supplied buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param dup integer - the MQTT dup flag
+ * @param packetid integer - the MQTT packet identifier
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_pubrel(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid)
+{
+ return MQTTSerialize_ack(buf, buflen, PUBREL, dup, packetid);
+}
+
+
+/**
+ * Serializes a pubrel packet into the supplied buffer.
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param packetid integer - the MQTT packet identifier
+ * @return serialized length, or error if 0
+ */
+int MQTTSerialize_pubcomp(unsigned char* buf, int buflen, unsigned short packetid)
+{
+ return MQTTSerialize_ack(buf, buflen, PUBCOMP, 0, packetid);
+}
+
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribe.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribe.h
new file mode 100644
index 0000000..aa91826
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribe.h
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Xiang Rong - 442039 Add makefile to Embedded C client
+ *******************************************************************************/
+
+#ifndef MQTTSUBSCRIBE_H_
+#define MQTTSUBSCRIBE_H_
+
+#if !defined(DLLImport)
+ #define DLLImport
+#endif
+#if !defined(DLLExport)
+ #define DLLExport
+#endif
+
+DLLExport int MQTTSerialize_subscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid,
+ int count, MQTTString topicFilters[], int requestedQoSs[]);
+
+DLLExport int MQTTDeserialize_subscribe(unsigned char* dup, unsigned short* packetid,
+ int maxcount, int* count, MQTTString topicFilters[], int requestedQoSs[], unsigned char* buf, int len);
+
+DLLExport int MQTTSerialize_suback(unsigned char* buf, int buflen, unsigned short packetid, int count, int* grantedQoSs);
+
+DLLExport int MQTTDeserialize_suback(unsigned short* packetid, int maxcount, int* count, int grantedQoSs[], unsigned char* buf, int len);
+
+
+#endif /* MQTTSUBSCRIBE_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeClient.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeClient.c
new file mode 100644
index 0000000..57a0613
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeClient.c
@@ -0,0 +1,137 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+/**
+ * Determines the length of the MQTT subscribe packet that would be produced using the supplied parameters
+ * @param count the number of topic filter strings in topicFilters
+ * @param topicFilters the array of topic filter strings to be used in the publish
+ * @return the length of buffer needed to contain the serialized version of the packet
+ */
+int MQTTSerialize_subscribeLength(int count, MQTTString topicFilters[])
+{
+ int i;
+ int len = 2; /* packetid */
+
+ for (i = 0; i < count; ++i)
+ len += 2 + MQTTstrlen(topicFilters[i]) + 1; /* length + topic + req_qos */
+ return len;
+}
+
+
+/**
+ * Serializes the supplied subscribe data into the supplied buffer, ready for sending
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied bufferr
+ * @param dup integer - the MQTT dup flag
+ * @param packetid integer - the MQTT packet identifier
+ * @param count - number of members in the topicFilters and reqQos arrays
+ * @param topicFilters - array of topic filter names
+ * @param requestedQoSs - array of requested QoS
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTSerialize_subscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid, int count,
+ MQTTString topicFilters[], int requestedQoSs[])
+{
+ unsigned char *ptr = buf;
+ MQTTHeader header = {0};
+ int rem_len = 0;
+ int rc = 0;
+ int i = 0;
+
+ FUNC_ENTRY;
+ if (MQTTPacket_len(rem_len = MQTTSerialize_subscribeLength(count, topicFilters)) > buflen)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+
+ header.byte = 0;
+ header.bits.type = SUBSCRIBE;
+ header.bits.dup = dup;
+ header.bits.qos = 1;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, rem_len); /* write remaining length */;
+
+ writeInt(&ptr, packetid);
+
+ for (i = 0; i < count; ++i)
+ {
+ writeMQTTString(&ptr, topicFilters[i]);
+ writeChar(&ptr, requestedQoSs[i]);
+ }
+
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+
+/**
+ * Deserializes the supplied (wire) buffer into suback data
+ * @param packetid returned integer - the MQTT packet identifier
+ * @param maxcount - the maximum number of members allowed in the grantedQoSs array
+ * @param count returned integer - number of members in the grantedQoSs array
+ * @param grantedQoSs returned array of integers - the granted qualities of service
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success, 0 is failure
+ */
+int MQTTDeserialize_suback(unsigned short* packetid, int maxcount, int* count, int grantedQoSs[], unsigned char* buf, int buflen)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = 0;
+ int mylen;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != SUBACK)
+ goto exit;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+ if (enddata - curdata < 2)
+ goto exit;
+
+ *packetid = readInt(&curdata);
+
+ *count = 0;
+ while (curdata < enddata)
+ {
+ if (*count > maxcount)
+ {
+ rc = -1;
+ goto exit;
+ }
+ grantedQoSs[(*count)++] = readChar(&curdata);
+ }
+
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeServer.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeServer.c
new file mode 100644
index 0000000..5579645
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTSubscribeServer.c
@@ -0,0 +1,112 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+
+/**
+ * Deserializes the supplied (wire) buffer into subscribe data
+ * @param dup integer returned - the MQTT dup flag
+ * @param packetid integer returned - the MQTT packet identifier
+ * @param maxcount - the maximum number of members allowed in the topicFilters and requestedQoSs arrays
+ * @param count - number of members in the topicFilters and requestedQoSs arrays
+ * @param topicFilters - array of topic filter names
+ * @param requestedQoSs - array of requested QoS
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTDeserialize_subscribe(unsigned char* dup, unsigned short* packetid, int maxcount, int* count, MQTTString topicFilters[],
+ int requestedQoSs[], unsigned char* buf, int buflen)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = -1;
+ int mylen = 0;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != SUBSCRIBE)
+ goto exit;
+ *dup = header.bits.dup;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+
+ *packetid = readInt(&curdata);
+
+ *count = 0;
+ while (curdata < enddata)
+ {
+ if (!readMQTTLenString(&topicFilters[*count], &curdata, enddata))
+ goto exit;
+ if (curdata >= enddata) /* do we have enough data to read the req_qos version byte? */
+ goto exit;
+ requestedQoSs[*count] = readChar(&curdata);
+ (*count)++;
+ }
+
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes the supplied suback data into the supplied buffer, ready for sending
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param packetid integer - the MQTT packet identifier
+ * @param count - number of members in the grantedQoSs array
+ * @param grantedQoSs - array of granted QoS
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTSerialize_suback(unsigned char* buf, int buflen, unsigned short packetid, int count, int* grantedQoSs)
+{
+ MQTTHeader header = {0};
+ int rc = -1;
+ unsigned char *ptr = buf;
+ int i;
+
+ FUNC_ENTRY;
+ if (buflen < 2 + count)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+ header.byte = 0;
+ header.bits.type = SUBACK;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, 2 + count); /* write remaining length */
+
+ writeInt(&ptr, packetid);
+
+ for (i = 0; i < count; ++i)
+ writeChar(&ptr, grantedQoSs[i]);
+
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribe.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribe.h
new file mode 100644
index 0000000..355ca9a
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribe.h
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Xiang Rong - 442039 Add makefile to Embedded C client
+ *******************************************************************************/
+
+#ifndef MQTTUNSUBSCRIBE_H_
+#define MQTTUNSUBSCRIBE_H_
+
+#if !defined(DLLImport)
+ #define DLLImport
+#endif
+#if !defined(DLLExport)
+ #define DLLExport
+#endif
+
+DLLExport int MQTTSerialize_unsubscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid,
+ int count, MQTTString topicFilters[]);
+
+DLLExport int MQTTDeserialize_unsubscribe(unsigned char* dup, unsigned short* packetid, int max_count, int* count, MQTTString topicFilters[],
+ unsigned char* buf, int len);
+
+DLLExport int MQTTSerialize_unsuback(unsigned char* buf, int buflen, unsigned short packetid);
+
+DLLExport int MQTTDeserialize_unsuback(unsigned short* packetid, unsigned char* buf, int len);
+
+#endif /* MQTTUNSUBSCRIBE_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeClient.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeClient.c
new file mode 100644
index 0000000..e7ec530
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeClient.c
@@ -0,0 +1,106 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+/**
+ * Determines the length of the MQTT unsubscribe packet that would be produced using the supplied parameters
+ * @param count the number of topic filter strings in topicFilters
+ * @param topicFilters the array of topic filter strings to be used in the publish
+ * @return the length of buffer needed to contain the serialized version of the packet
+ */
+int MQTTSerialize_unsubscribeLength(int count, MQTTString topicFilters[])
+{
+ int i;
+ int len = 2; /* packetid */
+
+ for (i = 0; i < count; ++i)
+ len += 2 + MQTTstrlen(topicFilters[i]); /* length + topic*/
+ return len;
+}
+
+
+/**
+ * Serializes the supplied unsubscribe data into the supplied buffer, ready for sending
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @param dup integer - the MQTT dup flag
+ * @param packetid integer - the MQTT packet identifier
+ * @param count - number of members in the topicFilters array
+ * @param topicFilters - array of topic filter names
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTSerialize_unsubscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid,
+ int count, MQTTString topicFilters[])
+{
+ unsigned char *ptr = buf;
+ MQTTHeader header = {0};
+ int rem_len = 0;
+ int rc = -1;
+ int i = 0;
+
+ FUNC_ENTRY;
+ if (MQTTPacket_len(rem_len = MQTTSerialize_unsubscribeLength(count, topicFilters)) > buflen)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+
+ header.byte = 0;
+ header.bits.type = UNSUBSCRIBE;
+ header.bits.dup = dup;
+ header.bits.qos = 1;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, rem_len); /* write remaining length */;
+
+ writeInt(&ptr, packetid);
+
+ for (i = 0; i < count; ++i)
+ writeMQTTString(&ptr, topicFilters[i]);
+
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Deserializes the supplied (wire) buffer into unsuback data
+ * @param packetid returned integer - the MQTT packet identifier
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return error code. 1 is success, 0 is failure
+ */
+int MQTTDeserialize_unsuback(unsigned short* packetid, unsigned char* buf, int buflen)
+{
+ unsigned char type = 0;
+ unsigned char dup = 0;
+ int rc = 0;
+
+ FUNC_ENTRY;
+ rc = MQTTDeserialize_ack(&type, &dup, packetid, buf, buflen);
+ if (type == UNSUBACK)
+ rc = 1;
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeServer.c b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeServer.c
new file mode 100644
index 0000000..42b6102
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/MQTTUnsubscribeServer.c
@@ -0,0 +1,102 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#include "MQTTPacket.h"
+#include "StackTrace.h"
+
+#include
+
+
+/**
+ * Deserializes the supplied (wire) buffer into unsubscribe data
+ * @param dup integer returned - the MQTT dup flag
+ * @param packetid integer returned - the MQTT packet identifier
+ * @param maxcount - the maximum number of members allowed in the topicFilters and requestedQoSs arrays
+ * @param count - number of members in the topicFilters and requestedQoSs arrays
+ * @param topicFilters - array of topic filter names
+ * @param buf the raw buffer data, of the correct length determined by the remaining length field
+ * @param buflen the length in bytes of the data in the supplied buffer
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTDeserialize_unsubscribe(unsigned char* dup, unsigned short* packetid, int maxcount, int* count, MQTTString topicFilters[],
+ unsigned char* buf, int len)
+{
+ MQTTHeader header = {0};
+ unsigned char* curdata = buf;
+ unsigned char* enddata = NULL;
+ int rc = 0;
+ int mylen = 0;
+
+ FUNC_ENTRY;
+ header.byte = readChar(&curdata);
+ if (header.bits.type != UNSUBSCRIBE)
+ goto exit;
+ *dup = header.bits.dup;
+
+ curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */
+ enddata = curdata + mylen;
+
+ *packetid = readInt(&curdata);
+
+ *count = 0;
+ while (curdata < enddata)
+ {
+ if (!readMQTTLenString(&topicFilters[*count], &curdata, enddata))
+ goto exit;
+ (*count)++;
+ }
+
+ rc = 1;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
+/**
+ * Serializes the supplied unsuback data into the supplied buffer, ready for sending
+ * @param buf the buffer into which the packet will be serialized
+ * @param buflen the length in bytes of the supplied buffer
+ * @param packetid integer - the MQTT packet identifier
+ * @return the length of the serialized data. <= 0 indicates error
+ */
+int MQTTSerialize_unsuback(unsigned char* buf, int buflen, unsigned short packetid)
+{
+ MQTTHeader header = {0};
+ int rc = 0;
+ unsigned char *ptr = buf;
+
+ FUNC_ENTRY;
+ if (buflen < 2)
+ {
+ rc = MQTTPACKET_BUFFER_TOO_SHORT;
+ goto exit;
+ }
+ header.byte = 0;
+ header.bits.type = UNSUBACK;
+ writeChar(&ptr, header.byte); /* write header */
+
+ ptr += MQTTPacket_encode(ptr, 2); /* write remaining length */
+
+ writeInt(&ptr, packetid);
+
+ rc = ptr - buf;
+exit:
+ FUNC_EXIT_RC(rc);
+ return rc;
+}
+
+
diff --git a/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/StackTrace.h b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/StackTrace.h
new file mode 100644
index 0000000..2808a0d
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/MQTTPacket/src/StackTrace.h
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2014 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Ian Craggs - initial API and implementation and/or initial documentation
+ * Ian Craggs - fix for bug #434081
+ *******************************************************************************/
+
+#ifndef STACKTRACE_H_
+#define STACKTRACE_H_
+
+#include
+#define NOSTACKTRACE 1
+
+#if defined(NOSTACKTRACE)
+#define FUNC_ENTRY
+#define FUNC_ENTRY_NOLOG
+#define FUNC_ENTRY_MED
+#define FUNC_ENTRY_MAX
+#define FUNC_EXIT
+#define FUNC_EXIT_NOLOG
+#define FUNC_EXIT_MED
+#define FUNC_EXIT_MAX
+#define FUNC_EXIT_RC(x)
+#define FUNC_EXIT_MED_RC(x)
+#define FUNC_EXIT_MAX_RC(x)
+
+#else
+
+#if defined(WIN32)
+#define inline __inline
+#define FUNC_ENTRY StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MINIMUM)
+#define FUNC_ENTRY_NOLOG StackTrace_entry(__FUNCTION__, __LINE__, -1)
+#define FUNC_ENTRY_MED StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MEDIUM)
+#define FUNC_ENTRY_MAX StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MAXIMUM)
+#define FUNC_EXIT StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MINIMUM)
+#define FUNC_EXIT_NOLOG StackTrace_exit(__FUNCTION__, __LINE__, -1)
+#define FUNC_EXIT_MED StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MEDIUM)
+#define FUNC_EXIT_MAX StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MAXIMUM)
+#define FUNC_EXIT_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MINIMUM)
+#define FUNC_EXIT_MED_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MEDIUM)
+#define FUNC_EXIT_MAX_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MAXIMUM)
+#else
+#define FUNC_ENTRY StackTrace_entry(__func__, __LINE__, TRACE_MINIMUM)
+#define FUNC_ENTRY_NOLOG StackTrace_entry(__func__, __LINE__, -1)
+#define FUNC_ENTRY_MED StackTrace_entry(__func__, __LINE__, TRACE_MEDIUM)
+#define FUNC_ENTRY_MAX StackTrace_entry(__func__, __LINE__, TRACE_MAXIMUM)
+#define FUNC_EXIT StackTrace_exit(__func__, __LINE__, NULL, TRACE_MINIMUM)
+#define FUNC_EXIT_NOLOG StackTrace_exit(__func__, __LINE__, NULL, -1)
+#define FUNC_EXIT_MED StackTrace_exit(__func__, __LINE__, NULL, TRACE_MEDIUM)
+#define FUNC_EXIT_MAX StackTrace_exit(__func__, __LINE__, NULL, TRACE_MAXIMUM)
+#define FUNC_EXIT_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MINIMUM)
+#define FUNC_EXIT_MED_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MEDIUM)
+#define FUNC_EXIT_MAX_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MAXIMUM)
+
+void StackTrace_entry(const char* name, int line, int trace);
+void StackTrace_exit(const char* name, int line, void* return_value, int trace);
+
+void StackTrace_printStack(FILE* dest);
+char* StackTrace_get(unsigned long);
+
+#endif
+
+#endif
+
+
+
+
+#endif /* STACKTRACE_H_ */
diff --git a/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.c b/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.c
new file mode 100644
index 0000000..f8450a8
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.c
@@ -0,0 +1,169 @@
+//*****************************************************************************
+//! \file mqtt_interface.c
+//! \brief Paho MQTT to WIZnet Chip interface implement file.
+//! \details The process of porting an interface to use paho MQTT.
+//! \version 1.0.0
+//! \date 2016/12/06
+//! \par Revision history
+//! <2016/12/06> 1st Release
+//!
+//! \author Peter Bang & Justin Kim
+//! \copyright
+//!
+//! Copyright (c) 2016, WIZnet Co., LTD.
+//! All rights reserved.
+//!
+//! Redistribution and use in source and binary forms, with or without
+//! modification, are permitted provided that the following conditions
+//! are met:
+//!
+//! * Redistributions of source code must retain the above copyright
+//! notice, this list of conditions and the following disclaimer.
+//! * Redistributions in binary form must reproduce the above copyright
+//! notice, this list of conditions and the following disclaimer in the
+//! documentation and/or other materials provided with the distribution.
+//! * Neither the name of the nor the names of its
+//! contributors may be used to endorse or promote products derived
+//! from this software without specific prior written permission.
+//!
+//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
+//
+//*****************************************************************************
+
+#include "mqtt_interface.h"
+#include "wizchip_conf.h"
+
+unsigned long MilliTimer;
+
+/*
+ * @brief MQTT MilliTimer handler
+ * @note MUST BE register to your system 1m Tick timer handler.
+ */
+void MilliTimer_Handler(void) {
+ MilliTimer++;
+}
+
+/*
+ * @brief Timer Initialize
+ * @param timer : pointer to a Timer structure
+ * that contains the configuration information for the Timer.
+ */
+void TimerInit(Timer* timer) {
+ timer->end_time = 0;
+}
+
+/*
+ * @brief expired Timer
+ * @param timer : pointer to a Timer structure
+ * that contains the configuration information for the Timer.
+ */
+char TimerIsExpired(Timer* timer) {
+ long left = timer->end_time - MilliTimer;
+ return (left < 0);
+}
+
+/*
+ * @brief Countdown millisecond Timer
+ * @param timer : pointer to a Timer structure
+ * that contains the configuration information for the Timer.
+ * timeout : setting timeout millisecond.
+ */
+void TimerCountdownMS(Timer* timer, unsigned int timeout) {
+ timer->end_time = MilliTimer + timeout;
+}
+
+/*
+ * @brief Countdown second Timer
+ * @param timer : pointer to a Timer structure
+ * that contains the configuration information for the Timer.
+ * timeout : setting timeout millisecond.
+ */
+void TimerCountdown(Timer* timer, unsigned int timeout) {
+ timer->end_time = MilliTimer + (timeout * 1000);
+}
+
+/*
+ * @brief left millisecond Timer
+ * @param timer : pointer to a Timer structure
+ * that contains the configuration information for the Timer.
+ */
+int TimerLeftMS(Timer* timer) {
+ long left = timer->end_time - MilliTimer;
+ return (left < 0) ? 0 : left;
+}
+
+/*
+ * @brief New network setting
+ * @param n : pointer to a Network structure
+ * that contains the configuration information for the Network.
+ * sn : socket number where x can be (0..7).
+ * @retval None
+ */
+void NewNetwork(Network* n, int sn) {
+ n->my_socket = sn;
+ n->mqttread = w5x00_read;
+ n->mqttwrite = w5x00_write;
+ n->disconnect = w5x00_disconnect;
+}
+
+/*
+ * @brief read function
+ * @param n : pointer to a Network structure
+ * that contains the configuration information for the Network.
+ * buffer : pointer to a read buffer.
+ * len : buffer length.
+ */
+int w5x00_read(Network* n, unsigned char* buffer, int len)
+{
+
+ if((getSn_SR(n->my_socket) == SOCK_ESTABLISHED) && (getSn_RX_RSR(n->my_socket)>0))
+ return recv(n->my_socket, buffer, len);
+}
+
+/*
+ * @brief write function
+ * @param n : pointer to a Network structure
+ * that contains the configuration information for the Network.
+ * buffer : pointer to a read buffer.
+ * len : buffer length.
+ */
+int w5x00_write(Network* n, unsigned char* buffer, int len)
+{
+ if(getSn_SR(n->my_socket) == SOCK_ESTABLISHED)
+ return send(n->my_socket, buffer, len);
+}
+
+/*
+ * @brief disconnect function
+ * @param n : pointer to a Network structure
+ * that contains the configuration information for the Network.
+ */
+void w5x00_disconnect(Network* n)
+{
+ disconnect(n->my_socket);
+}
+
+/*
+ * @brief connect network function
+ * @param n : pointer to a Network structure
+ * that contains the configuration information for the Network.
+ * ip : server iP.
+ * port : server port.
+ */
+int ConnectNetwork(Network* n, char* ip, int port)
+{
+ uint8_t myport = 12345;
+
+ socket(n->my_socket,Sn_MR_TCP,myport,0);
+ connect(n->my_socket,ip,port);
+}
diff --git a/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.h b/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.h
new file mode 100644
index 0000000..47cc692
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/MQTT/mqtt_interface.h
@@ -0,0 +1,260 @@
+//*****************************************************************************
+//! \file mqtt_interface.h
+//! \brief Paho MQTT to WIZnet Chip interface Header file.
+//! \details The process of porting an interface to use paho MQTT.
+//! \version 1.0.0
+//! \date 2016/12/06
+//! \par Revision history
+//! <2016/12/06> 1st Release
+//!
+//! \author Peter Bang & Justin Kim
+//! \copyright
+//!
+//! Copyright (c) 2016, WIZnet Co., LTD.
+//! All rights reserved.
+//!
+//! Redistribution and use in source and binary forms, with or without
+//! modification, are permitted provided that the following conditions
+//! are met:
+//!
+//! * Redistributions of source code must retain the above copyright
+//! notice, this list of conditions and the following disclaimer.
+//! * Redistributions in binary form must reproduce the above copyright
+//! notice, this list of conditions and the following disclaimer in the
+//! documentation and/or other materials provided with the distribution.
+//! * Neither the name of the nor the names of its
+//! contributors may be used to endorse or promote products derived
+//! from this software without specific prior written permission.
+//!
+//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
+//
+//*****************************************************************************
+
+/* MQTT subscribe Example.... W5500 + STM32F103(IoT board)
+//Include: Board configuration
+#include "IoTEVB.h"
+
+//Include: MCU peripheral Library
+#include "stm32f10x_rcc.h"
+#include "stm32f10x.h"
+
+//Include: W5500 iolibrary
+#include "w5500.h"
+#include "wizchip_conf.h"
+#include "misc.h"
+
+//Include: Internet iolibrary
+#include "MQTTClient.h"
+
+//Include: MCU Specific W5500 driver
+#include "W5500HardwareDriver.h"
+
+//Include: Standard IO Library
+#include
+
+//Socket number defines
+#define TCP_SOCKET 0
+
+//Receive Buffer Size define
+#define BUFFER_SIZE 2048
+
+//Global variables
+unsigned char targetIP[4] = {}; // mqtt server IP
+unsigned int targetPort = 1883; // mqtt server port
+uint8_t mac_address[6] = {};
+wiz_NetInfo gWIZNETINFO = { .mac = {}, //user MAC
+ .ip = {}, //user IP
+ .sn = {},
+ .gw = {},
+ .dns = {},
+ .dhcp = NETINFO_STATIC};
+
+unsigned char tempBuffer[BUFFER_SIZE] = {};
+
+struct opts_struct
+{
+ char* clientid;
+ int nodelimiter;
+ char* delimiter;
+ enum QoS qos;
+ char* username;
+ char* password;
+ char* host;
+ int port;
+ int showtopics;
+} opts ={ (char*)"stdout-subscriber", 0, (char*)"\n", QOS0, NULL, NULL, targetIP, targetPort, 0 };
+
+
+// @brief messageArrived callback function
+void messageArrived(MessageData* md)
+{
+ unsigned char testbuffer[100];
+ MQTTMessage* message = md->message;
+
+ if (opts.showtopics)
+ {
+ memcpy(testbuffer,(char*)message->payload,(int)message->payloadlen);
+ *(testbuffer + (int)message->payloadlen + 1) = "\n";
+ printf("%s\r\n",testbuffer);
+ }
+
+ if (opts.nodelimiter)
+ printf("%.*s", (int)message->payloadlen, (char*)message->payload);
+ else
+ printf("%.*s%s", (int)message->payloadlen, (char*)message->payload, opts.delimiter);
+}
+
+
+// @brief 1 millisecond Tick Timer setting
+void NVIC_configuration(void)
+{
+ NVIC_InitTypeDef NVIC_InitStructure;
+ SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
+ SysTick_Config(72000);
+ NVIC_InitStructure.NVIC_IRQChannel = SysTick_IRQn;
+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; // Highest priority
+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
+ NVIC_Init(&NVIC_InitStructure);
+}
+
+// @brief 1 millisecond Tick Timer Handler setting
+void SysTick_Handler(void)
+{
+ MilliTimer_Handler();
+}
+
+int main(void)
+{
+ led_ctrl led1,led2;
+ int i;
+ int rc = 0;
+ unsigned char buf[100];
+ //Usart initialization for Debug.
+ USART1Initialze();
+ printf("USART initialized.\n\r");
+
+ I2C1Initialize();
+ printf("I2C initialized.\n\r");
+
+ MACEEP_Read(mac_address,0xfa,6);
+
+ printf("Mac address\n\r");
+ for(i = 0 ; i < 6 ; i++)
+ {
+ printf("%02x ",mac_address[i]);
+ }
+ printf("\n\r");
+
+ //LED initialization.
+ led_initialize();
+ led1 = led2 = ON;
+
+ led2Ctrl(led2);
+ led1Ctrl(led1);
+
+ //W5500 initialization.
+ W5500HardwareInitilize();
+ printf("W5500 hardware interface initialized.\n\r");
+
+ W5500Initialze();
+ printf("W5500 IC initialized.\n\r");
+
+ //Set network informations
+ wizchip_setnetinfo(&gWIZNETINFO);
+
+ setSHAR(mac_address);
+
+ print_network_information();
+
+ Network n;
+ MQTTClient c;
+
+ NewNetwork(&n, TCP_SOCKET);
+ ConnectNetwork(&n, targetIP, targetPort);
+ MQTTClientInit(&c,&n,1000,buf,100,tempBuffer,2048);
+
+ MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+ data.willFlag = 0;
+ data.MQTTVersion = 3;
+ data.clientID.cstring = opts.clientid;
+ data.username.cstring = opts.username;
+ data.password.cstring = opts.password;
+
+ data.keepAliveInterval = 60;
+ data.cleansession = 1;
+
+ rc = MQTTConnect(&c, &data);
+ printf("Connected %d\r\n", rc);
+ opts.showtopics = 1;
+
+ printf("Subscribing to %s\r\n", "hello/wiznet");
+ rc = MQTTSubscribe(&c, "hello/wiznet", opts.qos, messageArrived);
+ printf("Subscribed %d\r\n", rc);
+
+ while(1)
+ {
+ MQTTYield(&c, data.keepAliveInterval);
+ }
+}
+*/
+
+#ifndef __MQTT_INTERFACE_H_
+#define __MQTT_INTERFACE_H_
+
+/*
+ * @brief MQTT MilliTimer handler
+ * @note MUST BE register to your system 1m Tick timer handler
+ */
+void MilliTimer_Handler(void);
+
+/*
+ * @brief Timer structure
+ */
+typedef struct Timer Timer;
+struct Timer {
+ unsigned long systick_period;
+ unsigned long end_time;
+};
+
+/*
+ * @brief Network structure
+ */
+typedef struct Network Network;
+struct Network
+{
+ int my_socket;
+ int (*mqttread) (Network*, unsigned char*, int, int);
+ int (*mqttwrite) (Network*, unsigned char*, int, int);
+ void (*disconnect) (Network*);
+};
+
+/*
+ * @brief Timer function
+ */
+void TimerInit(Timer*);
+char TimerIsExpired(Timer*);
+void TimerCountdownMS(Timer*, unsigned int);
+void TimerCountdown(Timer*, unsigned int);
+int TimerLeftMS(Timer*);
+
+/*
+ * @brief Network interface porting
+ */
+int w5x00_read(Network*, unsigned char*, int);
+int w5x00_write(Network*, unsigned char*, int);
+void w5x00_disconnect(Network*);
+void NewNetwork(Network* n, int sn);
+int ConnectNetwork(Network*, char*, int);
+
+#endif //__MQTT_INTERFACE_H_
diff --git a/WIZ550S2E_App/src/Internet/SNMP/snmp.c b/WIZ550S2E_App/src/Internet/SNMP/snmp.c
new file mode 100644
index 0000000..b705097
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNMP/snmp.c
@@ -0,0 +1,927 @@
+#include
+#include
+#include
+#include
+#include
+
+#include "socket.h"
+#include "snmp.h"
+#include "snmp_custom.h"
+
+/********************************************************************************************/
+/* SNMP : Functions declaration */
+/********************************************************************************************/
+// SNMP Parsing functions
+int32_t findEntry(uint8_t *oid, int32_t len);
+int32_t getOID(int32_t id, uint8_t *oid, uint8_t *len);
+int32_t getValue( uint8_t *vptr, int32_t vlen);
+int32_t getEntry(int32_t id, uint8_t *dataType, void *ptr, int32_t *len);
+int32_t setEntry(int32_t id, void *val, int32_t vlen, uint8_t dataType, int32_t index);
+int32_t makeTrapVariableBindings(dataEntryType *oid_data, void *ptr, uint32_t *len);
+
+int32_t parseLength(const uint8_t *msg, int32_t *len);
+int32_t parseTLV(const uint8_t *msg, int32_t index, tlvStructType *tlv);
+void insertRespLen(int32_t reqStart, int32_t respStart, int32_t size);
+int32_t parseVarBind(int32_t reqType, int32_t index);
+int32_t parseSequence(int32_t reqType, int32_t index);
+int32_t parseSequenceOf(int32_t reqType);
+int32_t parseRequest();
+int32_t parseCommunity();
+int32_t parseVersion();
+int32_t parseSNMPMessage();
+
+// Debugging function
+#ifdef _SNMP_DEBUG_
+void dumpCode(uint8_t* header, uint8_t* tail, uint8_t *buff, int32_t len);
+#endif
+
+// Utils
+void ipToByteArray(int8_t *ip, uint8_t *pDes);
+
+/********************************************************************************************/
+/* SNMP : Variable declaration */
+/********************************************************************************************/
+// SNMP message structures
+struct messageStruct request_msg;
+struct messageStruct response_msg;
+
+// SNMP Time counter
+static time_t startTime = 0;
+volatile uint32_t snmp_tick_10ms = 0; //volatile uint32_t snmp_tick_1ms = 0;
+
+// SNMP Sockets
+static uint8_t SOCK_SNMP_AGENT;
+static uint8_t SOCK_SNMP_TRAP;
+
+uint8_t packet_trap[MAX_TRAPMSG_LEN] = {0,};
+uint8_t errorStatus, errorIndex;
+
+
+/********************************************************************************************/
+/* SNMP : Time handler */
+/********************************************************************************************/
+void currentUptime(void *ptr, uint8_t *len)
+{
+ time_t curTime = getSNMPTimeTick();
+
+ //*(uint32_t *)ptr = (uint32_t)(curTime - startTime) / 10; // calculation for 1ms tick
+ *(uint32_t *)ptr = (uint32_t)(curTime - startTime); // calculation for 10ms tick
+ *len = 4;
+}
+
+void SNMP_time_handler(void)
+{
+ //snmp_tick_1ms++;
+ snmp_tick_10ms++;
+}
+
+uint32_t getSNMPTimeTick(void)
+{
+ //return snmp_tick_1ms;
+ return snmp_tick_10ms;
+}
+
+
+/********************************************************************************************/
+/* SNMP : Library Part */
+/********************************************************************************************/
+/**
+ * @addtogroup snmp_module
+ * @{
+ */
+
+/**
+ * Initialize SNMP Daemon.
+ * This should be called just one time at first time
+ *
+ * @param none
+ * @return none
+ */
+void snmpd_init(uint8_t * managerIP, uint8_t * agentIP, uint8_t sn_agent, uint8_t sn_trap)
+{
+#ifdef _SNMP_DEBUG_
+ printf("\r\n - SNMP : Start SNMP Agent Daemon\r\n");
+#endif
+ SOCK_SNMP_AGENT = sn_agent;
+ SOCK_SNMP_TRAP = sn_trap;
+
+ if((SOCK_SNMP_AGENT > _WIZCHIP_SOCK_NUM_) || (SOCK_SNMP_TRAP > _WIZCHIP_SOCK_NUM_)) return;
+
+ startTime = getSNMPTimeTick(); // Start time (unit: 10ms)
+ initTable(); // Settings for OID entry values
+
+ initial_Trap(managerIP, agentIP);
+
+/*
+ // Example Codes for SNMP Trap
+ {
+ dataEntryType enterprise_oid = {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0x9b, 0x19, 0x01, 0x00},
+ SNMPDTYPE_OBJ_ID, 0x0a, {"\x2b\x06\x01\x04\x01\x81\x9b\x19\x10\x00"}, NULL, NULL};
+
+ dataEntryType trap_oid1 = {8, {0x2b, 6, 1, 4, 1, 0, 11, 0}, SNMPDTYPE_OCTET_STRING, 30, {""}, NULL, NULL};
+ dataEntryType trap_oid2 = {8, {0x2b, 6, 1, 4, 1, 0, 12, 0}, SNMPDTYPE_INTEGER, 4, {""}, NULL, NULL};
+
+ strcpy((char *)trap_oid1.u.octetstring, "Alert!!!"); // String added
+ trap_oid2.u.intval = 123456; // Integer value added
+
+ // Generic Trap: warmStart
+ snmp_sendTrap((void *)"192.168.0.214", (void *)"192.168.0.112", (void *)"public", enterprise_oid, SNMPTRAP_WARMSTART, 0, 0);
+
+ // Enterprise-Specific Trap
+ snmp_sendTrap((void *)"192.168.0.214", (void *)"192.168.0.112", (void *)"public", enterprise_oid, 6, 0, 2, &trap_oid1, &trap_oid2);
+ }
+*/
+}
+
+
+/**
+ * SNMP Process Handler.
+ * UDP Socket and SNMP Agent transaction handling.
+ *
+ * @param none
+ * @return none
+ */
+
+int32_t snmpd_run(void)
+{
+ int32_t ret;
+ int32_t len = 0;
+
+ uint8_t svr_addr[6];
+ uint16_t svr_port;
+
+ if(SOCK_SNMP_AGENT > _WIZCHIP_SOCK_NUM_) return -99;
+
+ switch(getSn_SR(SOCK_SNMP_AGENT))
+ {
+ case SOCK_UDP :
+ if ( (len = getSn_RX_RSR(SOCK_SNMP_AGENT)) > 0)
+ {
+ request_msg.len= recvfrom(SOCK_SNMP_AGENT, request_msg.buffer, len, svr_addr, &svr_port);
+ }
+ else
+ {
+ request_msg.len = 0;
+ }
+
+ if (request_msg.len > 0)
+ {
+#ifdef _SNMP_DEBUG_
+ dumpCode((void *)"\r\n[Request]\r\n", (void *)"\r\n", request_msg.buffer, request_msg.len);
+#endif
+ // Initialize
+ request_msg.index = 0;
+ response_msg.index = 0;
+ errorStatus = errorIndex = 0;
+ memset(response_msg.buffer, 0x00, MAX_SNMPMSG_LEN);
+
+ // Received message parsing and send response process
+ if (parseSNMPMessage() != -1)
+ {
+ sendto(SOCK_SNMP_AGENT, response_msg.buffer, response_msg.index, svr_addr, svr_port);
+ }
+
+#ifdef _SNMP_DEBUG_
+ dumpCode((void *)"\r\n[Response]\r\n", (void *)"\r\n", response_msg.buffer, response_msg.index);
+#endif
+ }
+ break;
+
+ case SOCK_CLOSED :
+ if((ret = socket(SOCK_SNMP_AGENT, Sn_MR_UDP, PORT_SNMP_AGENT, 0x00)) != SOCK_SNMP_AGENT)
+ return ret;
+#ifdef _SNMP_DEBUG_
+ printf(" - [%d] UDP Socket for SNMP Agent, port [%d]\r\n", SOCK_SNMP_AGENT, PORT_SNMP_AGENT);
+#endif
+ break;
+
+ default :
+ break;
+ }
+
+
+ return 1;
+}
+
+
+int32_t findEntry(uint8_t *oid, int32_t len)
+{
+ int32_t i;
+
+ for (i = 0 ; i < maxData ; i++)
+ {
+ if (len == snmpData[i].oidlen)
+ {
+ if (!memcmp(snmpData[i].oid, oid, len)) return(i);
+ }
+ }
+
+ return OID_NOT_FOUND;
+}
+
+
+int32_t getOID(int32_t id, uint8_t *oid, uint8_t *len)
+{
+ int32_t j;
+
+ if (!((id >= 0) && (id < maxData))) return INVALID_ENTRY_ID;
+
+ *len = snmpData[id].oidlen;
+
+ for (j = 0 ; j < *len ; j++)
+ {
+ oid[j] = snmpData[id].oid[j];
+ }
+
+ return SNMP_SUCCESS;
+}
+
+
+int32_t getValue( uint8_t *vptr, int32_t vlen)
+{
+ int32_t index = 0;
+ int32_t value = 0;
+
+ while (index < vlen)
+ {
+ if (index != 0) value <<= 8;
+ value |= vptr[index++];
+ }
+
+ return value;
+}
+
+
+int32_t getEntry(int32_t id, uint8_t *dataType, void *ptr, int32_t *len)
+{
+ uint8_t * ptr_8;
+ int32_t value;
+
+ uint8_t * string;
+ int32_t j;
+
+ if (!((id >= 0) && (id < maxData))) return INVALID_ENTRY_ID;
+
+ *dataType = snmpData[id].dataType;
+
+ switch(*dataType)
+ {
+ case SNMPDTYPE_OCTET_STRING :
+ case SNMPDTYPE_OBJ_ID :
+ {
+ string = ptr;
+
+ if (snmpData[id].getfunction != NULL)
+ {
+ snmpData[id].getfunction( (void *)&snmpData[id].u.octetstring, &snmpData[id].dataLen );
+ }
+
+ if ( (*dataType)==SNMPDTYPE_OCTET_STRING )
+ {
+ snmpData[id].dataLen = (uint8_t)strlen((char const*)&snmpData[id].u.octetstring);
+ }
+
+ *len = snmpData[id].dataLen;
+ for (j = 0 ; j < *len ; j++)
+ {
+ string[j] = snmpData[id].u.octetstring[j];
+ }
+ }
+ break;
+
+ case SNMPDTYPE_INTEGER :
+ case SNMPDTYPE_TIME_TICKS :
+ case SNMPDTYPE_COUNTER :
+ case SNMPDTYPE_GAUGE :
+ {
+ if (snmpData[id].getfunction != NULL)
+ {
+ snmpData[id].getfunction( (void *)&snmpData[id].u.intval, &snmpData[id].dataLen );
+ }
+
+ if(snmpData[id].dataLen) *len = snmpData[id].dataLen;
+ else *len = sizeof(uint32_t);
+
+ /*
+ // Original code (IAR, STM32)
+ // This code is not working in NXP+LPCXpresso (32-bit pointer operation error)
+ value = (int32_t *)ptr;
+ *value = HTONL(snmpData[id].u.intval);
+ */
+
+ ptr_8 = ptr;
+ //value = HTONL(snmpData[id].u.intval); // Endian convert when processing 32bit pointer operation
+ value = snmpData[id].u.intval;
+
+ for (j = 0 ; j < *len ; j++)
+ {
+ ptr_8[j] = (uint8_t)((value >> ((*len-j-1)*8)));
+ }
+ }
+ break;
+
+ default :
+ return INVALID_DATA_TYPE;
+ }
+
+ return SNMP_SUCCESS;
+}
+
+
+int32_t setEntry(int32_t id, void *val, int32_t vlen, uint8_t dataType, int32_t index)
+{
+
+ int32_t retStatus=OID_NOT_FOUND;
+ int32_t j;
+
+ if (snmpData[id].dataType != dataType)
+ {
+ errorStatus = BAD_VALUE;
+ errorIndex = index;
+ return INVALID_DATA_TYPE;
+ }
+
+ switch(snmpData[id].dataType)
+ {
+ case SNMPDTYPE_OCTET_STRING :
+ case SNMPDTYPE_OBJ_ID :
+ {
+ uint8_t *string = val;
+ for (j = 0 ; j < vlen ; j++)
+ {
+ snmpData[id].u.octetstring[j] = string[j];
+ }
+ snmpData[id].dataLen = vlen;
+ }
+ retStatus = SNMP_SUCCESS;
+ break;
+
+ case SNMPDTYPE_INTEGER :
+ case SNMPDTYPE_TIME_TICKS :
+ case SNMPDTYPE_COUNTER :
+ case SNMPDTYPE_GAUGE :
+ {
+ snmpData[id].u.intval = getValue( (uint8_t *)val, vlen);
+ snmpData[id].dataLen = vlen;
+
+ if (snmpData[id].setfunction != NULL)
+ {
+ snmpData[id].setfunction(snmpData[id].u.intval);
+ }
+
+ }
+ retStatus = SNMP_SUCCESS;
+ break;
+
+ default :
+ retStatus = INVALID_DATA_TYPE;
+ break;
+
+ }
+
+ return retStatus;
+}
+
+
+int32_t parseLength(const uint8_t *msg, int32_t *len)
+{
+ int32_t i=1;
+
+ if (msg[0] & 0x80)
+ {
+ int32_t tlen = (msg[0] & 0x7f) - 1;
+ *len = msg[i++];
+
+ while (tlen--)
+ {
+ *len <<= 8;
+ *len |= msg[i++];
+ }
+ }
+ else
+ {
+ *len = msg[0];
+ }
+
+ return i;
+}
+
+
+int32_t parseTLV(const uint8_t *msg, int32_t index, tlvStructType *tlv)
+{
+ int32_t Llen = 0;
+
+ tlv->start = index;
+
+ Llen = parseLength((const uint8_t *)&msg[index+1], &tlv->len );
+
+ tlv->vstart = index + Llen + 1;
+
+ switch (msg[index])
+ {
+ case SNMPDTYPE_SEQUENCE:
+ case GET_REQUEST:
+ case GET_NEXT_REQUEST:
+ case SET_REQUEST:
+ tlv->nstart = tlv->vstart;
+ break;
+ default:
+ tlv->nstart = tlv->vstart + tlv->len;
+ break;
+ }
+
+ return 0;
+}
+
+
+void insertRespLen(int32_t reqStart, int32_t respStart, int32_t size)
+{
+ int32_t indexStart, lenLength;
+ uint32_t mask = 0xff;
+ int32_t shift = 0;
+
+ if (request_msg.buffer[reqStart+1] & 0x80)
+ {
+ lenLength = request_msg.buffer[reqStart+1] & 0x7f;
+ indexStart = respStart+2;
+
+ while (lenLength--)
+ {
+ response_msg.buffer[indexStart+lenLength] =
+ (uint8_t)((size & mask) >> shift);
+ shift+=8;
+ mask <<= shift;
+ }
+ }
+ else
+ {
+ response_msg.buffer[respStart+1] = (uint8_t)(size & 0xff);
+ }
+}
+
+int32_t parseVarBind(int32_t reqType, int32_t index)
+{
+ int32_t seglen = 0, id;
+ tlvStructType name, value;
+ int32_t size = 0;
+
+ //extern const int32_t maxData;
+
+ parseTLV(request_msg.buffer, request_msg.index, &name);
+
+ if ( request_msg.buffer[name.start] != SNMPDTYPE_OBJ_ID ) return -1;
+
+ id = findEntry(&request_msg.buffer[name.vstart], name.len);
+
+ if ((reqType == GET_REQUEST) || (reqType == SET_REQUEST))
+ {
+ seglen = name.nstart - name.start;
+ COPY_SEGMENT(name);
+ size = seglen;
+ }
+ else if (reqType == GET_NEXT_REQUEST)
+ {
+ response_msg.buffer[response_msg.index] = request_msg.buffer[name.start];
+
+ if (++id >= maxData)
+ {
+ id = OID_NOT_FOUND;
+ seglen = name.nstart - name.start;
+ COPY_SEGMENT(name);
+ size = seglen;
+ }
+ else
+ {
+ request_msg.index += name.nstart - name.start;
+
+ getOID(id, &response_msg.buffer[response_msg.index+2], &response_msg.buffer[response_msg.index+1]);
+
+ seglen = response_msg.buffer[response_msg.index+1]+2;
+ response_msg.index += seglen ;
+ size = seglen;
+ }
+ }
+
+ parseTLV(request_msg.buffer, request_msg.index, &value);
+
+ if (id != OID_NOT_FOUND)
+ {
+ uint8_t dataType;
+ int32_t len;
+
+ if ((reqType == GET_REQUEST) || (reqType == GET_NEXT_REQUEST))
+ {
+ getEntry(id, &dataType, &response_msg.buffer[response_msg.index+2], &len);
+
+ response_msg.buffer[response_msg.index] = dataType;
+ response_msg.buffer[response_msg.index+1] = len;
+ seglen = (2 + len);
+ response_msg.index += seglen;
+
+ request_msg.index += (value.nstart - value.start);
+
+ }
+ else if (reqType == SET_REQUEST)
+ {
+ setEntry(id, &request_msg.buffer[value.vstart], value.len, request_msg.buffer[value.start], index);
+ seglen = value.nstart - value.start;
+ COPY_SEGMENT(value);
+ }
+ }
+ else
+ {
+ seglen = value.nstart - value.start;
+ COPY_SEGMENT(value);
+
+ errorIndex = index;
+ errorStatus = NO_SUCH_NAME;
+ }
+
+ size += seglen;
+
+ return size;
+}
+
+
+int32_t parseSequence(int32_t reqType, int32_t index)
+{
+ int32_t seglen;
+ tlvStructType seq;
+ int32_t size = 0, respLoc;
+
+ parseTLV(request_msg.buffer, request_msg.index, &seq);
+
+ if ( request_msg.buffer[seq.start] != SNMPDTYPE_SEQUENCE ) return -1;
+
+ seglen = seq.vstart - seq.start;
+ respLoc = response_msg.index;
+ COPY_SEGMENT(seq);
+
+ size = parseVarBind( reqType, index );
+ insertRespLen(seq.start, respLoc, size);
+ size += seglen;
+
+ return size;
+}
+
+
+int32_t parseSequenceOf(int32_t reqType)
+{
+ int32_t seglen;
+ tlvStructType seqof;
+ int32_t size = 0, respLoc;
+ int32_t index = 0;
+
+ parseTLV(request_msg.buffer, request_msg.index, &seqof);
+
+ if ( request_msg.buffer[seqof.start] != SNMPDTYPE_SEQUENCE_OF ) return -1;
+
+ seglen = seqof.vstart - seqof.start;
+ respLoc = response_msg.index;
+ COPY_SEGMENT(seqof);
+
+ while (request_msg.index < request_msg.len)
+ {
+ size += parseSequence( reqType, index++ );
+ }
+
+ insertRespLen(seqof.start, respLoc, size);
+
+ return size;
+}
+
+
+int32_t parseRequest()
+{
+ int32_t ret, seglen;
+ tlvStructType snmpreq, requestid, errStatus, errIndex;
+ int32_t size = 0, respLoc, reqType;
+
+ parseTLV(request_msg.buffer, request_msg.index, &snmpreq);
+
+ reqType = request_msg.buffer[snmpreq.start];
+
+ if ( !VALID_REQUEST(reqType) ) return -1;
+
+ seglen = snmpreq.vstart - snmpreq.start;
+ respLoc = snmpreq.start;
+ size += seglen;
+ COPY_SEGMENT(snmpreq);
+
+ response_msg.buffer[snmpreq.start] = GET_RESPONSE;
+
+ parseTLV(request_msg.buffer, request_msg.index, &requestid);
+ seglen = requestid.nstart - requestid.start;
+ size += seglen;
+ COPY_SEGMENT(requestid);
+
+ parseTLV(request_msg.buffer, request_msg.index, &errStatus);
+ seglen = errStatus.nstart - errStatus.start;
+ size += seglen;
+ COPY_SEGMENT(errStatus);
+
+ parseTLV(request_msg.buffer, request_msg.index, &errIndex);
+ seglen = errIndex.nstart - errIndex.start;
+ size += seglen;
+ COPY_SEGMENT(errIndex);
+
+ ret = parseSequenceOf(reqType);
+ if (ret == -1) return -1;
+ else size += ret;
+
+ insertRespLen(snmpreq.start, respLoc, size);
+
+ if (errorStatus)
+ {
+ response_msg.buffer[errStatus.vstart] = errorStatus;
+ response_msg.buffer[errIndex.vstart] = errorIndex + 1;
+ }
+
+ return size;
+}
+
+
+int32_t parseCommunity()
+{
+ int32_t seglen;
+ tlvStructType community;
+ int32_t size=0;
+
+ parseTLV(request_msg.buffer, request_msg.index, &community);
+
+ if (!((request_msg.buffer[community.start] == SNMPDTYPE_OCTET_STRING) && (community.len == COMMUNITY_SIZE)))
+ {
+ return -1;
+ }
+
+ if (!memcmp(&request_msg.buffer[community.vstart], (int8_t *)COMMUNITY, COMMUNITY_SIZE))
+ {
+ seglen = community.nstart - community.start;
+ size += seglen;
+ COPY_SEGMENT(community);
+
+ size += parseRequest();
+ }
+ else
+ {
+ return -1;
+ }
+
+ return size;
+}
+
+
+int32_t parseVersion()
+{
+ int32_t size = 0, seglen;
+ tlvStructType tlv;
+
+ size = parseTLV(request_msg.buffer, request_msg.index, &tlv);
+
+ if (!((request_msg.buffer[tlv.start] == SNMPDTYPE_INTEGER) && (request_msg.buffer[tlv.vstart] == SNMP_V1)))
+ return -1;
+
+ seglen = tlv.nstart - tlv.start;
+ size += seglen;
+ COPY_SEGMENT(tlv);
+ size = parseCommunity();
+
+ if (size == -1) return size;
+ else return (size + seglen);
+}
+
+
+int32_t parseSNMPMessage()
+{
+ int32_t size = 0, seglen, respLoc;
+ tlvStructType tlv;
+
+ parseTLV(request_msg.buffer, request_msg.index, &tlv);
+
+ if (request_msg.buffer[tlv.start] != SNMPDTYPE_SEQUENCE_OF) return -1;
+
+ seglen = tlv.vstart - tlv.start;
+ respLoc = tlv.start;
+ COPY_SEGMENT(tlv);
+
+ size = parseVersion();
+
+ if (size == -1) return -1;
+ else size += seglen;
+
+ insertRespLen(tlv.start, respLoc, size);
+
+ return 0;
+}
+
+void ipToByteArray(int8_t *ip, uint8_t *pDes)
+{
+ uint32_t i, ip1=0, ip2=0, ip3=0, ip4=0;
+ int8_t buff[32];
+ uint32_t len = (uint32_t)strlen((char const*)ip);
+ strcpy((char *)buff, (char const*)ip);
+
+ for (i=0; ioidlen;
+
+ for (j = 0 ; j < oid_data->oidlen ; j++)
+ {
+ ((uint8_t*)ptr)[j+4] = oid_data->oid[j];
+ }
+
+ switch(oid_data->dataType)
+ {
+ case SNMPDTYPE_OCTET_STRING :
+ case SNMPDTYPE_OBJ_ID :
+ {
+ uint8_t *string = &((uint8_t*)ptr)[4+oid_data->oidlen+2];
+
+ if ( oid_data->dataType==SNMPDTYPE_OCTET_STRING )
+ {
+ oid_data->dataLen = (uint8_t)strlen((char const*)&oid_data->u.octetstring);
+ }
+ for (j = 0 ; j < oid_data->dataLen ; j++)
+ {
+ string[j] = oid_data->u.octetstring[j];
+ }
+
+ ((uint8_t*)ptr)[4+oid_data->oidlen] = oid_data->dataType;
+ ((uint8_t*)ptr)[4+oid_data->oidlen+1] = oid_data->dataLen;
+ ((uint8_t*)ptr)[1] = 2 + oid_data->oidlen + 2 + oid_data->dataLen;
+ *len = 4 + oid_data->oidlen + 2 + oid_data->dataLen;
+ }
+ break;
+
+ case SNMPDTYPE_INTEGER :
+ case SNMPDTYPE_TIME_TICKS :
+ case SNMPDTYPE_COUNTER :
+ case SNMPDTYPE_GAUGE :
+ {
+ oid_data->dataLen = 4;
+
+ *(int32_t*)(&((uint8_t*)ptr)[4+oid_data->oidlen+2]) = HTONL(oid_data->u.intval);
+
+ ((uint8_t*)ptr)[4+oid_data->oidlen] = oid_data->dataType;
+ ((uint8_t*)ptr)[4+oid_data->oidlen+1] = oid_data->dataLen;
+ ((uint8_t*)ptr)[1] = 2 + oid_data->oidlen + 2 + oid_data->dataLen;
+ *len = 4 + oid_data->oidlen + 2 + oid_data->dataLen;
+ }
+ break;
+
+ default :
+ return INVALID_DATA_TYPE;
+ }
+
+ return SNMP_SUCCESS;
+}
+
+
+int32_t snmp_sendTrap(uint8_t * managerIP, uint8_t * agentIP, int8_t* community, dataEntryType enterprise_oid, uint32_t genericTrap, uint32_t specificTrap, uint32_t va_count, ...)
+{
+ uint32_t i;
+ int32_t packet_index = 0;
+ int32_t packet_buff1 = 0;
+ int32_t packet_buff2 = 0;
+ int32_t packet_buff3 = 0;
+
+ va_list ap;
+ uint32_t length_var_bindings = 0;
+ uint32_t length_buff = 0;
+
+ //SNMP Trap packet generation
+ packet_trap[packet_index++] = 0x30; // ASN.1 Header
+
+ packet_trap[packet_index] = 0xff; // pdu_length, temp
+ packet_buff1 = packet_index++;
+
+ packet_trap[packet_index++] = 0x02; // Version
+ packet_trap[packet_index++] = 0x01;
+ packet_trap[packet_index++] = 0x00;
+
+ packet_trap[packet_index++] = 0x04; // Community
+ packet_trap[packet_index++] = (uint8_t)strlen((char const*)community);
+ memcpy(&(packet_trap[packet_index]), community, strlen((char const*)community));
+
+ packet_index = packet_index + (uint8_t)strlen((char const*)community);
+
+ packet_trap[packet_index++] = 0xa4; // trap
+ packet_trap[packet_index] = 0xff; // length, temp
+ packet_buff2 = packet_index++;
+
+ packet_trap[packet_index++] = 0x06; // enterprise_oid
+ packet_trap[packet_index++] = enterprise_oid.oidlen;
+ for (i=0; i> 24) & 0x000000ff) | \
+ (((x) >> 8) & 0x0000ff00) | \
+ (((x) << 8) & 0x00ff0000) | \
+ (((x) << 24) & 0xff000000))
+#endif
+
+typedef struct {
+ uint8_t oidlen;
+ uint8_t oid[MAX_OID];
+ uint8_t dataType;
+ uint8_t dataLen;
+ union {
+ uint8_t octetstring[MAX_STRING];
+ uint32_t intval;
+ } u;
+ void (*getfunction)(void *, uint8_t *);
+ void (*setfunction)(int32_t);
+} dataEntryType;
+
+struct messageStruct {
+ uint8_t buffer[MAX_SNMPMSG_LEN];
+ int32_t len;
+ int32_t index;
+};
+
+typedef struct {
+ int32_t start; /* Absolute Index of the TLV */
+ int32_t len; /* The L value of the TLV */
+ int32_t vstart; /* Absolute Index of this TLV's Value */
+ int32_t nstart; /* Absolute Index of the next TLV */
+} tlvStructType;
+
+
+/********************************************************************************************/
+/* SNMP : Functions */
+/********************************************************************************************/
+// SNMP Main functions
+void snmpd_init(uint8_t * managerIP, uint8_t * agentIP, uint8_t sn_agent, uint8_t sn_trap);
+int32_t snmpd_run(void);
+int32_t snmp_sendTrap(uint8_t * managerIP, uint8_t * agentIP, int8_t* community, dataEntryType enterprise_oid, uint32_t genericTrap, uint32_t specificTrap, uint32_t va_count, ...);
+
+// SNMP Time handler functions
+void SNMP_time_handler(void);
+uint32_t getSNMPTimeTick(void);
+void currentUptime(void *ptr, uint8_t *len);
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.c b/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.c
new file mode 100644
index 0000000..68590c7
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.c
@@ -0,0 +1,147 @@
+
+/********************************************************************************************
+ * SNMP : User Customization Part
+ * - OID Registration
+ * - User defined functions for OID related
+ * + Integer value, String
+ * + I/O control / Chip registers
+ * + Network Informations
+ * + Etc.
+ *
+ *********************************************************************************************/
+#include "snmp_custom.h"
+
+#ifdef _USE_WIZNET_W5500_EVB_
+ #include "board.h"
+#endif
+
+dataEntryType snmpData[] =
+{
+ // System MIB
+ // SysDescr Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 1, 0},
+ SNMPDTYPE_OCTET_STRING, 30, {"WIZnet Embedded SNMP Agent"},
+ NULL, NULL},
+
+ // SysObjectID Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 2, 0},
+ SNMPDTYPE_OBJ_ID, 8, {"\x2b\x06\x01\x02\x01\x01\x02\x00"},
+ NULL, NULL},
+
+ // SysUptime Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 3, 0},
+ SNMPDTYPE_TIME_TICKS, 0, {""},
+ currentUptime, NULL},
+
+ // sysContact Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 4, 0},
+ SNMPDTYPE_OCTET_STRING, 30, {"http://www.wizwiki.net/forum"},
+ NULL, NULL},
+
+ // sysName Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 5, 0},
+ SNMPDTYPE_OCTET_STRING, 30, {"http://www.wiznet.co.kr"},
+ NULL, NULL},
+
+ // Location Entry
+ {8, {0x2b, 6, 1, 2, 1, 1, 6, 0},
+ SNMPDTYPE_OCTET_STRING, 30, {"4F Humax Village"},
+ NULL, NULL},
+
+ // SysServices
+ {8, {0x2b, 6, 1, 2, 1, 1, 7, 0},
+ SNMPDTYPE_INTEGER, 4, {""},
+ NULL, NULL},
+
+#ifdef _USE_WIZNET_W5500_EVB_
+ // Get the WIZnet W5500-EVB LED Status
+ {8, {0x2b, 6, 1, 4, 1, 6, 1, 0},
+ SNMPDTYPE_OCTET_STRING, 40, {""},
+ get_LEDStatus_all, NULL},
+
+ // Set the LED_R (RGB LED)
+ {8, {0x2b, 6, 1, 4, 1, 6, 1, 1},
+ SNMPDTYPE_INTEGER, 4, {""},
+ NULL, set_LEDStatus_R},
+
+ // Set the LED_G (RGB LED)
+ {8, {0x2b, 6, 1, 4, 1, 6, 1, 2},
+ SNMPDTYPE_INTEGER, 4, {""},
+ NULL, set_LEDStatus_G},
+
+ // Set the LED_B (RGB LED)
+ {8, {0x2b, 6, 1, 4, 1, 6, 1, 3},
+ SNMPDTYPE_INTEGER, 4, {""},
+ NULL, set_LEDStatus_B},
+#endif
+
+ // OID Test #1 (long-length OID example, 19865)
+ {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0x9b, 0x19, 0x01, 0x00},
+ SNMPDTYPE_OCTET_STRING, 30, {"long-length OID Test #1"},
+ NULL, NULL},
+
+ // OID Test #2 (long-length OID example, 22210)
+ {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0xad, 0x42, 0x01, 0x00},
+ SNMPDTYPE_OCTET_STRING, 35, {"long-length OID Test #2"},
+ NULL, NULL},
+
+ // OID Test #2: SysObjectID Entry
+ {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0xad, 0x42, 0x02, 0x00},
+ SNMPDTYPE_OBJ_ID, 0x0a, {"\x2b\x06\x01\x04\x01\x81\xad\x42\x02\x00"},
+ NULL, NULL},
+};
+
+const int32_t maxData = (sizeof(snmpData) / sizeof(dataEntryType));
+
+void initTable()
+{
+ // Example integer value for [OID 1.3.6.1.2.1.1.7.0]
+ snmpData[6].u.intval = -5;
+
+}
+
+
+// W5500-EVB: LED Control ///////////////////////////////////////////////////////////////////////////
+#ifdef _USE_WIZNET_W5500_EVB_
+void get_LEDStatus_all(void *ptr, uint8_t *len)
+{
+ uint8_t led_status[3] = {0, };
+
+ led_status[LED_R] = (uint8_t)Board_LED_Test(LED_R);
+ led_status[LED_G] = (uint8_t)Board_LED_Test(LED_G);
+ led_status[LED_B] = (uint8_t)Board_LED_Test(LED_B);
+
+ *len = sprintf((char *)ptr, "LED R [%s] / G [%s] / B [%s]", led_status[LED_R]?"On":"Off", led_status[LED_G]?"On":"Off", led_status[LED_B]?"On":"Off");
+}
+
+void set_LEDStatus_R(int32_t val)
+{
+ if(val == 0) Board_LED_Set(LED_R, false);
+ else Board_LED_Set(LED_R, true);
+}
+
+void set_LEDStatus_G(int32_t val)
+{
+ if(val == 0) Board_LED_Set(LED_G, false);
+ else Board_LED_Set(LED_G, true);
+}
+
+void set_LEDStatus_B(int32_t val)
+{
+ if(val == 0) Board_LED_Set(LED_B, false);
+ else Board_LED_Set(LED_B, true);
+}
+#endif
+/////////////////////////////////////////////////////////////////////////////////////////////////////
+
+void initial_Trap(uint8_t * managerIP, uint8_t * agentIP)
+{
+ // SNMP Trap: WarmStart(1) Trap
+ {
+ dataEntryType enterprise_oid = {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0x9b, 0x19, 0x01, 0x00},
+ SNMPDTYPE_OBJ_ID, 0x0a, {"\x2b\x06\x01\x04\x01\x81\x9b\x19\x10\x00"}, NULL, NULL};
+ // Generic Trap: warmStart COMMUNITY
+ snmp_sendTrap(managerIP, agentIP, (void *)COMMUNITY, enterprise_oid, SNMPTRAP_WARMSTART, 0, 0);
+ }
+
+}
diff --git a/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.h b/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.h
new file mode 100644
index 0000000..58e4e19
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNMP/snmp_custom.h
@@ -0,0 +1,33 @@
+#ifndef _SNMP_CUSTOM_H_
+#define _SNMP_CUSTOM_H_
+
+#include
+#include
+#include
+#include
+
+#include "snmp.h"
+
+extern dataEntryType snmpData[];
+extern const int32_t maxData;
+
+// Define for using W5500-EVB: H/W Dependency (e.g., LEDs...)
+//#define _USE_WIZNET_W5500_EVB_
+
+#define COMMUNITY "public\0"
+#define COMMUNITY_SIZE (strlen(COMMUNITY))
+
+/* Predefined function: Response value control */
+void initTable();
+
+/* User defined functions: LED control examples */
+#ifdef _USE_WIZNET_W5500_EVB_
+ void get_LEDStatus_all(void *ptr, uint8_t *len);
+ void set_LEDStatus_R(int32_t val);
+ void set_LEDStatus_G(int32_t val);
+ void set_LEDStatus_B(int32_t val);
+#endif
+/* SNMP Trap: warmStart(1) */
+void initial_Trap(uint8_t * managerIP, uint8_t * agentIP);
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/SNMP/tools/OID_Converter/Readme.txt b/WIZ550S2E_App/src/Internet/SNMP/tools/OID_Converter/Readme.txt
new file mode 100644
index 0000000..4476586
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNMP/tools/OID_Converter/Readme.txt
@@ -0,0 +1,45 @@
+============================================================
+
+============================================================
+
++ Example OID for convert
+ 1.3.6.1.4.1.19865.1.0
+
+(1) Convert Usage
+ CMD>>oid 1.3.6.1.4.1.19865.1.0
+ => 06 0A 2B 06 01 04 01 81 9B 19 01 00
+
+ >> TLV(tag-length-value) Example OID
+ (06) Tag
+ (0A) Length
+ [2B] 1(iso).3(identified-organization) (in ASN.1 BER encoding, i.e. 1*40+3 = 0x2b)
+ [06] 6(dod)
+ [01] 1(internet)
+ [04] 4(private)
+ [01] 1(enterprise)
+ [81 9B 19] 19865(Vendor-Specific)
+ ...
+
+(2) Add the entry to OID table in source code (DataEntryType, put the converted value to array)
+ {0x0a, {0x2b, 0x06, 0x01, 0x04, 0x01, 0x81, 0x9b, 0x19, 0x01, 0x00},
+ SNMPDTYPE_OCTET_STRING, 30, {"long-length OID Test"},
+ NULL, NULL},
+
+============================================================
+OID Converter: OID encoder/decoder
+v1.3 - Matthias Gaertner 1999/2001 - Freeware
+============================================================
+
+The OID converter is a handy little tool to convert ASN.1 OIDs from readable dotted decimal notation to binary hexadecimal Distinguished Encoding Rules (DER) representation and vice versa.
+If you're into x.509 certificates, this may be useful to you, too.
+
+Usage:
+ OID [-c|-C] [-o] {-i|1.2.3.4}
+ converts dotted form to ASCII HEX DER output.
+ OID -x [-o] {-i|hex-digits}
+ decodes ASCII HEX DER and gives dotted form.
+
+If you need more information, please refer to Matthias Gaertner's page,
+http://www.rtner.de/software/oid.html
+
+===============================================================================================
\ No newline at end of file
diff --git a/WIZ550S2E_App/src/Internet/SNMP/tools/net-snmp-5.7(win32-bin)/snmptrapd.conf b/WIZ550S2E_App/src/Internet/SNMP/tools/net-snmp-5.7(win32-bin)/snmptrapd.conf
new file mode 100644
index 0000000..494e4ec
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNMP/tools/net-snmp-5.7(win32-bin)/snmptrapd.conf
@@ -0,0 +1,33 @@
+#
+# net-snmp (or ucd-snmp) persistent data file.
+#
+############################################################################
+# STOP STOP STOP STOP STOP STOP STOP STOP STOP
+#
+# **** DO NOT EDIT THIS FILE ****
+#
+# STOP STOP STOP STOP STOP STOP STOP STOP STOP
+############################################################################
+#
+# DO NOT STORE CONFIGURATION ENTRIES HERE.
+# Please save normal configuration tokens for snmptrapd in SNMPCONFPATH/snmptrapd.conf.
+# Only "createUser" tokens should be placed here by snmptrapd administrators.
+# (Did I mention: do not edit this file?)
+#
+
+
+authCommunity log,execute,net public
+
+
+
+
+
+
+
+
+
+
+
+
+engineBoots 1
+oldEngineID 0x80001f88803d6f00001ba7934e00000000
diff --git a/WIZ550S2E_App/src/Internet/SNTP/sntp.c b/WIZ550S2E_App/src/Internet/SNTP/sntp.c
new file mode 100644
index 0000000..5b9c463
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/SNTP/sntp.c
@@ -0,0 +1,450 @@
+/*
+ * sntp.c
+ *
+ * Created on: 2014. 12. 15.
+ * Author: Administrator
+ */
+
+
+#include
+
+#include "sntp.h"
+#include "socket.h"
+
+ntpformat NTPformat;
+datetime Nowdatetime;
+uint8_t ntpmessage[48];
+uint8_t *data_buf;
+uint8_t NTP_SOCKET;
+uint8_t time_zone;
+uint16_t ntp_retry_cnt=0; //counting the ntp retry number
+
+/*
+00)UTC-12:00 Baker Island, Howland Island (both uninhabited)
+01) UTC-11:00 American Samoa, Samoa
+02) UTC-10:00 (Summer)French Polynesia (most), United States (Aleutian Islands, Hawaii)
+03) UTC-09:30 Marquesas Islands
+04) UTC-09:00 Gambier Islands;(Summer)United States (most of Alaska)
+05) UTC-08:00 (Summer)Canada (most of British Columbia), Mexico (Baja California)
+06) UTC-08:00 United States (California, most of Nevada, most of Oregon, Washington (state))
+07) UTC-07:00 Mexico (Sonora), United States (Arizona); (Summer)Canada (Alberta)
+08) UTC-07:00 Mexico (Chihuahua), United States (Colorado)
+09) UTC-06:00 Costa Rica, El Salvador, Ecuador (Galapagos Islands), Guatemala, Honduras
+10) UTC-06:00 Mexico (most), Nicaragua;(Summer)Canada (Manitoba, Saskatchewan), United States (Illinois, most of Texas)
+11) UTC-05:00 Colombia, Cuba, Ecuador (continental), Haiti, Jamaica, Panama, Peru
+12) UTC-05:00 (Summer)Canada (most of Ontario, most of Quebec)
+13) UTC-05:00 United States (most of Florida, Georgia, Massachusetts, most of Michigan, New York, North Carolina, Ohio, Washington D.C.)
+14) UTC-04:30 Venezuela
+15) UTC-04:00 Bolivia, Brazil (Amazonas), Chile (continental), Dominican Republic, Canada (Nova Scotia), Paraguay,
+16) UTC-04:00 Puerto Rico, Trinidad and Tobago
+17) UTC-03:30 Canada (Newfoundland)
+18) UTC-03:00 Argentina; (Summer) Brazil (Brasilia, Rio de Janeiro, Sao Paulo), most of Greenland, Uruguay
+19) UTC-02:00 Brazil (Fernando de Noronha), South Georgia and the South Sandwich Islands
+20) UTC-01:00 Portugal (Azores), Cape Verde
+21) UTC±00:00 Cote d'Ivoire, Faroe Islands, Ghana, Iceland, Senegal; (Summer) Ireland, Portugal (continental and Madeira)
+22) UTC±00:00 Spain (Canary Islands), Morocco, United Kingdom
+23) UTC+01:00 Angola, Cameroon, Nigeria, Tunisia; (Summer)Albania, Algeria, Austria, Belgium, Bosnia and Herzegovina,
+24) UTC+01:00 Spain (continental), Croatia, Czech Republic, Denmark, Germany, Hungary, Italy, Kinshasa, Kosovo,
+25) UTC+01:00 Macedonia, France (metropolitan), the Netherlands, Norway, Poland, Serbia, Slovakia, Slovenia, Sweden, Switzerland
+26) UTC+02:00 Libya, Egypt, Malawi, Mozambique, South Africa, Zambia, Zimbabwe, (Summer)Bulgaria, Cyprus, Estonia,
+27) UTC+02:00 Finland, Greece, Israel, Jordan, Latvia, Lebanon, Lithuania, Moldova, Palestine, Romania, Syria, Turkey, Ukraine
+28) UTC+03:00 Belarus, Djibouti, Eritrea, Ethiopia, Iraq, Kenya, Madagascar, Russia (Kaliningrad Oblast), Saudi Arabia,
+29) UTC+03:00 South Sudan, Sudan, Somalia, South Sudan, Tanzania, Uganda, Yemen
+30) UTC+03:30 (Summer)Iran
+31) UTC+04:00 Armenia, Azerbaijan, Georgia, Mauritius, Oman, Russia (European), Seychelles, United Arab Emirates
+32) UTC+04:30 Afghanistan
+33) UTC+05:00 Kazakhstan (West), Maldives, Pakistan, Uzbekistan
+34) UTC+05:30 India, Sri Lanka
+35) UTC+05:45 Nepal
+36) UTC+06:00 Kazakhstan (most), Bangladesh, Russia (Ural: Sverdlovsk Oblast, Chelyabinsk Oblast)
+37) UTC+06:30 Cocos Islands, Myanmar
+38) UTC+07:00 Jakarta, Russia (Novosibirsk Oblast), Thailand, Vietnam
+39) UTC+08:00 China, Hong Kong, Russia (Krasnoyarsk Krai), Malaysia, Philippines, Singapore, Taiwan, most of Mongolia, Western Australia
+40) UTC+09:00 Korea, East Timor, Russia (Irkutsk Oblast), Japan
+41) UTC+09:30 Australia (Northern Territory);(Summer)Australia (South Australia))
+42) UTC+10:00 Russia (Zabaykalsky Krai); (Summer)Australia (New South Wales, Queensland, Tasmania, Victoria)
+43) UTC+10:30 Lord Howe Island
+44) UTC+11:00 New Caledonia, Russia (Primorsky Krai), Solomon Islands
+45) UTC+11:30 Norfolk Island
+46) UTC+12:00 Fiji, Russia (Kamchatka Krai);(Summer)New Zealand
+47) UTC+12:45 (Summer)New Zealand
+48) UTC+13:00 Tonga
+49) UTC+14:00 Kiribati (Line Islands)
+*/
+void get_seconds_from_ntp_server(uint8_t *buf, uint16_t idx)
+{
+ tstamp seconds = 0;
+ uint8_t i=0;
+ for (i = 0; i < 4; i++)
+ {
+ seconds = (seconds << 8) | buf[idx + i];
+ }
+ switch (time_zone)
+ {
+ case 0:
+ seconds -= 12*3600;
+ break;
+ case 1:
+ seconds -= 11*3600;
+ break;
+ case 2:
+ seconds -= 10*3600;
+ break;
+ case 3:
+ seconds -= (9*3600+30*60);
+ break;
+ case 4:
+ seconds -= 9*3600;
+ break;
+ case 5:
+ case 6:
+ seconds -= 8*3600;
+ break;
+ case 7:
+ case 8:
+ seconds -= 7*3600;
+ break;
+ case 9:
+ case 10:
+ seconds -= 6*3600;
+ break;
+ case 11:
+ case 12:
+ case 13:
+ seconds -= 5*3600;
+ break;
+ case 14:
+ seconds -= (4*3600+30*60);
+ break;
+ case 15:
+ case 16:
+ seconds -= 4*3600;
+ break;
+ case 17:
+ seconds -= (3*3600+30*60);
+ break;
+ case 18:
+ seconds -= 3*3600;
+ break;
+ case 19:
+ seconds -= 2*3600;
+ break;
+ case 20:
+ seconds -= 1*3600;
+ break;
+ case 21: //?
+ case 22:
+ break;
+ case 23:
+ case 24:
+ case 25:
+ seconds += 1*3600;
+ break;
+ case 26:
+ case 27:
+ seconds += 2*3600;
+ break;
+ case 28:
+ case 29:
+ seconds += 3*3600;
+ break;
+ case 30:
+ seconds += (3*3600+30*60);
+ break;
+ case 31:
+ seconds += 4*3600;
+ break;
+ case 32:
+ seconds += (4*3600+30*60);
+ break;
+ case 33:
+ seconds += 5*3600;
+ break;
+ case 34:
+ seconds += (5*3600+30*60);
+ break;
+ case 35:
+ seconds += (5*3600+45*60);
+ break;
+ case 36:
+ seconds += 6*3600;
+ break;
+ case 37:
+ seconds += (6*3600+30*60);
+ break;
+ case 38:
+ seconds += 7*3600;
+ break;
+ case 39:
+ seconds += 8*3600;
+ break;
+ case 40:
+ seconds += 9*3600;
+ break;
+ case 41:
+ seconds += (9*3600+30*60);
+ break;
+ case 42:
+ seconds += 10*3600;
+ break;
+ case 43:
+ seconds += (10*3600+30*60);
+ break;
+ case 44:
+ seconds += 11*3600;
+ break;
+ case 45:
+ seconds += (11*3600+30*60);
+ break;
+ case 46:
+ seconds += 12*3600;
+ break;
+ case 47:
+ seconds += (12*3600+45*60);
+ break;
+ case 48:
+ seconds += 13*3600;
+ break;
+ case 49:
+ seconds += 14*3600;
+ break;
+
+ }
+
+ //calculation for date
+ calcdatetime(seconds);
+}
+
+void SNTP_init(uint8_t s, uint8_t *ntp_server, uint8_t tz, uint8_t *buf)
+{
+ NTP_SOCKET = s;
+
+ NTPformat.dstaddr[0] = ntp_server[0];
+ NTPformat.dstaddr[1] = ntp_server[1];
+ NTPformat.dstaddr[2] = ntp_server[2];
+ NTPformat.dstaddr[3] = ntp_server[3];
+
+ time_zone = tz;
+
+ data_buf = buf;
+
+ uint8_t Flag;
+ NTPformat.leap = 0; /* leap indicator */
+ NTPformat.version = 4; /* version number */
+ NTPformat.mode = 3; /* mode */
+ NTPformat.stratum = 0; /* stratum */
+ NTPformat.poll = 0; /* poll interval */
+ NTPformat.precision = 0; /* precision */
+ NTPformat.rootdelay = 0; /* root delay */
+ NTPformat.rootdisp = 0; /* root dispersion */
+ NTPformat.refid = 0; /* reference ID */
+ NTPformat.reftime = 0; /* reference time */
+ NTPformat.org = 0; /* origin timestamp */
+ NTPformat.rec = 0; /* receive timestamp */
+ NTPformat.xmt = 1; /* transmit timestamp */
+
+ Flag = (NTPformat.leap<<6)+(NTPformat.version<<3)+NTPformat.mode; //one byte Flag
+ memcpy(ntpmessage,(void const*)(&Flag),1);
+}
+
+int8_t SNTP_run(datetime *time)
+{
+ uint16_t RSR_len;
+ uint32_t destip = 0;
+ uint16_t destport;
+ uint16_t startindex = 40; //last 8-byte of data_buf[size is 48 byte] is xmt, so the startindex should be 40
+
+ switch(getSn_SR(NTP_SOCKET))
+ {
+ case SOCK_UDP:
+ if ((RSR_len = getSn_RX_RSR(NTP_SOCKET)) > 0)
+ {
+ if (RSR_len > MAX_SNTP_BUF_SIZE) RSR_len = MAX_SNTP_BUF_SIZE; // if Rx data size is lager than TX_RX_MAX_BUF_SIZE
+ recvfrom(NTP_SOCKET, data_buf, RSR_len, (uint8_t *)&destip, &destport);
+
+ get_seconds_from_ntp_server(data_buf,startindex);
+ time->yy = Nowdatetime.yy;
+ time->mo = Nowdatetime.mo;
+ time->dd = Nowdatetime.dd;
+ time->hh = Nowdatetime.hh;
+ time->mm = Nowdatetime.mm;
+ time->ss = Nowdatetime.ss;
+
+ ntp_retry_cnt=0;
+ close(NTP_SOCKET);
+
+ return 1;
+ }
+
+ if(ntp_retry_cnt<0xFFFF)
+ {
+ if(ntp_retry_cnt==0)//first send request, no need to wait
+ {
+ sendto(NTP_SOCKET,ntpmessage,sizeof(ntpmessage),NTPformat.dstaddr,ntp_port);
+ ntp_retry_cnt++;
+ }
+ else // send request again? it should wait for a while
+ {
+ if((ntp_retry_cnt % 0xFFF) == 0) //wait time
+ {
+ sendto(NTP_SOCKET,ntpmessage,sizeof(ntpmessage),NTPformat.dstaddr,ntp_port);
+#ifdef _SNTP_DEBUG_
+ printf("ntp retry: %d\r\n", ntp_retry_cnt);
+#endif
+ ntp_retry_cnt++;
+ }
+ }
+ }
+ else //ntp retry fail
+ {
+ ntp_retry_cnt=0;
+#ifdef _SNTP_DEBUG_
+ printf("ntp retry failed!\r\n");
+#endif
+ close(NTP_SOCKET);
+ }
+ break;
+ case SOCK_CLOSED:
+ socket(NTP_SOCKET,Sn_MR_UDP,ntp_port,0);
+ break;
+ }
+ // Return value
+ // 0 - failed / 1 - success
+ return 0;
+}
+
+void calcdatetime(tstamp seconds)
+{
+ uint8_t yf=0;
+ tstamp n=0,d=0,total_d=0,rz=0;
+ uint16_t y=0,r=0,yr=0;
+ signed long long yd=0;
+
+ n = seconds;
+ total_d = seconds/(SECS_PERDAY);
+ d=0;
+ uint32_t p_year_total_sec=SECS_PERDAY*365;
+ uint32_t r_year_total_sec=SECS_PERDAY*366;
+ while(n>=p_year_total_sec)
+ {
+ if((EPOCH+r)%400==0 || ((EPOCH+r)%100!=0 && (EPOCH+r)%4==0))
+ {
+ n = n -(r_year_total_sec);
+ d = d + 366;
+ }
+ else
+ {
+ n = n - (p_year_total_sec);
+ d = d + 365;
+ }
+ r+=1;
+ y+=1;
+
+ }
+
+ y += EPOCH;
+
+ Nowdatetime.yy = y;
+
+ yd=0;
+ yd = total_d - d;
+
+ yf=1;
+ while(yd>=28)
+ {
+
+ if(yf==1 || yf==3 || yf==5 || yf==7 || yf==8 || yf==10 || yf==12)
+ {
+ yd -= 31;
+ if(yd<0)break;
+ rz += 31;
+ }
+
+ if (yf==2)
+ {
+ if (y%400==0 || (y%100!=0 && y%4==0))
+ {
+ yd -= 29;
+ if(yd<0)break;
+ rz += 29;
+ }
+ else
+ {
+ yd -= 28;
+ if(yd<0)break;
+ rz += 28;
+ }
+ }
+ if(yf==4 || yf==6 || yf==9 || yf==11 )
+ {
+ yd -= 30;
+ if(yd<0)break;
+ rz += 30;
+ }
+ yf += 1;
+
+ }
+ Nowdatetime.mo=yf;
+ yr = total_d-d-rz;
+
+ yr += 1;
+
+ Nowdatetime.dd=yr;
+
+ //calculation for time
+ seconds = seconds%SECS_PERDAY;
+ Nowdatetime.hh = seconds/3600;
+ Nowdatetime.mm = (seconds%3600)/60;
+ Nowdatetime.ss = (seconds%3600)%60;
+
+}
+
+tstamp changedatetime_to_seconds(void)
+{
+ tstamp seconds=0;
+ uint32_t total_day=0;
+ uint16_t i=0,run_year_cnt=0,l=0;
+
+ l = Nowdatetime.yy;//low
+
+
+ for(i=EPOCH;i
+
+/*
+ * @brief Define it for Debug & Monitor DNS processing.
+ * @note If defined, it dependens on
+ */
+//#define _SNTP_DEBUG_
+
+#define MAX_SNTP_BUF_SIZE sizeof(ntpformat) ///< maximum size of DNS buffer. */
+
+/* for ntpclient */
+typedef signed char s_char;
+typedef unsigned long long tstamp;
+typedef unsigned int tdist;
+
+typedef struct _ntpformat
+{
+
+ uint8_t dstaddr[4]; /* destination (local) address */
+ char version; /* version number */
+ char leap; /* leap indicator */
+ char mode; /* mode */
+ char stratum; /* stratum */
+ char poll; /* poll interval */
+ s_char precision; /* precision */
+ tdist rootdelay; /* root delay */
+ tdist rootdisp; /* root dispersion */
+ char refid; /* reference ID */
+ tstamp reftime; /* reference time */
+ tstamp org; /* origin timestamp */
+ tstamp rec; /* receive timestamp */
+ tstamp xmt; /* transmit timestamp */
+
+
+} ntpformat;
+
+typedef struct _datetime
+{
+ uint16_t yy;
+ uint8_t mo;
+ uint8_t dd;
+ uint8_t hh;
+ uint8_t mm;
+ uint8_t ss;
+} datetime;
+
+#define ntp_port 123 //ntp server port number
+#define SECS_PERDAY 86400UL // seconds in a day = 60*60*24
+#define UTC_ADJ_HRS 9 // SEOUL : GMT+9
+#define EPOCH 1900 // NTP start year
+
+void get_seconds_from_ntp_server(uint8_t *buf, uint16_t idx);
+void SNTP_init(uint8_t s, uint8_t *ntp_server, uint8_t tz, uint8_t *buf);
+int8_t SNTP_run(datetime *time);
+tstamp changedatetime_to_seconds(void);
+void calcdatetime(tstamp seconds);
+
+#endif /* SNTP_H_ */
diff --git a/WIZ550S2E_App/src/Internet/TFTP/netutil.c b/WIZ550S2E_App/src/Internet/TFTP/netutil.c
new file mode 100644
index 0000000..77b0992
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/TFTP/netutil.c
@@ -0,0 +1,158 @@
+#include
+#include
+#include
+#include "netutil.h"
+
+/**
+ * Convert a 32bit Address into a Dotted Decimal Format string.
+ *
+ * @param addr 32bit address.
+ * @return Dotted Decimal Format string.
+ */
+int8_t* inet_ntoa(uint32_t addr)
+{
+ static int8_t addr_str[16];
+ memset(addr_str,0,16);
+ sprintf((char*)addr_str,"%d.%d.%d.%d",(int32_t)(addr>>24 & 0xFF),(int32_t)(addr>>16 & 0xFF),(int32_t)(addr>>8 & 0xFF),(int32_t)(addr & 0xFF));
+ return addr_str;
+}
+
+/**
+ * Convert a 32bit Address into a Dotted Decimal Format string.
+ * This is differ from inet_ntoa in fixed length.
+ *
+ * @param addr 32bit address.
+ * @return Dotted Decimal Format string.
+ */
+int8_t* inet_ntoa_pad(uint32_t addr)
+{
+ static int8_t addr_str[16];
+ memset(addr_str,0,16);
+ sprintf((char*)addr_str,"%03d.%03d.%03d.%03d",(int32_t)(addr>>24 & 0xFF),(int32_t)(addr>>16 & 0xFF),(int32_t)(addr>>8 & 0xFF),(int32_t)(addr & 0xFF));
+ return addr_str;
+}
+
+/**
+ * Converts a string containing an (Ipv4) Internet Protocol decimal dotted address into a 32bit address.
+ *
+ * @param addr Dotted Decimal Format string.
+ * @return 32bit address.
+ */
+uint32_t inet_addr(uint8_t* addr)
+{
+ int8_t i;
+ uint32_t inetaddr = 0;
+ int8_t taddr[30];
+ int8_t * nexttok;
+ int32_t num;
+ strcpy((char*)taddr,(char*)addr);
+
+ nexttok = taddr;
+ for(i = 0; i < 4 ; i++)
+ {
+ nexttok = (int8_t*)strtok((char*)nexttok,".");
+ if(nexttok[0] == '0' && nexttok[1] == 'x') num = strtol((char*)nexttok+2, NULL, 16);
+ else num = strtol((char*)nexttok, NULL, 10);
+ inetaddr = inetaddr << 8;
+ inetaddr |= (num & 0xFF);
+ nexttok = NULL;
+ }
+ return inetaddr;
+}
+
+/**
+ * Swap the byte order of 16bit(short) wide variable.
+ *
+ * @param i 16bit value to swap
+ * @return Swapped value
+ */
+uint16_t swaps(uint16_t i)
+{
+ uint16_t ret=0;
+ ret = (i & 0xFF) << 8;
+ ret |= ((i >> 8)& 0xFF);
+ return ret;
+}
+
+/**
+ * Swap the byte order of 32bit(long) wide variable.
+ *
+ * @param l 32bit value to convert
+ * @return Swapped value
+ */
+uint32_t swapl(uint32_t l)
+{
+ uint32_t ret=0;
+ ret = (l & 0xFF) << 24;
+ ret |= ((l >> 8) & 0xFF) << 16;
+ ret |= ((l >> 16) & 0xFF) << 8;
+ ret |= ((l >> 24) & 0xFF);
+ return ret;
+}
+
+/**
+ * htons function converts a unsigned short from host to TCP/IP network byte order (which is big-endian).
+ *
+ * @param hostshort The value to convert.
+ * @return The value in TCP/IP network byte order.
+ */
+uint16_t htons(uint16_t hostshort)
+{
+#ifdef SYSTEM_LITTLE_ENDIAN
+ return swaps(hostshort);
+#else
+ return hostshort;
+#endif
+}
+
+
+/**
+ * htonl function converts a unsigned long from host to TCP/IP network byte order (which is big-endian).
+ *
+ * @param hostlong The value to convert.
+ * @return The value in TCP/IP network byte order.
+ */
+uint32_t htonl(uint32_t hostlong)
+{
+#ifdef SYSTEM_LITTLE_ENDIAN
+ return swapl(hostlong);
+#else
+ return hostlong;
+#endif
+}
+
+
+/**
+ * ntohs function converts a unsigned short from TCP/IP network byte order
+ * to host byte order (which is little-endian on Intel processors).
+ *
+ * @param netshort The value to convert.
+ * @return A 16-bit number in host byte order
+ */
+uint32_t ntohs(uint16_t netshort)
+{
+#ifdef SYSTEM_LITTLE_ENDIAN
+ return htons(netshort);
+#else
+ return netshort;
+#endif
+}
+
+/**
+ * converts a unsigned long from TCP/IP network byte order to host byte order
+ * (which is little-endian on Intel processors).
+ *
+ * @param netlong The value to convert.
+ * @return A 16-bit number in host byte order
+ */
+uint32_t ntohl(uint32_t netlong)
+{
+#ifdef SYSTEM_LITTLE_ENDIAN
+ return swapl(netlong);
+#else
+ return netlong;
+#endif
+}
+/**
+ * @}
+ */
diff --git a/WIZ550S2E_App/src/Internet/TFTP/netutil.h b/WIZ550S2E_App/src/Internet/TFTP/netutil.h
new file mode 100644
index 0000000..bf82366
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/TFTP/netutil.h
@@ -0,0 +1,19 @@
+
+#ifndef __NETUTIL_H__
+#define __NETUTIL_H__
+
+#include
+
+#define SYSTEM_LITTLE_ENDIAN
+
+int8_t* inet_ntoa(uint32_t addr);
+int8_t* inet_ntoa_pad(uint32_t addr);
+uint32_t inet_addr(uint8_t* addr);
+uint16_t swaps(uint16_t i);
+uint32_t swapl(uint32_t l);
+uint16_t htons(uint16_t hostshort);
+uint32_t htonl(uint32_t hostlong);
+uint32_t ntohs(uint16_t netshort);
+uint32_t ntohl(uint32_t netlong);
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/TFTP/tftp.c b/WIZ550S2E_App/src/Internet/TFTP/tftp.c
new file mode 100644
index 0000000..2002ca4
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/TFTP/tftp.c
@@ -0,0 +1,660 @@
+/**
+ * @file tftp.c
+ * @brief TFTP Source File.
+ * @version 0.1.0
+ * @author Sang-sik Kim
+ */
+
+/* Includes -----------------------------------------------------*/
+#include
+#include "tftp.h"
+#include "socket.h"
+#include "netutil.h"
+
+/* define -------------------------------------------------------*/
+
+/* typedef ------------------------------------------------------*/
+
+/* Extern Variable ----------------------------------------------*/
+
+/* Extern Functions ---------------------------------------------*/
+#ifdef F_STORAGE
+extern void save_data(uint8_t *data, uint32_t data_len, uint16_t block_number);
+#endif
+
+/* Global Variable ----------------------------------------------*/
+static int g_tftp_socket = -1;
+
+static uint8_t g_filename[FILE_NAME_SIZE];
+
+static uint32_t g_server_ip = 0;
+static uint16_t g_server_port = 0;
+static uint16_t g_local_port = 0;
+
+static uint32_t g_tftp_state = STATE_NONE;
+static uint16_t g_block_num = 0;
+
+static uint32_t g_timeout = 5;
+static uint32_t g_resend_flag = 0;
+static uint32_t tftp_time_cnt = 0;
+static uint32_t tftp_retry_cnt = 0;
+
+static uint8_t *g_tftp_rcv_buf = NULL;
+
+static TFTP_OPTION default_tftp_opt = {
+ .code = (uint8_t *)"timeout",
+ .value = (uint8_t *)"5"
+};
+
+uint8_t g_progress_state = TFTP_PROGRESS;
+
+#ifdef __TFTP_DEBUG__
+int dbg_level = (INFO_DBG | ERROR_DBG | IPC_DBG);
+#endif
+
+/* static function define ---------------------------------------*/
+static void set_filename(uint8_t *file, uint32_t file_size)
+{
+ memcpy(g_filename, file, file_size);
+}
+
+static inline void set_server_ip(uint32_t ipaddr)
+{
+ g_server_ip = ipaddr;
+}
+
+static inline uint32_t get_server_ip()
+{
+ return g_server_ip;
+}
+
+static inline void set_server_port(uint16_t port)
+{
+ g_server_port = port;
+}
+
+static inline uint16_t get_server_port()
+{
+ return g_server_port;
+}
+
+static inline void set_local_port(uint16_t port)
+{
+ g_local_port = port;
+}
+
+static inline uint16_t get_local_port()
+{
+ return g_local_port;
+}
+
+static inline uint16_t genernate_port()
+{
+ /* TODO */
+ return 0;
+}
+
+static inline void set_tftp_state(uint32_t state)
+{
+ g_tftp_state = state;
+}
+
+static inline uint32_t get_tftp_state()
+{
+ return g_tftp_state;
+}
+
+static inline void set_tftp_timeout(uint32_t timeout)
+{
+ g_timeout = timeout;
+}
+
+static inline uint32_t get_tftp_timeout()
+{
+ return g_timeout;
+}
+
+static inline void set_block_number(uint16_t block_number)
+{
+ g_block_num = block_number;
+}
+
+static inline uint16_t get_block_number()
+{
+ return g_block_num;
+}
+
+static int open_tftp_socket(uint8_t sock)
+{
+ uint8_t sd, sck_state;
+
+ sd = socket(sock, Sn_MR_UDP, 51000, SF_IO_NONBLOCK);
+ if(sd != sock) {
+ //DBG_PRINT(ERROR_DBG, "[%s] socket error\r\n", __func__);
+ return -1;
+ }
+
+ do {
+ getsockopt(sd , SO_STATUS, &sck_state);
+ } while(sck_state != SOCK_UDP);
+
+ return sd;
+}
+
+static int send_udp_packet(int socket, uint8_t *packet, uint32_t len, uint32_t ip, uint16_t port)
+{
+ int snd_len;
+
+ ip = htonl(ip);
+
+ snd_len = sendto(socket, packet, len, (uint8_t *)&ip, port);
+ if(snd_len != len) {
+ //DBG_PRINT(ERROR_DBG, "[%s] sendto error\r\n", __func__);
+ return -1;
+ }
+
+ return snd_len;
+}
+
+static int recv_udp_packet(int socket, uint8_t *packet, uint32_t len, uint32_t *ip, uint16_t *port)
+{
+ int ret;
+ uint8_t sck_state;
+ uint16_t recv_len;
+
+ /* Receive Packet Process */
+ ret = getsockopt(socket, SO_STATUS, &sck_state);
+ if(ret != SOCK_OK) {
+ //DBG_PRINT(ERROR_DBG, "[%s] getsockopt SO_STATUS error\r\n", __func__);
+ return -1;
+ }
+
+ if(sck_state == SOCK_UDP) {
+ ret = getsockopt(socket, SO_RECVBUF, &recv_len);
+ if(ret != SOCK_OK) {
+ //DBG_PRINT(ERROR_DBG, "[%s] getsockopt SO_RECVBUF error\r\n", __func__);
+ return -1;
+ }
+
+ if(recv_len) {
+ recv_len = recvfrom(socket, packet, len, (uint8_t *)ip, port);
+ if(recv_len < 0) {
+ //DBG_PRINT(ERROR_DBG, "[%s] recvfrom error\r\n", __func__);
+ return -1;
+ }
+
+ *ip = ntohl(*ip);
+
+ return recv_len;
+ }
+ }
+ return -1;
+}
+
+static void close_tftp_socket(int socket)
+{
+ close(socket);
+}
+
+
+static void init_tftp(void)
+{
+ g_filename[0] = 0;
+
+ set_server_ip(0);
+ set_server_port(0);
+ set_local_port(0);
+
+ set_tftp_state(STATE_NONE);
+ set_block_number(0);
+
+ /* timeout flag */
+ g_resend_flag = 0;
+ tftp_retry_cnt = tftp_time_cnt = 0;
+
+ g_progress_state = TFTP_PROGRESS;
+}
+
+static void tftp_cancel_timeout(void)
+{
+ if(g_resend_flag) {
+ g_resend_flag = 0;
+ tftp_retry_cnt = tftp_time_cnt = 0;
+ }
+}
+
+static void tftp_reg_timeout()
+{
+ if(g_resend_flag == 0) {
+ g_resend_flag = 1;
+ tftp_retry_cnt = tftp_time_cnt = 0;
+ }
+}
+
+static void process_tftp_option(uint8_t *msg, uint32_t msg_len)
+{
+ /* TODO Option Process */
+}
+
+static void send_tftp_rrq(uint8_t *filename, uint8_t *mode, TFTP_OPTION *opt, uint8_t opt_len)
+{
+ uint8_t snd_buf[MAX_MTU_SIZE];
+ uint8_t *pkt = snd_buf;
+ uint32_t i, len;
+
+ *((uint16_t *)pkt) = htons(TFTP_RRQ);
+ pkt += 2;
+ strcpy((char *)pkt, (const char *)filename);
+ pkt += strlen((char *)filename) + 1;
+ strcpy((char *)pkt, (const char *)mode);
+ pkt += strlen((char *)mode) + 1;
+
+ for(i = 0 ; i < opt_len ; i++) {
+ strcpy((char *)pkt, (const char *)opt[i].code);
+ pkt += strlen((char *)opt[i].code) + 1;
+ strcpy((char *)pkt, (const char *)opt[i].value);
+ pkt += strlen((char *)opt[i].value) + 1;
+ }
+
+ len = pkt - snd_buf;
+
+ send_udp_packet(g_tftp_socket, snd_buf, len, get_server_ip(), TFTP_SERVER_PORT);
+ set_tftp_state(STATE_RRQ);
+ set_filename(filename, strlen((char *)filename) + 1);
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP RRQ : FileName(%s), Mode(%s)\r\n", filename, mode);
+#endif
+}
+
+#if 0 // 2014.07.01 sskim
+static void send_tftp_wrq(uint8_t *filename, uint8_t *mode, TFTP_OPTION *opt, uint8_t opt_len)
+{
+ uint8_t snd_buf[MAX_MTU_SIZE];
+ uint8_t *pkt = snd_buf;
+ uint32_t i, len;
+
+ *((uint16_t *)pkt) = htons((uint16_t)TFTP_WRQ);
+ pkt += 2;
+ strcpy((char *)pkt, (const char *)filename);
+ pkt += strlen((char *)filename) + 1;
+ strcpy((char *)pkt, (const char *)mode);
+ pkt += strlen((char *)mode) + 1;
+
+ for(i = 0 ; i < opt_len ; i++) {
+ strcpy((char *)pkt, (const char *)opt[i].code);
+ pkt += strlen((char *)opt[i].code) + 1;
+ strcpy((char *)pkt, (const char *)opt[i].value);
+ pkt += strlen((char *)opt[i].value) + 1;
+ }
+
+ len = pkt - snd_buf;
+
+ send_udp_packet(g_tftp_socket , snd_buf, len, get_server_ip(), TFTP_SERVER_PORT);
+ set_tftp_state(STATE_WRQ);
+ set_filename(filename, strlen((char *)filename) + 1);
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP WRQ : FileName(%s), Mode(%s)\r\n", filename, mode);
+#endif
+}
+#endif
+
+#if 0 // 2014.07.01 sskim
+static void send_tftp_data(uint16_t block_number, uint8_t *data, uint16_t data_len)
+{
+ uint8_t snd_buf[MAX_MTU_SIZE];
+ uint8_t *pkt = snd_buf;
+ uint32_t len;
+
+ *((uint16_t *)pkt) = htons((uint16_t)TFTP_DATA);
+ pkt += 2;
+ *((uint16_t *)pkt) = htons(block_number);
+ pkt += 2;
+ memcpy(pkt, data, data_len);
+ pkt += data_len;
+
+ len = pkt - snd_buf;
+
+ send_udp_packet(g_tftp_socket , snd_buf, len, get_server_ip(), get_server_port());
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP DATA : Block Number(%d), Data Length(%d)\r\n", block_number, data_len);
+#endif
+}
+#endif
+
+static void send_tftp_ack(uint16_t block_number)
+{
+ uint8_t snd_buf[4];
+ uint8_t *pkt = snd_buf;
+
+ *((uint16_t *)pkt) = htons((uint16_t)TFTP_ACK);
+ pkt += 2;
+ *((uint16_t *)pkt) = htons(block_number);
+ pkt += 2;
+
+ send_udp_packet(g_tftp_socket , snd_buf, 4, get_server_ip(), get_server_port());
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP ACK : Block Number(%d)\r\n", block_number);
+#endif
+}
+
+#if 0 // 2014.07.01 sskim
+static void send_tftp_oack(TFTP_OPTION *opt, uint8_t opt_len)
+{
+ uint8_t snd_buf[MAX_MTU_SIZE];
+ uint8_t *pkt = snd_buf;
+ uint32_t i, len;
+
+ *((uint16_t *)pkt) = htons((uint16_t)TFTP_OACK);
+ pkt += 2;
+
+ for(i = 0 ; i < opt_len ; i++) {
+ strcpy((char *)pkt, (const char *)opt[i].code);
+ pkt += strlen((char *)opt[i].code) + 1;
+ strcpy((char *)pkt, (const char *)opt[i].value);
+ pkt += strlen((char *)opt[i].value) + 1;
+ }
+
+ len = pkt - snd_buf;
+
+ send_udp_packet(g_tftp_socket , snd_buf, len, get_server_ip(), get_server_port());
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP OACK \r\n");
+#endif
+}
+#endif
+
+#if 0 // 2014.07.01 sskim
+static void send_tftp_error(uint16_t error_number, uint8_t *error_message)
+{
+ uint8_t snd_buf[MAX_MTU_SIZE];
+ uint8_t *pkt = snd_buf;
+ uint32_t len;
+
+ *((uint16_t *)pkt) = htons((uint16_t)TFTP_ERROR);
+ pkt += 2;
+ *((uint16_t *)pkt) = htons(error_number);
+ pkt += 2;
+ strcpy((char *)pkt, (const char *)error_message);
+ pkt += strlen((char *)error_message) + 1;
+
+ len = pkt - snd_buf;
+
+ send_udp_packet(g_tftp_socket , snd_buf, len, get_server_ip(), get_server_port());
+ tftp_reg_timeout();
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, ">> TFTP ERROR : Error Number(%d)\r\n", error_number);
+#endif
+}
+#endif
+
+static void recv_tftp_rrq(uint8_t *msg, uint32_t msg_len)
+{
+ /* When TFTP Server Mode */
+}
+
+static void recv_tftp_wrq(uint8_t *msg, uint32_t msg_len)
+{
+ /* When TFTP Server Mode */
+}
+
+static void recv_tftp_data(uint8_t *msg, uint32_t msg_len)
+{
+ TFTP_DATA_T *data = (TFTP_DATA_T *)msg;
+
+ data->opcode = ntohs(data->opcode);
+ data->block_num = ntohs(data->block_num);
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, "<< TFTP_DATA : opcode(%d), block_num(%d)\r\n", data->opcode, data->block_num);
+#endif
+
+ switch(get_tftp_state())
+ {
+ case STATE_RRQ :
+ case STATE_OACK :
+ if(data->block_num == 1) {
+ set_tftp_state(STATE_DATA);
+ set_block_number(data->block_num);
+#ifdef F_STORAGE
+ save_data(data->data, msg_len - 4, data->block_num);
+#endif
+ tftp_cancel_timeout();
+ }
+ send_tftp_ack(data->block_num);
+
+ if((msg_len - 4) < TFTP_BLK_SIZE) {
+ init_tftp();
+ g_progress_state = TFTP_SUCCESS;
+ }
+
+ break;
+
+ case STATE_DATA :
+ if(data->block_num == (get_block_number() + 1)) {
+ set_block_number(data->block_num);
+#ifdef F_STORAGE
+ save_data(data->data, msg_len - 4, data->block_num);
+#endif
+ tftp_cancel_timeout();
+ }
+ send_tftp_ack(data->block_num);
+
+ if((msg_len - 4) < TFTP_BLK_SIZE) {
+ init_tftp();
+ g_progress_state = TFTP_SUCCESS;
+ }
+
+ break;
+
+ default :
+ /* invalid message */
+ break;
+ }
+}
+
+static void recv_tftp_ack(uint8_t *msg, uint32_t msg_len)
+{
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, "<< TFTP_ACK : \r\n");
+#endif
+
+ switch(get_tftp_state())
+ {
+ case STATE_WRQ :
+ break;
+
+ case STATE_ACK :
+ break;
+
+ default :
+ /* invalid message */
+ break;
+ }
+}
+
+static void recv_tftp_oack(uint8_t *msg, uint32_t msg_len)
+{
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, "<< TFTP_OACK : \r\n");
+#endif
+
+ switch(get_tftp_state())
+ {
+ case STATE_RRQ :
+ process_tftp_option(msg, msg_len);
+ set_tftp_state(STATE_OACK);
+ tftp_cancel_timeout();
+ send_tftp_ack(0);
+ break;
+
+ case STATE_WRQ :
+ process_tftp_option(msg, msg_len);
+ set_tftp_state(STATE_ACK);
+ tftp_cancel_timeout();
+
+ /* TODO DATA Transfer */
+ //send_tftp_data(...);
+ break;
+
+ default :
+ /* invalid message */
+ break;
+ }
+}
+
+static void recv_tftp_error(uint8_t *msg, uint32_t msg_len)
+{
+ TFTP_ERROR_T *data= (TFTP_ERROR_T *)msg;
+
+ data->opcode = ntohs(data->opcode);
+ data->error_code = ntohs(data->error_code);
+
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(IPC_DBG, "<< TFTP_ERROR : %d (%s)\r\n", data->error_code, data->error_msg);
+ DBG_PRINT(ERROR_DBG, "[%s] Error Code : %d (%s)\r\n", __func__, data->error_code, data->error_msg);
+#endif
+ init_tftp();
+ g_progress_state = TFTP_FAIL;
+}
+
+static void recv_tftp_packet(uint8_t *packet, uint32_t packet_len, uint32_t from_ip, uint16_t from_port)
+{
+ uint16_t opcode;
+
+ /* Verify Server IP */
+ if(from_ip != get_server_ip()) {
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(ERROR_DBG, "[%s] Server IP faults\r\n", __func__);
+ DBG_PRINT(ERROR_DBG, "from IP : %08x, Server IP : %08x\r\n", from_ip, get_server_ip());
+#endif
+ return;
+ }
+
+ opcode = ntohs(*((uint16_t *)packet));
+
+ /* Set Server Port */
+ if((get_tftp_state() == STATE_WRQ) || (get_tftp_state() == STATE_RRQ)) {
+ set_server_port(from_port);
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(INFO_DBG, "[%s] Set Server Port : %d\r\n", __func__, from_port);
+#endif
+ }
+
+ switch(opcode)
+ {
+ case TFTP_RRQ : /* When Server */
+ recv_tftp_rrq(packet, packet_len);
+ break;
+ case TFTP_WRQ : /* When Server */
+ recv_tftp_wrq(packet, packet_len);
+ break;
+ case TFTP_DATA :
+ recv_tftp_data(packet, packet_len);
+ break;
+ case TFTP_ACK :
+ recv_tftp_ack(packet, packet_len);
+ break;
+ case TFTP_OACK :
+ recv_tftp_oack(packet, packet_len);
+ break;
+ case TFTP_ERROR :
+ recv_tftp_error(packet, packet_len);
+ break;
+
+ default :
+ // Unknown Mesage
+ break;
+ }
+}
+
+/* Functions ----------------------------------------------------*/
+void TFTP_init(uint8_t socket, uint8_t *buf)
+{
+ init_tftp();
+
+ g_tftp_socket = open_tftp_socket(socket);
+ g_tftp_rcv_buf = buf;
+}
+
+void TFTP_exit(void)
+{
+ init_tftp();
+
+ close_tftp_socket(g_tftp_socket);
+ g_tftp_socket = -1;
+
+ g_tftp_rcv_buf = NULL;
+}
+
+int TFTP_run(void)
+{
+ uint16_t len, from_port;
+ uint32_t from_ip;
+
+ /* Timeout Process */
+ if(g_resend_flag) {
+ if(tftp_time_cnt >= g_timeout) {
+ switch(get_tftp_state()) {
+ case STATE_WRQ: // 미구현
+ break;
+
+ case STATE_RRQ:
+ send_tftp_rrq(g_filename, (uint8_t *)TRANS_BINARY, &default_tftp_opt, 1);
+ break;
+
+ case STATE_OACK:
+ case STATE_DATA:
+ send_tftp_ack(get_block_number());
+ break;
+
+ case STATE_ACK: // 미구현
+ break;
+
+ default:
+ break;
+ }
+
+ tftp_time_cnt = 0;
+ tftp_retry_cnt++;
+
+ if(tftp_retry_cnt >= 5) {
+ init_tftp();
+ g_progress_state = TFTP_FAIL;
+ }
+ }
+ }
+
+ /* Receive Packet Process */
+ len = recv_udp_packet(g_tftp_socket, g_tftp_rcv_buf, MAX_MTU_SIZE, &from_ip, &from_port);
+ if(len < 0) {
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(ERROR_DBG, "[%s] recv_udp_packet error\r\n", __func__);
+#endif
+ return g_progress_state;
+ }
+
+ recv_tftp_packet(g_tftp_rcv_buf, len, from_ip, from_port);
+
+ return g_progress_state;
+}
+
+void TFTP_read_request(uint32_t server_ip, uint8_t *filename)
+{
+ set_server_ip(server_ip);
+#ifdef __TFTP_DEBUG__
+ DBG_PRINT(INFO_DBG, "[%s] Set Tftp Server : %x\r\n", __func__, server_ip);
+#endif
+
+ g_progress_state = TFTP_PROGRESS;
+ send_tftp_rrq(filename, (uint8_t *)TRANS_BINARY, &default_tftp_opt, 1);
+}
+
+void tftp_timeout_handler(void)
+{
+ if(g_resend_flag)
+ tftp_time_cnt++;
+}
diff --git a/WIZ550S2E_App/src/Internet/TFTP/tftp.h b/WIZ550S2E_App/src/Internet/TFTP/tftp.h
new file mode 100644
index 0000000..0b47241
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/TFTP/tftp.h
@@ -0,0 +1,93 @@
+/**
+ * @file tftp.h
+ * @brief TFTP Header File.
+ * @version 0.1.0
+ * @author Sang-sik Kim
+ */
+#ifndef __TFTP_H__
+#define __TFTP_H__
+
+#include
+
+#define F_APP_TFTP
+#define __TFTP_DEBUG__
+
+#define F_STORAGE // If your target support a storage, you have to activate this feature and implement.
+
+#define SOCK_TFTP 1
+
+#define INFO_DBG 0x01
+#define ERROR_DBG 0x02
+#define DEBUG_DBG 0x04
+#define IPC_DBG 0x08
+
+#define DBG_PRINT(level, format, args...) { \
+ if(dbg_level & level) \
+ printf(format, ##args); \
+ }
+
+#define NORMAL_MODE 0
+#define TFTP_MODE 1
+
+extern int dbg_level;
+
+/* tftp message */
+#define TFTP_RRQ 1
+#define TFTP_WRQ 2
+#define TFTP_DATA 3
+#define TFTP_ACK 4
+#define TFTP_ERROR 5
+#define TFTP_OACK 6
+
+/* tftp state */
+#define STATE_NONE 0
+#define STATE_RRQ 1
+#define STATE_WRQ 2
+#define STATE_DATA 3
+#define STATE_ACK 4
+#define STATE_OACK 5
+
+/* tftp transfer mode */
+#define TRANS_ASCII "netascii"
+#define TRANS_BINARY "octet"
+
+/* tftp progress state */
+#define TFTP_PROGRESS 0
+#define TFTP_FAIL 1
+#define TFTP_SUCCESS 2
+
+/* define */
+#define TFTP_SERVER_PORT 69
+#define TFTP_TEMP_PORT 51000
+#define TFTP_BLK_SIZE 512
+#define MAX_MTU_SIZE 1514
+#define FILE_NAME_SIZE 20
+
+//#define __TFTP_DEBUG__
+
+/* typedef */
+typedef struct tftp_data {
+ uint16_t opcode;
+ uint16_t block_num;
+ uint8_t data[0];
+} TFTP_DATA_T;
+
+typedef struct tftp_error {
+ uint16_t opcode;
+ uint16_t error_code;
+ uint8_t error_msg[0];
+} TFTP_ERROR_T;
+
+typedef struct tftp_option {
+ uint8_t *code;
+ uint8_t *value;
+} TFTP_OPTION;
+
+/* Functions */
+void TFTP_init(uint8_t socket, uint8_t *buf);
+void TFTP_exit(void);
+int TFTP_run(void);
+void TFTP_read_request(uint32_t server_ip, uint8_t *filename);
+void tftp_timeout_handler(void);
+
+#endif /*__TFTP_H__ */
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpParser.c b/WIZ550S2E_App/src/Internet/httpServer/httpParser.c
new file mode 100644
index 0000000..3d353e3
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpParser.c
@@ -0,0 +1,402 @@
+/**
+ @file httpd.c
+ @brief functions associated http processing
+ */
+
+#include
+#include
+#include "socket.h"
+#include "httpParser.h"
+
+/*****************************************************************************
+ * Public types/enumerations/variables
+ ****************************************************************************/
+//uint8_t BUFPUB[2048];
+uint8_t BUFPUB[256];
+
+/*****************************************************************************
+ * Private functions
+ ****************************************************************************/
+static void replacetochar(uint8_t * str, uint8_t oldchar, uint8_t newchar); /* Replace old character with new character in the string */
+static uint8_t C2D(uint8_t c); /* Convert a character to HEX */
+
+/**
+ @brief convert escape characters(%XX) to ASCII character
+ */
+void unescape_http_url(
+ char * url /**< pointer to be converted ( escape characters )*/
+ )
+{
+ int x, y;
+
+ for (x = 0, y = 0; url[y]; ++x, ++y) {
+ if ((url[x] = url[y]) == '%') {
+ url[x] = C2D(url[y+1])*0x10+C2D(url[y+2]);
+ y+=2;
+ }
+ }
+ url[x] = '\0';
+}
+
+
+/**
+ @brief make response header such as html, gif, jpeg,etc.
+ */
+void make_http_response_head(
+ char * buf, /**< pointer to response header to be made */
+ char type, /**< response type */
+ uint32_t len /**< size of response header */
+ )
+{
+ char * head;
+ char tmp[10];
+
+ /* file type*/
+ if (type == PTYPE_HTML) head = RES_HTMLHEAD_OK;
+ else if (type == PTYPE_GIF) head = RES_GIFHEAD_OK;
+ else if (type == PTYPE_TEXT) head = RES_TEXTHEAD_OK;
+ else if (type == PTYPE_JPEG) head = RES_JPEGHEAD_OK;
+ else if (type == PTYPE_FLASH) head = RES_FLASHHEAD_OK;
+ else if (type == PTYPE_XML) head = RES_XMLHEAD_OK;
+ else if (type == PTYPE_CSS) head = RES_CSSHEAD_OK;
+ else if (type == PTYPE_JSON) head = RES_JSONHEAD_OK;
+ else if (type == PTYPE_JS) head = RES_JSHEAD_OK;
+ else if (type == PTYPE_CGI) head = RES_CGIHEAD_OK;
+ else if (type == PTYPE_PNG) head = RES_PNGHEAD_OK;
+ else if (type == PTYPE_ICO) head = RES_ICOHEAD_OK;
+ else if (type == PTYPE_TTF) head = RES_TTFHEAD_OK;
+ else if (type == PTYPE_OTF) head = RES_OTFHEAD_OK;
+ else if (type == PTYPE_WOFF) head = RES_WOFFHEAD_OK;
+ else if (type == PTYPE_EOT) head = RES_EOTHEAD_OK;
+ else if (type == PTYPE_SVG) head = RES_SVGHEAD_OK;
+#ifdef _HTTPPARSER_DEBUG_
+ else
+ {
+ head = NULL;
+ printf("\r\n\r\n-MAKE HEAD UNKNOWN-\r\n");
+ }
+#else
+ else head = NULL;
+#endif
+
+ sprintf(tmp, "%ld", len);
+ strcpy(buf, head);
+ strcat(buf, tmp);
+ strcat(buf, "\r\n\r\n");
+}
+
+
+/**
+ @brief find MIME type of a file
+ */
+void find_http_uri_type(
+ uint8_t * type, /**< type to be returned */
+ uint8_t * buff /**< file name */
+ )
+{
+ /* Decide type according to extension*/
+
+ char * buf;
+ buf = (char *)buff;
+
+ if (strstr(buf, ".htm") || strstr(buf, ".html")) *type = PTYPE_HTML;
+ else if (strstr(buf, ".gif")) *type = PTYPE_GIF;
+ else if (strstr(buf, ".text") || strstr(buf,".txt")) *type = PTYPE_TEXT;
+ else if (strstr(buf, ".jpeg") || strstr(buf,".jpg")) *type = PTYPE_JPEG;
+ else if (strstr(buf, ".swf")) *type = PTYPE_FLASH;
+ else if (strstr(buf, ".cgi") || strstr(buf,".CGI")) *type = PTYPE_CGI;
+ else if (strstr(buf, ".json") || strstr(buf,".JSON")) *type = PTYPE_JSON;
+ else if (strstr(buf, ".js") || strstr(buf,".JS")) *type = PTYPE_JS;
+ else if (strstr(buf, ".CGI") || strstr(buf,".cgi")) *type = PTYPE_CGI;
+ else if (strstr(buf, ".xml") || strstr(buf,".XML")) *type = PTYPE_XML;
+ else if (strstr(buf, ".css") || strstr(buf,".CSS")) *type = PTYPE_CSS;
+ else if (strstr(buf, ".png") || strstr(buf,".PNG")) *type = PTYPE_PNG;
+ else if (strstr(buf, ".ico") || strstr(buf,".ICO")) *type = PTYPE_ICO;
+ else if (strstr(buf, ".ttf") || strstr(buf,".TTF")) *type = PTYPE_TTF;
+ else if (strstr(buf, ".otf") || strstr(buf,".OTF")) *type = PTYPE_OTF;
+ else if (strstr(buf, ".woff") || strstr(buf,".WOFF")) *type = PTYPE_WOFF;
+ else if (strstr(buf, ".eot") || strstr(buf,".EOT")) *type = PTYPE_EOT;
+ else if (strstr(buf, ".svg") || strstr(buf,".SVG")) *type = PTYPE_SVG;
+ else *type = PTYPE_ERR;
+}
+
+
+/**
+ @brief parse http request from a peer
+ */
+void parse_http_request(
+ st_http_request * request, /**< request to be returned */
+ uint8_t * buf /**< pointer to be parsed */
+ )
+{
+ char * nexttok;
+ nexttok = strtok((char*)buf," ");
+ if(!nexttok)
+ {
+ request->METHOD = METHOD_ERR;
+ return;
+ }
+ if(!strcmp(nexttok, "GET") || !strcmp(nexttok,"get"))
+ {
+ request->METHOD = METHOD_GET;
+ nexttok = strtok(NULL," ");
+
+ }
+ else if (!strcmp(nexttok, "HEAD") || !strcmp(nexttok,"head"))
+ {
+ request->METHOD = METHOD_HEAD;
+ nexttok = strtok(NULL," ");
+
+ }
+ else if (!strcmp(nexttok, "POST") || !strcmp(nexttok,"post"))
+ {
+ nexttok = strtok(NULL,"\0");
+ request->METHOD = METHOD_POST;
+ }
+ else
+ {
+ request->METHOD = METHOD_ERR;
+ }
+
+ if(!nexttok)
+ {
+ request->METHOD = METHOD_ERR;
+ return;
+ }
+ strcpy((char *)request->URI, nexttok);
+}
+
+#ifdef _OLD_
+/**
+ @brief get next parameter value in the request
+ */
+uint8_t * get_http_param_value(
+ char* uri,
+ char* param_name
+ )
+{
+ char tempURI[MAX_URI_SIZE];
+ uint8_t * name = 0;
+
+
+ if(!uri || !param_name) return 0;
+
+ strcpy((char*)tempURI,uri);
+ if((name = (uint8_t*)strstr(tempURI, param_name)))
+ {
+ name += strlen(param_name) + 1; // strlen(para_name) + strlen("=")
+ if((name = (uint8_t*)strtok((char *)name,"& \r\n\t\0")))
+ {
+ unescape_http_url((char *)name);
+ replacetochar(name, '+', ' ');
+ }
+ }
+#ifdef _HTTPPARSER_DEBUG_
+ printf(" %s=%s",param_name,name);
+#endif
+
+ return name;
+}
+#else
+/**
+ @brief get next parameter value in the request
+ */
+uint8_t * get_http_param_value(char* uri, char* param_name)
+{
+
+ uint8_t * name = 0;
+ uint8_t * ret = BUFPUB;
+ uint8_t * pos2;
+ uint16_t len = 0, content_len = 0;
+ uint8_t tmp_buf[10]={0x00, };
+
+ if(!uri || !param_name) return 0;
+
+ /***************/
+ mid(uri, "Content-Length: ", "\r\n", (char *)tmp_buf);
+ content_len = ATOI(tmp_buf, 10);
+ uri = strstr(uri, "\r\n\r\n");
+ uri += 4;
+ uri[content_len] = 0;
+ /***************/
+
+ if((name = (uint8_t *)strstr(uri, param_name)))
+ {
+ name += strlen(param_name) + 1;
+ pos2 = (uint8_t*)strstr((char*)name, "&");
+ if(!pos2)
+ {
+ pos2 = name + strlen((char*)name);
+ }
+ len = pos2 - name;
+
+ if(len)
+ {
+ ret[len] = 0;
+ strncpy((char*)ret,(char*)name, len);
+ unescape_http_url((char *)ret);
+ replacetochar(ret, '+' ,' ');
+ //ret[len] = 0;
+ //ret[strlen((int8*)ret)] = 0;
+ //printf("len=%d\r\n",len);
+ }
+ else
+ {
+ ret[0] = 0;
+ }
+ }
+ else
+ {
+ return 0;
+ }
+#ifdef _HTTPPARSER_DEBUG_
+ printf(" %s=%s\r\n", param_name, ret);
+#endif
+ return ret;
+}
+#endif
+
+#ifdef _OLD_
+uint8_t * get_http_uri_name(uint8_t * uri)
+{
+ char tempURI[MAX_URI_SIZE];
+ uint8_t * uri_name;
+
+ if(!uri) return 0;
+
+ strcpy(tempURI, (char *)uri);
+
+ uri_name = (uint8_t *)strtok(tempURI, " ?");
+
+ if(strcmp((char *)uri_name,"/")) uri_name++;
+
+#ifdef _HTTPPARSER_DEBUG_
+ printf(" uri_name = %s\r\n", uri_name);
+#endif
+
+ return uri_name;
+}
+#else
+
+uint8_t get_http_uri_name(uint8_t * uri, uint8_t * uri_buf)
+{
+ uint8_t * uri_ptr;
+ if(!uri) return 0;
+
+ strcpy((char *)uri_buf, (char *)uri);
+
+ uri_ptr = (uint8_t *)strtok((char *)uri_buf, " ?");
+
+ if(strcmp((char *)uri_ptr,"/")) uri_ptr++;
+ strcpy((char *)uri_buf, (char *)uri_ptr);
+
+#ifdef _HTTPPARSER_DEBUG_
+ printf(" uri_name = %s\r\n", uri_buf);
+#endif
+
+ return 1;
+}
+
+#endif
+
+void inet_addr_(uint8_t * addr, uint8_t *ip)
+{
+ uint8_t i;
+ uint8_t taddr[30];
+ uint8_t * nexttok;
+ uint8_t num;
+
+ strcpy((char *)taddr, (char *)addr);
+
+ nexttok = taddr;
+ for(i = 0; i < 4 ; i++)
+ {
+ nexttok = (uint8_t *)strtok((char *)nexttok, ".");
+ if(nexttok[0] == '0' && nexttok[1] == 'x') num = ATOI(nexttok+2,0x10);
+ else num = ATOI(nexttok,10);
+ ip[i] = num;
+ nexttok = NULL;
+ }
+}
+
+
+/**
+@brief CONVERT STRING INTO INTEGER
+@return a integer number
+*/
+uint16_t ATOI(
+ uint8_t * str, /**< is a pointer to convert */
+ uint8_t base /**< is a base value (must be in the range 2 - 16) */
+ )
+{
+ unsigned int num = 0;
+// debug_2013_11_25
+// while (*str !=0)
+ while ((*str !=0) && (*str != 0x20)) // not include the space(0x020)
+ num = num * base + C2D(*str++);
+ return num;
+}
+
+/**
+ * @brief Check strings and then execute callback function by each string.
+ * @param src The information of URI
+ * @param s1 The start string to be researched
+ * @param s2 The end string to be researched
+ * @param sub The string between s1 and s2
+ * @return The length value atfer working
+ */
+void mid(char* src, char* s1, char* s2, char* sub)
+{
+ char* sub1;
+ char* sub2;
+ uint16_t n;
+
+ sub1=strstr((char*)src,(char*)s1);
+ sub1+=strlen((char*)s1);
+ sub2=strstr((char*)sub1,(char*)s2);
+
+ n=sub2-sub1;
+ strncpy((char*)sub,(char*)sub1,n);
+ sub[n]='\0';
+}
+
+////////////////////////////////////////////////////////////////////
+// Static functions
+////////////////////////////////////////////////////////////////////
+
+/**
+@brief replace the specified character in a string with new character
+*/
+static void replacetochar(
+ uint8_t * str, /**< pointer to be replaced */
+ uint8_t oldchar, /**< old character */
+ uint8_t newchar /**< new character */
+ )
+{
+ int x;
+ for (x = 0; str[x]; x++)
+ if (str[x] == oldchar) str[x] = newchar;
+}
+
+/**
+@brief CONVERT CHAR INTO HEX
+@return HEX
+
+This function converts HEX(0-F) to a character
+*/
+static uint8_t C2D(
+ uint8_t c /**< is a character('0'-'F') to convert to HEX */
+ )
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'a' && c <= 'f')
+ return 10 + c -'a';
+ if (c >= 'A' && c <= 'F')
+ return 10 + c -'A';
+
+ return (char)c;
+}
+
+
+
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpParser.h b/WIZ550S2E_App/src/Internet/httpServer/httpParser.h
new file mode 100644
index 0000000..888c337
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpParser.h
@@ -0,0 +1,150 @@
+/**
+ @file httpd.h
+ @brief Define Constants and fucntions associated with HTTP protocol.
+ */
+
+#include
+
+#ifndef __HTTPPARSER_H__
+#define __HTTPPARSER_H__
+
+//#define _HTTPPARSER_DEBUG_
+
+#define HTTP_SERVER_PORT 80 /**< HTTP server well-known port number */
+
+/* HTTP Method */
+#define METHOD_ERR 0 /**< Error Method. */
+#define METHOD_GET 1 /**< GET Method. */
+#define METHOD_HEAD 2 /**< HEAD Method. */
+#define METHOD_POST 3 /**< POST Method. */
+
+/* HTTP GET Method */
+#define PTYPE_ERR 0 /**< Error file. */
+#define PTYPE_HTML 1 /**< HTML file. */
+#define PTYPE_GIF 2 /**< GIF file. */
+#define PTYPE_TEXT 3 /**< TEXT file. */
+#define PTYPE_JPEG 4 /**< JPEG file. */
+#define PTYPE_FLASH 5 /**< FLASH file. */
+#define PTYPE_MPEG 6 /**< MPEG file. */
+#define PTYPE_PDF 7 /**< PDF file. */
+#define PTYPE_CGI 8 /**< CGI file. */
+#define PTYPE_XML 9 /**< XML file. */
+#define PTYPE_CSS 10 /**< CSS file. */
+#define PTYPE_JS 11 /**< JavaScript file. */
+#define PTYPE_JSON 12 /**< JSON (JavaScript Standard Object Notation) file. */
+#define PTYPE_PNG 13 /**< PNG file. */
+#define PTYPE_ICO 14 /**< ICON file. */
+
+#define PTYPE_TTF 20 /**< Font type: TTF file. */
+#define PTYPE_OTF 21 /**< Font type: OTF file. */
+#define PTYPE_WOFF 22 /**< Font type: WOFF file. */
+#define PTYPE_EOT 23 /**< Font type: EOT file. */
+#define PTYPE_SVG 24 /**< Font type: SVG file. */
+
+
+/* HTTP response */
+#define STATUS_OK 200
+#define STATUS_CREATED 201
+#define STATUS_ACCEPTED 202
+#define STATUS_NO_CONTENT 204
+#define STATUS_MV_PERM 301
+#define STATUS_MV_TEMP 302
+#define STATUS_NOT_MODIF 304
+#define STATUS_BAD_REQ 400
+#define STATUS_UNAUTH 401
+#define STATUS_FORBIDDEN 403
+#define STATUS_NOT_FOUND 404
+#define STATUS_INT_SERR 500
+#define STATUS_NOT_IMPL 501
+#define STATUS_BAD_GATEWAY 502
+#define STATUS_SERV_UNAVAIL 503
+
+/* HTML Doc. for ERROR */
+static const char ERROR_HTML_PAGE[] = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 78\r\n\r\n\r\n\r\nSorry, the page you requested was not found.\r\n\r\n\r\n\0";
+static const char ERROR_REQUEST_PAGE[] = "HTTP/1.1 400 OK\r\nContent-Type: text/html\r\nContent-Length: 50\r\n\r\n\r\n\r\nInvalid request.\r\n\r\n\r\n\0";
+
+/* HTML Doc. for CGI result */
+#define HTML_HEADER "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: "
+
+/* Response header for HTML*/
+#define RES_HTMLHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: keep-alive\r\nContent-Length: "
+
+/* Response head for TEXT */
+#define RES_TEXTHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: "
+
+/* Response head for GIF */
+#define RES_GIFHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\nContent-Length: "
+
+/* Response head for JPEG */
+#define RES_JPEGHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Length: "
+
+/* Response head for PNG */
+#define RES_PNGHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: "
+
+/* Response head for FLASH */
+#define RES_FLASHHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/x-shockwave-flash\r\nContent-Length: "
+
+/* Response head for XML */
+#define RES_XMLHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\nContent-Length: "
+
+/* Response head for CSS */
+#define RES_CSSHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: text/css\r\nContent-Length: "
+
+/* Response head for JavaScript */
+#define RES_JSHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: "
+
+/* Response head for JSON */
+#define RES_JSONHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: "
+
+/* Response head for ICO */
+#define RES_ICOHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: image/x-icon\r\nContent-Length: "
+
+/* Response head for CGI */
+#define RES_CGIHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: "
+
+/* Response head for TTF, Font */
+#define RES_TTFHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/x-font-truetype\r\nContent-Length: "
+
+/* Response head for OTF, Font */
+#define RES_OTFHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/x-font-opentype\r\nContent-Length: "
+
+/* Response head for WOFF, Font */
+#define RES_WOFFHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/font-woff\r\nContent-Length: "
+
+/* Response head for EOT, Font */
+#define RES_EOTHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.ms-fontobject\r\nContent-Length: "
+
+/* Response head for SVG, Font */
+#define RES_SVGHEAD_OK "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: "
+
+/**
+ @brief Structure of HTTP REQUEST
+ */
+
+//#define MAX_URI_SIZE 1461
+#define MAX_URI_SIZE 512
+
+typedef struct _st_http_request
+{
+ uint8_t METHOD; /**< request method(METHOD_GET...). */
+ uint8_t TYPE; /**< request type(PTYPE_HTML...). */
+ uint8_t URI[MAX_URI_SIZE]; /**< request file name. */
+}st_http_request;
+
+// HTTP Parsing functions
+void unescape_http_url(char * url); /* convert escape character to ascii */
+void parse_http_request(st_http_request *, uint8_t *); /* parse request from peer */
+void find_http_uri_type(uint8_t *, uint8_t *); /* find MIME type of a file */
+void make_http_response_head(char *, char, uint32_t); /* make response header */
+uint8_t * get_http_param_value(char* uri, char* param_name); /* get the user-specific parameter value */
+uint8_t get_http_uri_name(uint8_t * uri, uint8_t * uri_buf); /* get the requested URI name */
+#ifdef _OLD_
+uint8_t * get_http_uri_name(uint8_t * uri);
+#endif
+
+// Utility functions
+uint16_t ATOI(uint8_t * str, uint8_t base);
+void mid(char* src, char* s1, char* s2, char* sub);
+void inet_addr_(uint8_t * addr, uint8_t * ip);
+
+#endif /* end of __HTTPPARSER_H__ */
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpServer.c b/WIZ550S2E_App/src/Internet/httpServer/httpServer.c
new file mode 100644
index 0000000..3afadb7
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpServer.c
@@ -0,0 +1,749 @@
+#include
+#include
+#include
+
+#include "socket.h"
+#include "wizchip_conf.h"
+
+#include "httpServer.h"
+#include "httpParser.h"
+#include "httpUtil.h"
+
+#ifdef _USE_SDCARD_
+#include "ff.h" // header file for FatFs library (FAT file system)
+#endif
+
+#ifndef DATA_BUF_SIZE
+ #define DATA_BUF_SIZE 2048
+#endif
+
+/*****************************************************************************
+ * Private types/enumerations/variables
+ ****************************************************************************/
+static uint8_t HTTPSock_Num[_WIZCHIP_SOCK_NUM_] = {0, };
+static st_http_request * http_request; /**< Pointer to received HTTP request */
+static st_http_request * parsed_http_request; /**< Pointer to parsed HTTP request */
+static uint8_t * http_response; /**< Pointer to HTTP response */
+
+// ## For Debugging
+//static uint8_t uri_buf[128];
+
+// Number of registered web content in code flash memory
+static uint16_t total_content_cnt = 0;
+/*****************************************************************************
+ * Public types/enumerations/variables
+ ****************************************************************************/
+uint8_t * pHTTP_TX;
+uint8_t * pHTTP_RX;
+
+volatile uint32_t httpServer_tick_1s = 0;
+st_http_socket HTTPSock_Status[_WIZCHIP_SOCK_NUM_] = { {STATE_HTTP_IDLE, }, };
+httpServer_webContent web_content[MAX_CONTENT_CALLBACK];
+
+#ifdef _USE_SDCARD_
+FIL fs; // FatFs: File object
+FRESULT fr; // FatFs: File function return code
+#endif
+
+/*****************************************************************************
+ * Private functions
+ ****************************************************************************/
+void httpServer_Sockinit(uint8_t cnt, uint8_t * socklist);
+static uint8_t getHTTPSocketNum(uint8_t seqnum);
+static int8_t getHTTPSequenceNum(uint8_t socket);
+static int8_t http_disconnect(uint8_t sn);
+
+static void http_process_handler(uint8_t s, st_http_request * p_http_request);
+static void send_http_response_header(uint8_t s, uint8_t content_type, uint32_t body_len, uint16_t http_status);
+static void send_http_response_body(uint8_t s, uint8_t * uri_name, uint8_t * buf, uint32_t start_addr, uint32_t file_len);
+static void send_http_response_cgi(uint8_t s, uint8_t * buf, uint8_t * http_body, uint16_t file_len);
+
+/*****************************************************************************
+ * Public functions
+ ****************************************************************************/
+// Callback functions definition: MCU Reset / WDT Reset
+void default_mcu_reset(void) {;}
+void default_wdt_reset(void) {;}
+void (*HTTPServer_ReStart)(void) = default_mcu_reset;
+void (*HTTPServer_WDT_Reset)(void) = default_wdt_reset;
+
+void httpServer_Sockinit(uint8_t cnt, uint8_t * socklist)
+{
+ uint8_t i;
+
+ for(i = 0; i < cnt; i++)
+ {
+ // Mapping the H/W socket numbers to the sequential index numbers
+ HTTPSock_Num[i] = socklist[i];
+ }
+}
+
+static uint8_t getHTTPSocketNum(uint8_t seqnum)
+{
+ // Return the 'H/W socket number' corresponding to the index number
+ return HTTPSock_Num[seqnum];
+}
+
+static int8_t getHTTPSequenceNum(uint8_t socket)
+{
+ uint8_t i;
+
+ for(i = 0; i < _WIZCHIP_SOCK_NUM_; i++)
+ if(HTTPSock_Num[i] == socket) return i;
+
+ return -1;
+}
+
+void httpServer_init(uint8_t * tx_buf, uint8_t * rx_buf, uint8_t cnt, uint8_t * socklist)
+{
+ // User's shared buffer
+ pHTTP_TX = tx_buf;
+ pHTTP_RX = rx_buf;
+
+ // H/W Socket number mapping
+ httpServer_Sockinit(cnt, socklist);
+}
+
+
+/* Register the call back functions for HTTP Server */
+void reg_httpServer_cbfunc(void(*mcu_reset)(void), void(*wdt_reset)(void))
+{
+ // Callback: HW Reset and WDT reset function for each MCU platforms
+ if(mcu_reset) HTTPServer_ReStart = mcu_reset;
+ if(wdt_reset) HTTPServer_WDT_Reset = wdt_reset;
+}
+
+
+void httpServer_run(uint8_t seqnum)
+{
+ uint8_t s; // socket number
+ uint16_t len;
+ uint32_t gettime = 0;
+
+#ifdef _HTTPSERVER_DEBUG_
+ uint8_t destip[4] = {0, };
+ uint16_t destport = 0;
+#endif
+
+ http_request = (st_http_request *)pHTTP_RX; // Structure of HTTP Request
+ parsed_http_request = (st_http_request *)pHTTP_TX;
+
+ // Get the H/W socket number
+ s = getHTTPSocketNum(seqnum);
+
+ /* HTTP Service Start */
+ switch(getSn_SR(s))
+ {
+ case SOCK_ESTABLISHED:
+ // Interrupt clear
+ if(getSn_IR(s) & Sn_IR_CON)
+ {
+ setSn_IR(s, Sn_IR_CON);
+ }
+
+ // HTTP Process states
+ switch(HTTPSock_Status[seqnum].sock_status)
+ {
+
+ case STATE_HTTP_IDLE :
+ if ((len = getSn_RX_RSR(s)) > 0)
+ {
+ if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;
+ len = recv(s, (uint8_t *)http_request, len);
+
+ *(((uint8_t *)http_request) + len) = '\0';
+
+ parse_http_request(parsed_http_request, (uint8_t *)http_request);
+#ifdef _HTTPSERVER_DEBUG_
+ getSn_DIPR(s, destip);
+ destport = getSn_DPORT(s);
+ printf("\r\n");
+ printf("> HTTPSocket[%d] : HTTP Request received ", s);
+ printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
+#endif
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", s);
+#endif
+ // HTTP 'response' handler; includes send_http_response_header / body function
+ http_process_handler(s, parsed_http_request);
+
+ gettime = get_httpServer_timecount();
+ // Check the TX socket buffer for End of HTTP response sends
+ while(getSn_TX_FSR(s) != (getSn_TXBUF_SIZE(s)*1024))
+ {
+ if((get_httpServer_timecount() - gettime) > 3)
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE: TX Buffer clear timeout\r\n", s);
+#endif
+ break;
+ }
+ }
+
+ if(HTTPSock_Status[seqnum].file_len > 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_INPROC;
+ else HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
+ }
+ break;
+
+ case STATE_HTTP_RES_INPROC :
+ /* Repeat: Send the remain parts of HTTP responses */
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", s);
+#endif
+ // Repeatedly send remaining data to client
+ send_http_response_body(s, 0, http_response, 0, 0);
+
+ if(HTTPSock_Status[seqnum].file_len == 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
+ break;
+
+ case STATE_HTTP_RES_DONE :
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", s);
+#endif
+ // Socket file info structure re-initialize
+ HTTPSock_Status[seqnum].file_len = 0;
+ HTTPSock_Status[seqnum].file_offset = 0;
+ HTTPSock_Status[seqnum].file_start = 0;
+ HTTPSock_Status[seqnum].sock_status = STATE_HTTP_IDLE;
+
+//#ifdef _USE_SDCARD_
+// f_close(&fs);
+//#endif
+#ifdef _USE_WATCHDOG_
+ HTTPServer_WDT_Reset();
+#endif
+ http_disconnect(s);
+ break;
+
+ default :
+ break;
+ }
+ break;
+
+ case SOCK_CLOSE_WAIT:
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", s); // if a peer requests to close the current connection
+#endif
+ disconnect(s);
+ break;
+
+ case SOCK_CLOSED:
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : CLOSED\r\n", s);
+#endif
+ if(socket(s, Sn_MR_TCP, HTTP_SERVER_PORT, 0x00) == s) /* Reinitialize the socket */
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : OPEN\r\n", s);
+#endif
+ }
+ break;
+
+ case SOCK_INIT:
+ listen(s);
+ break;
+
+ case SOCK_LISTEN:
+ break;
+
+ default :
+ break;
+
+ } // end of switch
+
+#ifdef _USE_WATCHDOG_
+ HTTPServer_WDT_Reset();
+#endif
+}
+
+////////////////////////////////////////////
+// Private Functions
+////////////////////////////////////////////
+static void send_http_response_header(uint8_t s, uint8_t content_type, uint32_t body_len, uint16_t http_status)
+{
+ switch(http_status)
+ {
+ case STATUS_OK: // HTTP/1.1 200 OK
+ if((content_type != PTYPE_CGI) && (content_type != PTYPE_XML)) // CGI/XML type request does not respond HTTP header
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header - STATUS_OK\r\n", s);
+#endif
+ make_http_response_head((char*)http_response, content_type, body_len);
+ }
+ else
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header - NONE / CGI or XML\r\n", s);
+#endif
+ // CGI/XML type request does not respond HTTP header to client
+ http_status = 0;
+ }
+ break;
+ case STATUS_BAD_REQ: // HTTP/1.1 400 OK
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header - STATUS_BAD_REQ\r\n", s);
+#endif
+ memcpy(http_response, ERROR_REQUEST_PAGE, sizeof(ERROR_REQUEST_PAGE));
+ break;
+ case STATUS_NOT_FOUND: // HTTP/1.1 404 Not Found
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header - STATUS_NOT_FOUND\r\n", s);
+#endif
+ memcpy(http_response, ERROR_HTML_PAGE, sizeof(ERROR_HTML_PAGE));
+ break;
+ default:
+ break;
+ }
+
+ // Send the HTTP Response 'header'
+ if(http_status)
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [Send] HTTP Response Header [ %d ]byte\r\n", s, (uint16_t)strlen((char *)http_response));
+#endif
+ send(s, http_response, strlen((char *)http_response));
+ }
+}
+
+static void send_http_response_body(uint8_t s, uint8_t * uri_name, uint8_t * buf, uint32_t start_addr, uint32_t file_len)
+{
+ int8_t get_seqnum;
+ uint32_t send_len;
+
+ uint8_t flag_datasend_end = 0;
+
+#ifdef _USE_SDCARD_
+ uint16_t blocklen;
+#endif
+#ifdef _USE_FLASH_
+ uint32_t addr = 0;
+#endif
+
+ if((get_seqnum = getHTTPSequenceNum(s)) == -1) return; // exception handling; invalid number
+
+ // Send the HTTP Response 'body'; requested file
+ if(!HTTPSock_Status[get_seqnum].file_len) // ### Send HTTP response body: First part ###
+ {
+ if (file_len > DATA_BUF_SIZE - 1)
+ {
+ HTTPSock_Status[get_seqnum].file_start = start_addr;
+ HTTPSock_Status[get_seqnum].file_len = file_len;
+ send_len = DATA_BUF_SIZE - 1;
+
+/////////////////////////////////////////////////////////////////////////////////////////////////
+// ## 20141219 Eric added, for 'File object structure' (fs) allocation reduced (8 -> 1)
+ memset(HTTPSock_Status[get_seqnum].file_name, 0x00, MAX_CONTENT_NAME_LEN);
+ strcpy((char *)HTTPSock_Status[get_seqnum].file_name, (char *)uri_name);
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response body - file name [ %s ]\r\n", s, HTTPSock_Status[get_seqnum].file_name);
+#endif
+/////////////////////////////////////////////////////////////////////////////////////////////////
+
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response body - file len [ %ld ]byte\r\n", s, file_len);
+#endif
+ }
+ else
+ {
+ // Send process end
+ send_len = file_len;
+
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response end - file len [ %ld ]byte\r\n", s, send_len);
+#endif
+ }
+#ifdef _USE_FLASH_
+ if(HTTPSock_Status[get_seqnum]->storage_type == DATAFLASH) addr = start_addr;
+#endif
+ }
+ else // remained parts
+ {
+#ifdef _USE_FLASH_
+ if(HTTPSock_Status[get_seqnum]->storage_type == DATAFLASH)
+ {
+ addr = HTTPSock_Status[get_seqnum].file_start + HTTPSock_Status[get_seqnum].file_offset;
+ }
+#endif
+ send_len = HTTPSock_Status[get_seqnum].file_len - HTTPSock_Status[get_seqnum].file_offset;
+
+ if(send_len > DATA_BUF_SIZE - 1)
+ {
+ send_len = DATA_BUF_SIZE - 1;
+ //HTTPSock_Status[get_seqnum]->file_offset += send_len;
+ }
+ else
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response end - file len [ %ld ]byte\r\n", s, HTTPSock_Status[get_seqnum].file_len);
+#endif
+ // Send process end
+ flag_datasend_end = 1;
+ }
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response body - send len [ %ld ]byte\r\n", s, send_len);
+#endif
+ }
+
+/*****************************************************/
+ //HTTPSock_Status[get_seqnum]->storage_type == NONE
+ //HTTPSock_Status[get_seqnum]->storage_type == CODEFLASH
+ //HTTPSock_Status[get_seqnum]->storage_type == SDCARD
+ //HTTPSock_Status[get_seqnum]->storage_type == DATAFLASH
+/*****************************************************/
+
+ if(HTTPSock_Status[get_seqnum].storage_type == CODEFLASH)
+ {
+ if(HTTPSock_Status[get_seqnum].file_len) start_addr = HTTPSock_Status[get_seqnum].file_start;
+ read_userReg_webContent(start_addr, &buf[0], HTTPSock_Status[get_seqnum].file_offset, send_len);
+ }
+#ifdef _USE_SDCARD_
+ else if(HTTPSock_Status[get_seqnum].storage_type == SDCARD)
+ {
+ // Data read from SD Card
+ fr = f_read(&fs, &buf[0], send_len, (void *)&blocklen);
+ if(fr != FR_OK)
+ {
+ send_len = 0;
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [FatFs] Error code return: %d (File Read) / HTTP Send Failed - %s\r\n", s, fr, HTTPSock_Status[get_seqnum].file_name);
+#endif
+ }
+ else
+ {
+ *(buf+send_len+1) = 0; // Insert '/0' for indicates the 'End of String' (null terminated)
+ }
+ }
+#endif
+
+#ifdef _USE_FLASH_
+ else if(HTTPSock_Status[get_seqnum]->storage_type == DATAFLASH)
+ {
+ // Data read from external data flash memory
+ read_from_flashbuf(addr, &buf[0], send_len);
+ *(buf+send_len+1) = 0; // Insert '/0' for indicates the 'End of String' (null terminated)
+ }
+#endif
+ else
+ {
+ send_len = 0;
+ }
+ // Requested content send to HTTP client
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [Send] HTTP Response body [ %ld ]byte\r\n", s, send_len);
+#endif
+
+ if(send_len) send(s, buf, send_len);
+ else flag_datasend_end = 1;
+
+ if(flag_datasend_end)
+ {
+ HTTPSock_Status[get_seqnum].file_start = 0;
+ HTTPSock_Status[get_seqnum].file_len = 0;
+ HTTPSock_Status[get_seqnum].file_offset = 0;
+ flag_datasend_end = 0;
+ }
+ else
+ {
+ HTTPSock_Status[get_seqnum].file_offset += send_len;
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response body - offset [ %ld ]\r\n", s, HTTPSock_Status[get_seqnum].file_offset);
+#endif
+ }
+
+// ## 20141219 Eric added, for 'File object structure' (fs) allocation reduced (8 -> 1)
+#ifdef _USE_SDCARD_
+ f_close(&fs);
+#endif
+// ## 20141219 added end
+}
+
+static void send_http_response_cgi(uint8_t s, uint8_t * buf, uint8_t * http_body, uint16_t file_len)
+{
+ uint16_t send_len = 0;
+
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header + Body - CGI\r\n", s);
+#endif
+ send_len = sprintf((char *)buf, "%s%d\r\n\r\n%s", RES_CGIHEAD_OK, file_len, http_body);
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : HTTP Response Header + Body - send len [ %d ]byte\r\n", s, send_len);
+#endif
+
+ send(s, buf, send_len);
+}
+
+
+static int8_t http_disconnect(uint8_t sn)
+{
+ setSn_CR(sn,Sn_CR_DISCON);
+ /* wait to process the command... */
+ while(getSn_CR(sn));
+
+ return SOCK_OK;
+}
+
+
+static void http_process_handler(uint8_t s, st_http_request * p_http_request)
+{
+ uint8_t * uri_name;
+ uint32_t content_addr = 0;
+ uint16_t content_num = 0;
+ uint32_t file_len = 0;
+
+ uint8_t uri_buf[MAX_URI_SIZE]={0x00, };
+
+ uint16_t http_status;
+ int8_t get_seqnum;
+ uint8_t content_found;
+
+ if((get_seqnum = getHTTPSequenceNum(s)) == -1) return; // exception handling; invalid number
+
+ http_status = 0;
+ http_response = pHTTP_RX;
+ file_len = 0;
+
+ //method Analyze
+ switch (p_http_request->METHOD)
+ {
+ case METHOD_ERR :
+ http_status = STATUS_BAD_REQ;
+ send_http_response_header(s, 0, 0, http_status);
+ break;
+
+ case METHOD_HEAD :
+ case METHOD_GET :
+ get_http_uri_name(p_http_request->URI, uri_buf);
+ uri_name = uri_buf;
+
+ if (!strcmp((char *)uri_name, "/")) strcpy((char *)uri_name, INITIAL_WEBPAGE); // If URI is "/", respond by index.html
+ if (!strcmp((char *)uri_name, "m")) strcpy((char *)uri_name, M_INITIAL_WEBPAGE);
+ if (!strcmp((char *)uri_name, "mobile")) strcpy((char *)uri_name, MOBILE_INITIAL_WEBPAGE);
+ find_http_uri_type(&p_http_request->TYPE, uri_name); // Checking requested file types (HTML, TEXT, GIF, JPEG and Etc. are included)
+
+#ifdef _HTTPSERVER_DEBUG_
+ printf("\r\n> HTTPSocket[%d] : HTTP Method GET\r\n", s);
+ printf("> HTTPSocket[%d] : Request Type = %d\r\n", s, p_http_request->TYPE);
+ printf("> HTTPSocket[%d] : Request URI = %s\r\n", s, uri_name);
+#endif
+
+ if(p_http_request->TYPE == PTYPE_CGI)
+ {
+ content_found = http_get_cgi_handler(uri_name, pHTTP_TX, &file_len);
+ if(content_found && (file_len <= (DATA_BUF_SIZE-(strlen(RES_CGIHEAD_OK)+8))))
+ {
+ send_http_response_cgi(s, http_response, pHTTP_TX, (uint16_t)file_len);
+ }
+ else
+ {
+ send_http_response_header(s, PTYPE_CGI, 0, STATUS_NOT_FOUND);
+ }
+ }
+ else
+ {
+ // Find the User registered index for web content
+ if(find_userReg_webContent(uri_buf, &content_num, &file_len))
+ {
+ content_found = 1; // Web content found in code flash memory
+ content_addr = (uint32_t)content_num;
+ HTTPSock_Status[get_seqnum].storage_type = CODEFLASH;
+ }
+ // Not CGI request, Web content in 'SD card' or 'Data flash' requested
+#ifdef _USE_SDCARD_
+#ifdef _HTTPSERVER_DEBUG_
+ printf("\r\n> HTTPSocket[%d] : Searching the requested content\r\n", s);
+#endif
+ if((fr = f_open(&fs, (const char *)uri_name, FA_READ)) == 0)
+ {
+ content_found = 1; // file open succeed
+
+ file_len = fs.fsize;
+ content_addr = fs.sclust;
+ HTTPSock_Status[get_seqnum].storage_type = SDCARD;
+ }
+#elif _USE_FLASH_
+ else if(/* Read content from Dataflash */)
+ {
+ content_found = 1;
+ HTTPSock_Status[get_seqnum]->storage_type = DATAFLASH;
+ ; // To do
+ }
+#endif
+ else
+ {
+ content_found = 0; // fail to find content
+ }
+
+ if(!content_found)
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : Unknown Page Request\r\n", s);
+#endif
+ http_status = STATUS_NOT_FOUND;
+ }
+ else
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : Find Content [%s] ok - Start [%ld] len [ %ld ]byte\r\n", s, uri_name, content_addr, file_len);
+#endif
+ http_status = STATUS_OK;
+ }
+
+ // Send HTTP header
+ if(http_status)
+ {
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : Requested content len = [ %ld ]byte\r\n", s, file_len);
+#endif
+ send_http_response_header(s, p_http_request->TYPE, file_len, http_status);
+ }
+
+ // Send HTTP body (content)
+ if(http_status == STATUS_OK)
+ {
+ send_http_response_body(s, uri_name, http_response, content_addr, file_len);
+ }
+ }
+ break;
+
+ case METHOD_POST :
+ mid((char *)p_http_request->URI, "/", " HTTP", (char *)uri_buf);
+ uri_name = uri_buf;
+ find_http_uri_type(&p_http_request->TYPE, uri_name); // Check file type (HTML, TEXT, GIF, JPEG are included)
+
+#ifdef _HTTPSERVER_DEBUG_
+ printf("\r\n> HTTPSocket[%d] : HTTP Method POST\r\n", s);
+ printf("> HTTPSocket[%d] : Request URI = %s ", s, uri_name);
+ printf("Type = %d\r\n", p_http_request->TYPE);
+#endif
+
+ if(p_http_request->TYPE == PTYPE_CGI) // HTTP POST Method; CGI Process
+ {
+ content_found = http_post_cgi_handler(uri_name, p_http_request, http_response, &file_len);
+#ifdef _HTTPSERVER_DEBUG_
+ printf("> HTTPSocket[%d] : [CGI: %s] / Response len [ %ld ]byte\r\n", s, content_found?"Content found":"Content not found", file_len);
+#endif
+ if(content_found && (file_len <= (DATA_BUF_SIZE-(strlen(RES_CGIHEAD_OK)+8))))
+ {
+ send_http_response_cgi(s, pHTTP_TX, http_response, (uint16_t)file_len);
+
+ // Reset the H/W for apply to the change configuration information
+ if(content_found == HTTP_RESET) HTTPServer_ReStart();
+ }
+ else
+ {
+ send_http_response_header(s, PTYPE_CGI, 0, STATUS_NOT_FOUND);
+ }
+ }
+ else // HTTP POST Method; Content not found
+ {
+ send_http_response_header(s, 0, 0, STATUS_NOT_FOUND);
+ }
+ break;
+
+ default :
+ http_status = STATUS_BAD_REQ;
+ send_http_response_header(s, 0, 0, http_status);
+ break;
+ }
+}
+
+void httpServer_time_handler(void)
+{
+ httpServer_tick_1s++;
+}
+
+uint32_t get_httpServer_timecount(void)
+{
+ return httpServer_tick_1s;
+}
+
+void reg_httpServer_webContent(uint8_t * content_name, uint8_t * content)
+{
+ uint16_t name_len;
+ uint32_t content_len;
+
+ if(content_name == NULL || content == NULL)
+ {
+ return;
+ }
+ else if(total_content_cnt >= MAX_CONTENT_CALLBACK)
+ {
+ return;
+ }
+
+ name_len = strlen((char *)content_name);
+ content_len = strlen((char *)content);
+
+ web_content[total_content_cnt].content_name = malloc(name_len+1);
+ strcpy((char *)web_content[total_content_cnt].content_name, (const char *)content_name);
+ web_content[total_content_cnt].content_len = content_len;
+ web_content[total_content_cnt].content = content;
+
+ total_content_cnt++;
+}
+
+uint8_t display_reg_webContent_list(void)
+{
+ uint16_t i;
+ uint8_t ret;
+
+ if(total_content_cnt == 0)
+ {
+ printf(">> Web content file not found\r\n");
+ ret = 0;
+ }
+ else
+ {
+ printf("\r\n=== List of Web content in code flash ===\r\n");
+ for(i = 0; i < total_content_cnt; i++)
+ {
+ printf(" [%d] ", i+1);
+ printf("%s, ", web_content[i].content_name);
+ printf("%ld byte, ", web_content[i].content_len);
+
+ if(web_content[i].content_len < 30) printf("[%s]\r\n", web_content[i].content);
+ else printf("[ ... ]\r\n");
+ }
+ printf("=========================================\r\n\r\n");
+ ret = 1;
+ }
+
+ return ret;
+}
+
+uint8_t find_userReg_webContent(uint8_t * content_name, uint16_t * content_num, uint32_t * file_len)
+{
+ uint16_t i;
+ uint8_t ret = 0; // '0' means 'File Not Found'
+
+ for(i = 0; i < total_content_cnt; i++)
+ {
+ if(!strcmp((char *)content_name, (char *)web_content[i].content_name))
+ {
+ *file_len = web_content[i].content_len;
+ *content_num = i;
+ ret = 1; // If the requested content found, ret set to '1' (Found)
+ break;
+ }
+ }
+ return ret;
+}
+
+
+uint16_t read_userReg_webContent(uint16_t content_num, uint8_t * buf, uint32_t offset, uint16_t size)
+{
+ uint16_t ret = 0;
+ uint8_t * ptr;
+
+ if(content_num > total_content_cnt) return 0;
+
+ ptr = web_content[content_num].content;
+ if(offset) ptr += offset;
+
+ strncpy((char *)buf, (char *)ptr, size);
+ *(buf+size) = 0; // Insert '/0' for indicates the 'End of String' (null terminated)
+
+ ret = strlen((void *)buf);
+ return ret;
+}
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpServer.h b/WIZ550S2E_App/src/Internet/httpServer/httpServer.h
new file mode 100644
index 0000000..6676d85
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpServer.h
@@ -0,0 +1,103 @@
+/**
+ @file httpServer.h
+ @brief Define constants and functions related HTTP Web server.
+ */
+
+#include
+
+#ifndef __HTTPSERVER_H__
+#define __HTTPSERVER_H__
+
+// HTTP Server debug message enable
+#define _HTTPSERVER_DEBUG_
+
+#define INITIAL_WEBPAGE "index.html"
+#define M_INITIAL_WEBPAGE "m/index.html"
+#define MOBILE_INITIAL_WEBPAGE "mobile/index.html"
+
+/* Web Server Content Storage Select */
+//#define _USE_SDCARD_
+#ifndef _USE_SDCARD_
+//#define _USE_FLASH_
+#endif
+
+#if !defined(_USE_SDCARD_) && !defined(_USE_FLASH_)
+#define _NOTUSED_STORAGE_
+#endif
+
+
+/* Watchdog timer */
+//#define _USE_WATCHDOG_
+
+/*********************************************
+* HTTP Process states list
+*********************************************/
+#define STATE_HTTP_IDLE 0 /* IDLE, Waiting for data received (TCP established) */
+#define STATE_HTTP_REQ_INPROC 1 /* Received HTTP request from HTTP client */
+#define STATE_HTTP_REQ_DONE 2 /* The end of HTTP request parse */
+#define STATE_HTTP_RES_INPROC 3 /* Sending the HTTP response to HTTP client (in progress) */
+#define STATE_HTTP_RES_DONE 4 /* The end of HTTP response send (HTTP transaction ended) */
+
+/*********************************************
+* HTTP Simple Return Value
+*********************************************/
+#define HTTP_FAILED 0
+#define HTTP_OK 1
+#define HTTP_RESET 2
+
+/*********************************************
+* HTTP Content NAME length
+*********************************************/
+#define MAX_CONTENT_NAME_LEN 128
+
+/*********************************************
+* HTTP Timeout
+*********************************************/
+#define HTTP_MAX_TIMEOUT_SEC 3 // Sec.
+
+typedef enum
+{
+ NONE, ///< Web storage none
+ CODEFLASH, ///< Code flash memory
+ SDCARD, ///< SD card
+ DATAFLASH ///< External data flash memory
+}StorageType;
+
+typedef struct _st_http_socket
+{
+ uint8_t sock_status;
+ uint8_t file_name[MAX_CONTENT_NAME_LEN];
+ uint32_t file_start;
+ uint32_t file_len;
+ uint32_t file_offset; // (start addr + sent size...)
+ uint8_t storage_type; // Storage type; Code flash, SDcard, Data flash ...
+}st_http_socket;
+
+// Web content structure for file in code flash memory
+#define MAX_CONTENT_CALLBACK 20
+
+typedef struct _httpServer_webContent
+{
+ uint8_t * content_name;
+ uint32_t content_len;
+ uint8_t * content;
+}httpServer_webContent;
+
+
+void httpServer_init(uint8_t * tx_buf, uint8_t * rx_buf, uint8_t cnt, uint8_t * socklist);
+void reg_httpServer_cbfunc(void(*mcu_reset)(void), void(*wdt_reset)(void));
+void httpServer_run(uint8_t seqnum);
+
+void reg_httpServer_webContent(uint8_t * content_name, uint8_t * content);
+uint8_t find_userReg_webContent(uint8_t * content_name, uint16_t * content_num, uint32_t * file_len);
+uint16_t read_userReg_webContent(uint16_t content_num, uint8_t * buf, uint32_t offset, uint16_t size);
+uint8_t display_reg_webContent_list(void);
+
+/*
+ * @brief HTTP Server 1sec Tick Timer handler
+ * @note SHOULD BE register to your system 1s Tick timer handler
+ */
+void httpServer_time_handler(void);
+uint32_t get_httpServer_timecount(void);
+
+#endif
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpUtil.c b/WIZ550S2E_App/src/Internet/httpServer/httpUtil.c
new file mode 100644
index 0000000..77c9a9d
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpUtil.c
@@ -0,0 +1,65 @@
+/**
+ * @file httpUtil.c
+ * @brief HTTP Server Utilities
+ * @version 1.0
+ * @date 2014/07/15
+ * @par Revision
+ * 2014/07/15 - 1.0 Release
+ * @author
+ * \n\n @par Copyright (C) 1998 - 2014 WIZnet. All rights reserved.
+ */
+
+#include
+#include
+#include
+#include "httpUtil.h"
+
+uint8_t http_get_cgi_handler(uint8_t * uri_name, uint8_t * buf, uint32_t * file_len)
+{
+ uint8_t ret = HTTP_OK;
+ uint16_t len = 0;
+
+ if(predefined_get_cgi_processor(uri_name, buf, &len))
+ {
+ ;
+ }
+ else if(strcmp((const char *)uri_name, "example.cgi") == 0)
+ {
+ // To do
+ ;
+ }
+ else
+ {
+ // CGI file not found
+ ret = HTTP_FAILED;
+ }
+
+ if(ret) *file_len = len;
+ return ret;
+}
+
+uint8_t http_post_cgi_handler(uint8_t * uri_name, st_http_request * p_http_request, uint8_t * buf, uint32_t * file_len)
+{
+ uint8_t ret = HTTP_OK;
+ uint16_t len = 0;
+ uint8_t val = 0;
+
+ if(predefined_set_cgi_processor(uri_name, p_http_request->URI, buf, &len))
+ {
+ ;
+ }
+ else if(strcmp((const char *)uri_name, "example.cgi") == 0)
+ {
+ // To do
+ val = 1;
+ len = sprintf((char *)buf, "%d", val);
+ }
+ else
+ {
+ // CGI file not found
+ ret = HTTP_FAILED;
+ }
+
+ if(ret) *file_len = len;
+ return ret;
+}
diff --git a/WIZ550S2E_App/src/Internet/httpServer/httpUtil.h b/WIZ550S2E_App/src/Internet/httpServer/httpUtil.h
new file mode 100644
index 0000000..b0a8dae
--- /dev/null
+++ b/WIZ550S2E_App/src/Internet/httpServer/httpUtil.h
@@ -0,0 +1,24 @@
+/**
+ * @file httpUtil.h
+ * @brief Header File for HTTP Server Utilities
+ * @version 1.0
+ * @date 2014/07/15
+ * @par Revision
+ * 2014/07/15 - 1.0 Release
+ * @author
+ * \n\n @par Copyright (C) 1998 - 2014 WIZnet. All rights reserved.
+ */
+
+#ifndef __HTTPUTIL_H__
+#define __HTTPUTIL_H__
+
+#include "httpServer.h"
+#include "httpParser.h"
+
+uint8_t http_get_cgi_handler(uint8_t * uri_name, uint8_t * buf, uint32_t * file_len);
+uint8_t http_post_cgi_handler(uint8_t * uri_name, st_http_request * p_http_request, uint8_t * buf, uint32_t * file_len);
+
+uint8_t predefined_get_cgi_processor(uint8_t * uri_name, uint8_t * buf, uint16_t * len);
+uint8_t predefined_set_cgi_processor(uint8_t * uri_name, uint8_t * uri, uint8_t * buf, uint16_t * len);
+
+#endif
diff --git a/WIZ550S2E_App/src/PlatformHandler/timerHandler.c b/WIZ550S2E_App/src/PlatformHandler/timerHandler.c
index ddf111d..a878b0f 100644
--- a/WIZ550S2E_App/src/PlatformHandler/timerHandler.c
+++ b/WIZ550S2E_App/src/PlatformHandler/timerHandler.c
@@ -7,9 +7,9 @@
#include "DHCP/dhcp.h"
#include "DNS/dns.h"
-uint8_t nagle_flag = 0;
-uint32_t nagle_time = 0;
-uint32_t uart_recv_count = 0;
+volatile uint8_t nagle_flag = 0;
+volatile uint32_t nagle_time = 0;
+volatile uint32_t uart_recv_count = 0;
uint8_t reconn_flag = 0; /* 0 : connect / 1 : NONE */
uint32_t reconn_time = 0;
diff --git a/WIZ550S2E_App/src/PlatformHandler/timerHandler.h b/WIZ550S2E_App/src/PlatformHandler/timerHandler.h
index 2cc3fc2..4f46682 100644
--- a/WIZ550S2E_App/src/PlatformHandler/timerHandler.h
+++ b/WIZ550S2E_App/src/PlatformHandler/timerHandler.h
@@ -4,9 +4,9 @@
#define TICKRATE_HZ1 (1000) /* 1000 ticks per second */
-extern uint8_t nagle_flag;
-extern uint32_t nagle_time;
-extern uint32_t uart_recv_count;
+extern volatile uint8_t nagle_flag;
+extern volatile uint32_t nagle_time;
+extern volatile uint32_t uart_recv_count;
extern uint8_t reconn_flag;
extern uint32_t reconn_time;
diff --git a/WIZ550S2E_App/src/S2E/S2E.c b/WIZ550S2E_App/src/S2E/S2E.c
index 3cf9635..f98d922 100644
--- a/WIZ550S2E_App/src/S2E/S2E.c
+++ b/WIZ550S2E_App/src/S2E/S2E.c
@@ -1,4 +1,3 @@
-
#include
#include "common.h"
#include "socket.h"
@@ -19,6 +18,10 @@ static int pattern_cnt = 0;
static int ready_cnt = 0;
static int pattern_offset = 0;
+#ifdef RENEWAL_UDP_PORT
+ static uint16_t udp_port = 5000;
+#endif
+
uint32_t uart_send_cnt = 0;
uint32_t uart_recv_cnt = 0;
uint32_t ether_send_cnt = 0;
@@ -117,6 +120,12 @@ static void ether_to_uart(uint8_t sock)
if((len > 0) && len <= RingBuffer_GetFree(&txring)) {
len = recvfrom(sock, g_recv_buf, sizeof(g_recv_buf), dstip, &dstport);
+#ifdef RENEWAL_UDP_PORT
+ struct __network_info *net = (struct __network_info *)get_S2E_Packet_pointer()->network_info;
+ udp_port = dstport;
+ net->remote_port = udp_port;
+// printf(" peer port : %d \r\n", udp_port); //for debug
+#endif
if(len < 0) {
//printf("recvfrom error\r\n");
return;
@@ -225,16 +234,19 @@ static void uart_to_ether(uint8_t sock)
uart_recv_cnt += len;
pattern_offset = 0;
- if(sock_state == SOCK_UDP) {
+ if(sock_state == SOCK_UDP)
+ {
uint8_t remote_ip[4];
memcpy(remote_ip, net->remote_ip, sizeof(remote_ip));
ret = sendto(sock, g_send_buf, len, remote_ip, net->remote_port);
- if(ret != len) {
- //printf("sendto error\r\n");
- return;
- }
+// if(ret != len) {
+// //printf("sendto error - ret : %d // len : %d\r\n", ret, len); //for debugging
+// return;
+// }
ether_send_cnt += len;
- } else if(sock_state == SOCK_ESTABLISHED) {
+ }
+ else if(sock_state == SOCK_ESTABLISHED)
+ {
ret = send(sock, g_send_buf, len);
if(ret != len) {
//printf("send error\r\n");
@@ -242,7 +254,6 @@ static void uart_to_ether(uint8_t sock)
}
ether_send_cnt += len;
}
-
nagle_flag = nagle_time = uart_recv_count = 0;
}
@@ -260,7 +271,7 @@ static void trigger_none_process(uint8_t sock_state)
return;
}
- if(uart_size_prev == RingBuffer_GetCount(&rxring)) { // UART ?신 ?이?? ?으?
+ if(uart_size_prev == RingBuffer_GetCount(&rxring)) { // UART ?�신 ?�이?��? ?�으�?
if(trigger_flag == 0)
trigger_flag = 1;
} else {
@@ -581,7 +592,7 @@ static void s2e_sockudp_process(uint8_t sock)
break;
case UDP_MODE:
- /* S2E ?작 */
+ /* S2E ?�작 */
ether_to_uart(sock);
uart_to_ether(sock);
break;
diff --git a/WIZ550S2E_App/src/common.h b/WIZ550S2E_App/src/common.h
index 6ad7639..87c5fa6 100644
--- a/WIZ550S2E_App/src/common.h
+++ b/WIZ550S2E_App/src/common.h
@@ -3,10 +3,13 @@
#define __COMMON_H__
#include
+#include "board.h"
+
+#define RENEWAL_UDP_PORT // add by kei
#define MAJOR_VER 1
-#define MINOR_VER 0
-#define MAINTENANCE_VER 3
+#define MINOR_VER 1
+#define MAINTENANCE_VER 0
#define SOCK_DATA 0
#define SOCK_CONFIG 1
diff --git a/WIZ550S2E_Boot/.cproject b/WIZ550S2E_Boot/.cproject
index fe145c1..d177035 100644
--- a/WIZ550S2E_Boot/.cproject
+++ b/WIZ550S2E_Boot/.cproject
@@ -117,7 +117,7 @@
-
+
diff --git a/WIZ550S2E_Boot/.settings/language.settings.xml b/WIZ550S2E_Boot/.settings/language.settings.xml
deleted file mode 100644
index 84d86b6..0000000
--- a/WIZ550S2E_Boot/.settings/language.settings.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/WIZ550S2E_Boot/Release/makefile b/WIZ550S2E_Boot/Release/makefile
new file mode 100644
index 0000000..7102de5
--- /dev/null
+++ b/WIZ550S2E_Boot/Release/makefile
@@ -0,0 +1,56 @@
+################################################################################
+# Automatically-generated file. Do not edit!
+################################################################################
+
+-include ../makefile.init
+
+RM := rm -rf
+
+# All of the sources participating in the build are defined here
+-include sources.mk
+-include src/netutil/subdir.mk
+-include src/PlatformHandler/subdir.mk
+-include src/Internet/TFTP/subdir.mk
+-include src/Ethernet/W5500/subdir.mk
+-include src/Ethernet/subdir.mk
+-include src/Configuration/subdir.mk
+-include src/subdir.mk
+-include subdir.mk
+-include objects.mk
+
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(strip $(C_DEPS)),)
+-include $(C_DEPS)
+endif
+endif
+
+-include ../makefile.defs
+
+# Add inputs and outputs from these tool invocations to the build variables
+
+# All Target
+all: WIZ550S2E_Boot.axf
+
+# Tool invocations
+WIZ550S2E_Boot.axf: $(OBJS) $(USER_OBJS)
+ @echo 'Building target: $@'
+ @echo 'Invoking: MCU Linker'
+ arm-none-eabi-gcc -nostdlib -L"D:\__Workspace\___Source\WIZnet\WIZ550S2E\wiznet_s2e_wiz550s2e_board\Release" -L"D:\__Workspace\___Source\WIZnet\WIZ550S2E\lpc_chip_11exx\Release" -Xlinker -Map="WIZ550S2E_Boot.map" -Xlinker --gc-sections -Xlinker --allow-multiple-definition -mcpu=cortex-m0 -mthumb -T "Bootloader.ld" -L ../linkscripts -o "WIZ550S2E_Boot.axf" $(OBJS) $(USER_OBJS) $(LIBS)
+ @echo 'Finished building target: $@'
+ @echo ' '
+ $(MAKE) --no-print-directory post-build
+
+# Other Targets
+clean:
+ -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) WIZ550S2E_Boot.axf
+ -@echo ' '
+
+post-build:
+ -@echo 'Performing post-build steps'
+ -arm-none-eabi-size "WIZ550S2E_Boot.axf"; arm-none-eabi-objcopy -O ihex "WIZ550S2E_Boot.axf" "WIZ550S2E_Boot.hex"; # arm-none-eabi-objcopy -v -O binary "WIZ550S2E_Boot.axf" "WIZ550S2E_Boot.bin" ; # checksum -p LPC11E36_501 -d "WIZ550S2E_Boot.bin";
+ -@echo ' '
+
+.PHONY: all clean dependents
+.SECONDARY: post-build
+
+-include ../makefile.targets
diff --git a/lpc_chip_11exx/.cproject b/lpc_chip_11exx/.cproject
index 28f7857..6ab5e5f 100644
--- a/lpc_chip_11exx/.cproject
+++ b/lpc_chip_11exx/.cproject
@@ -25,7 +25,7 @@
-
+
diff --git a/lpc_chip_11exx/Release/makefile b/lpc_chip_11exx/Release/makefile
new file mode 100644
index 0000000..ac4ffa2
--- /dev/null
+++ b/lpc_chip_11exx/Release/makefile
@@ -0,0 +1,50 @@
+################################################################################
+# Automatically-generated file. Do not edit!
+################################################################################
+
+-include ../makefile.init
+
+RM := rm -rf
+
+# All of the sources participating in the build are defined here
+-include sources.mk
+-include src/subdir.mk
+-include subdir.mk
+-include objects.mk
+
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(strip $(C_DEPS)),)
+-include $(C_DEPS)
+endif
+endif
+
+-include ../makefile.defs
+
+# Add inputs and outputs from these tool invocations to the build variables
+
+# All Target
+all: liblpc_chip_11exx.a
+
+# Tool invocations
+liblpc_chip_11exx.a: $(OBJS) $(USER_OBJS)
+ @echo 'Building target: $@'
+ @echo 'Invoking: MCU Archiver'
+ arm-none-eabi-ar -r "liblpc_chip_11exx.a" $(OBJS) $(USER_OBJS) $(LIBS)
+ @echo 'Finished building target: $@'
+ @echo ' '
+ $(MAKE) --no-print-directory post-build
+
+# Other Targets
+clean:
+ -$(RM) $(OBJS)$(C_DEPS)$(ARCHIVES) liblpc_chip_11exx.a
+ -@echo ' '
+
+post-build:
+ -@echo 'Performing post-build steps'
+ -arm-none-eabi-size "liblpc_chip_11exx.a" ; # arm-none-eabi-objdump -h -S "liblpc_chip_11exx.a" >"liblpc_chip_11exx.lss"
+ -@echo ' '
+
+.PHONY: all clean dependents
+.SECONDARY: post-build
+
+-include ../makefile.targets
diff --git a/wiznet_s2e_wiz550s2e_board/.cproject b/wiznet_s2e_wiz550s2e_board/.cproject
index 6448069..7576dd5 100644
--- a/wiznet_s2e_wiz550s2e_board/.cproject
+++ b/wiznet_s2e_wiz550s2e_board/.cproject
@@ -25,7 +25,7 @@
-
+
diff --git a/wiznet_s2e_wiz550s2e_board/Release/makefile b/wiznet_s2e_wiz550s2e_board/Release/makefile
new file mode 100644
index 0000000..f45c52e
--- /dev/null
+++ b/wiznet_s2e_wiz550s2e_board/Release/makefile
@@ -0,0 +1,50 @@
+################################################################################
+# Automatically-generated file. Do not edit!
+################################################################################
+
+-include ../makefile.init
+
+RM := rm -rf
+
+# All of the sources participating in the build are defined here
+-include sources.mk
+-include src/subdir.mk
+-include subdir.mk
+-include objects.mk
+
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(strip $(C_DEPS)),)
+-include $(C_DEPS)
+endif
+endif
+
+-include ../makefile.defs
+
+# Add inputs and outputs from these tool invocations to the build variables
+
+# All Target
+all: libwiznet_s2e_wiz550s2e_board.a
+
+# Tool invocations
+libwiznet_s2e_wiz550s2e_board.a: $(OBJS) $(USER_OBJS)
+ @echo 'Building target: $@'
+ @echo 'Invoking: MCU Archiver'
+ arm-none-eabi-ar -r "libwiznet_s2e_wiz550s2e_board.a" $(OBJS) $(USER_OBJS) $(LIBS)
+ @echo 'Finished building target: $@'
+ @echo ' '
+ $(MAKE) --no-print-directory post-build
+
+# Other Targets
+clean:
+ -$(RM) $(OBJS)$(C_DEPS)$(ARCHIVES) libwiznet_s2e_wiz550s2e_board.a
+ -@echo ' '
+
+post-build:
+ -@echo 'Performing post-build steps'
+ -arm-none-eabi-size "libwiznet_s2e_wiz550s2e_board.a" ; # arm-none-eabi-objdump -h -S "libwiznet_s2e_wiz550s2e_board.a" >"libwiznet_s2e_wiz550s2e_board.lss"
+ -@echo ' '
+
+.PHONY: all clean dependents
+.SECONDARY: post-build
+
+-include ../makefile.targets