

#include-once
#include <Array.au3>

;--Global Constants ------------------------------------------------------------


Global Const $TcpNoSocket = -1
Global Const $TcpDefConnections = -1


;Return Error Constants
Global Const $Tcp_WrongIpAdr = 1 ; Wrong Ip Address
Global Const $Tcp_WrongPort = 2 ; Wrong Prot
Global Const $Tcp_WrongState = 3 ; Wrong State (Modul intern)
Global Const $Tcp_MaxConReached = 4 ; Max. number of connection reached (Modul intern)
Global Const $Tcp_ConDisabled = 5 ; Tcp connection Disabled
Global Const $Tcp_Connected = 6 ; Tcp already connected
Global Const $Tcp_ServerDisabled = 7 ; Tcp Server disabled
Global Const $Tcp_NoData = 8 ;  Tcp No Data Received

;Failure Flags form Network Card (See http://msdn.microsoft.com/en-us/library/ms740668.aspx)
Global Const $Tcp_AdrAllReadyUse = 10048 ; Adress already in use
Global Const $Tcp_NetWorkDown = 10050 ; Network is down
Global Const $Tcp_NetWorkUnReachable = 10051 ; Host currently not reachable
Global Const $Tcp_ConnectionRefused = 10061 ; Connection refused by target computer


;Enum for Tcp States
Global Enum $Tcp_NoAction = 0, _
			$Tcp_StartUpOk = 1, _
			$Tcp_ServerActive = 2, _
			$Tcp_ClientActive = 3, _
			$Tcp_Error = 4


;Enum for Tcp Connection Status
Global Enum $Tcp_NoConnection = -1, _
			$Tcp_IsListen = 1, _
			$Tcp_IsConnected = 2


;Enum to define Paramter for the TcpServerSocketList
Global Enum $Tcp_Socket = 0, _
			$Tcp_SocketIp, _
			$NumOfSockLstData


;Enum for the definition of the Tcp_Timer
Global Enum $Tcp_TimerStatus = 0, _
			$Tcp_TimerStart, _
			$Tcp_TimerThreshold, _
			$Tcp_TimerCounter, _
			$Tcp_NumOfTimerParam


Global Enum $Tcp_TransmitParam = 0, _
			$Tcp_ReceiveParam, _
			$Tcp_NumOfUsrDatParam

;--Global Parameter (Internal Use)------------------------------------------------

;Prameter which includes the current state of the Tcp Connection
Global $TcpState = $Tcp_NoAction

;Pramter which shows the current connection status
Global $TcpConnectStatus

;Value which shows the MainSocket of the Tcp Connection
;When used as client - MainSocket used as connection to Server
;          as server - MainSocket used as indicator that Server is active
Global $TcpMainSocket

;Server socket list, includes all active connections between server and clients
Global $TcpServerSocketList[1][$NumOfSockLstData]

;Parameter to define the maximum allowed connections
Global $TcpMaxConnections

;Parameter array where cyclic transmit/receive data can be set.
Global $TcpUserDataParams[1][$Tcp_NumOfUsrDatParam]

;Sign/String which will be cyclic send to check wheter the Client/Server are connected
Global $TcpConnectCheckSign
Global $TcpConnectCheckTimer

;--Start Script ----------------------------------------------------------------

;==Skript=Starts=Here========
;init()
;============================
;main()
;============================
;shdown()
;==Skript=Ends=Here==========


;-- Main Function Definitions --------------------------------------------------


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_Init
; Description ...: Init function of the Tcp.au3
; Syntax ........: Tcp_Init([$timeOut = False[, $tTime = 100]])
; Parameters ....: $timeOut             - [optional] Boolean value Enable/Disable Connection timeout. Default is False.
;                  $tTime               - [optional] Integer value to define the timeout time. Default is 100.
; Return values .: None
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_Init($timeOut = False, $tTime = 100)
	Local $tcpStUp = $Tcp_NoAction
	Local $ret
	Local $error

	$tcpStUp = $Tcp_Error
	If $timeOut = True And $tTime <> 0 Then Opt("TCPTimeout", $tTime)

	$ret = TCPStartup()
	$error = @error
	If $ret = 1 Then $tcpStUp = $Tcp_StartUpOk


	Tcp_InitSocketList()
	Tcp_InitUserDataParams()
	Tcp_SetMaxConnections($TcpDefConnections)
	Tcp_SetMainSocket($TcpNoSocket)
	Tcp_SetConnectStatus($Tcp_NoConnection)
	Tcp_SetState($tcpStUp)
	Tcp_SetTcpCheckConnectSign(0xAAAA)
	$TcpConnectCheckTimer = Tcp_InitTimer(1000)
	Tcp_StartTimer($TcpConnectCheckTimer)

	If $ret = 0 Then Return SetError($error,0,-1)

	Return SetError(0,0,1)
EndFunc   ;==>TCP_Init


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_Main
; Description ...: Main function of the Tcp.au3. This function should be normally used in polling mode (while(1)-loop)
; Syntax ........: Tcp_Main()
; Parameters ....:
; Return values .: 1x2-D Array, which indiactes the connected and disconected sockets, [0][0] = Connected Socket
;																					   [0][1] = Disconnected Socket
;				   Param [0][0] = -1 							- Nothing to do value can be ignored
;				   Param [0][1] = -1 							- Nothing to do value can be ignored
;
;				   Param [0][0] > 0 							- Courrent connected socket
;				   Param [0][1] > 0 							- Courrent disconnected socket
; Author ........: Seidc
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_Main()
	Local $avRet[1][2] = [[-1,-1]]
	If Tcp_GetState() = $Tcp_ServerActive Then
		$avRet[0][0] = Tcp_AcceptIncommingConnection()
		$avRet[0][1] = Tcp_CheckSocketListConnections($Tcp_ServerActive)
	ElseIf Tcp_GetState() = $Tcp_ClientActive Then
		Tcp_CheckSocketListConnections($Tcp_ClientActive)
	Else

	EndIf
	Return SetError(0,0,$avRet)
EndFunc   ;==>TCP_Main



; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_Shutdown
; Description ...: Shutdown function of the Tcp.au3. If Tcp.au3 is used as Server, the shutdown disconnect all available connection
;				   and disables the Tcp modul.
;			       If it used as Client, the shutdown disconnects from server and then the Tcp modul.
; Syntax ........: Tcp_Shutdown()
; Parameters ....: None
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_Shutdown()
	If Tcp_IsConnected() Then Tcp_DisconnectFromServer()
	If Tcp_IsListen() Then Tcp_CloseServer()
	TCPShutdown()
EndFunc   ;==>Tcp_Shutdown

;-- Other Function Definitions -------------------------------------------------
; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_StartServer
; Description ...: Function to start a Tcp Server
; Syntax ........: Tcp_StartServer($port[, $ipAsString = @IPAddress1[, $maxConnections = -1]])
; Parameters ....: $port                - Port of the Server
;                  $ipAsString          - [optional] Ip of the Server which should be listen. Default is @IPAddress1.
;                  $maxConnections      - [optional] Number of max allowed connections. Default is -1 which means each connection allowed
; Return values .:  1 - Server start was successful
;				   -1 - Server start failed.
;						See @error for more details.
;						Possible @error values are shown at Return Error Constants
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_StartServer($port, $ipAsString = @IPAddress1, $maxConnections = -1)
	Local $ret = -1
	Local $error
	Local $mainSocket
	Local $cIp = TCPNameToIP($ipAsString)
	If Tcp_GetConnectStatus() = $Tcp_IsConnected Then Return SetError($Tcp_Connected, 0, -1)
	If Tcp_GetConnectStatus() = $Tcp_IsListen Then Return SetError($Tcp_WrongState, 0, -1)

	If $maxConnections = -1 Then
		$mainSocket = TCPListen($cIp, $port)
		$error = @error
		Tcp_SetMainSocket($mainSocket)
		$ret = 1
	Else
		$mainSocket = TCPListen($cIp, $port, $maxConnections)
		$error = @error
		Tcp_SetMainSocket($mainSocket)
		Tcp_SetMaxConnections($maxConnections)
		$ret = 1
	EndIf

	If $mainSocket > 0 Then
		Tcp_SetConnectStatus($Tcp_IsListen)
		Tcp_SetState($Tcp_ServerActive)
	EndIf

	If $error > 0 Then $ret = -1

	Return SetError($error, 0, $ret)
EndFunc   ;==>Tcp_StartServer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_CloseServer
; Description ...: Function to close (ShutDown) a Tcp Server
; Syntax ........: Tcp_CloseServer()
; Parameters ....: None
; Return values .:   1 - Tcp Server was successfully closed
;				    -1 - Close of a Tcp Server failed
;						See @error for more details.
;						Possible @error values are shown at Return Error Constants.
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_CloseServer()
	Local $ret = -1
	Local $error

	If Tcp_GetConnectStatus() <> $Tcp_IsListen Then Return SetError($Tcp_ServerDisabled, 0 - 1)

	Tcp_DisonnectAllSockets()
	$ret = Tcp_StopServer()
	$error = @error
	If $ret = True Then
		$ret = 1
	Else
		$ret = -1
	EndIf
	Return SetError($error, 0, $ret)
EndFunc   ;==>Tcp_CloseServer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_ConnectToServer
; Description ...:
; Syntax ........: Tcp_ConnectToServer($ipAsString, $port)
; Parameters ....: $ipAsString          - Ip v4 Adress to connect to server.
;                  $port                - Port of the Server.
; Return values .:   1 - Modul connected successfully to Server
;                   -1 - A connection error happen.
;						See @error for more details.
;						Possible @error values are shown at Return Error Constants
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_ConnectToServer($ipAsString, $port)
	Local $ret
	Local $error
	Local $mainSocket
	Local $cIp = TCPNameToIP($ipAsString)

	If Tcp_GetConnectStatus() = $Tcp_IsListen Then Return SetError($Tcp_WrongState, 0, -1)
	If Tcp_GetConnectStatus() = $Tcp_IsConnected Then Return SetError($Tcp_Connected, 0, -1)

	$mainSocket = TCPConnect($cIp, $port)
	If @error Then Return SetError(@error, 0, -1)

	Tcp_SetMainSocket($mainSocket)
	Tcp_SetConnectStatus($Tcp_IsConnected)
	Tcp_SetState($Tcp_ClientActive)
	Return SetError(0, 0, 1)
EndFunc   ;==>Tcp_ConnectToServer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_DisconnectFromServer
; Description ...: Function to disconnect from Server
; Syntax ........: Tcp_DisconnectFromServer()
; Parameters ....:  1 - Disconnection was succesfull
;				   -1 - Disconnection failed.
;						See @error for more details.
;						Possible @error values are shown at Return Error Constants
; Return values .: None
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_DisconnectFromServer()
	Local $ret
	Local $error

	If Tcp_GetConnectStatus() <> $Tcp_IsConnected Then Return SetError($Tcp_ConDisabled, 0, -1)
	$ret = TCPCloseSocket(Tcp_GetMainSocket())
	$error = @error
	If $ret = True Then
		Tcp_SetMainSocket($TcpNoSocket)
		Tcp_SetConnectStatus($Tcp_NoConnection)
		Tcp_SetState($Tcp_StartUpOk)
		$ret = 1
	Else
		$ret = -1
	EndIf

	Return SetError($error, 0, $ret)
EndFunc   ;==>Tcp_DisconnectFromServer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetState
; Description ...: Getter function to get the current TCP state
; Syntax ........: Tcp_GetState()
; Parameters ....:
; Return values .: None
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetState()
	Return $TcpState
EndFunc   ;==>Tcp_GetState


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetConnectStatus
; Description ...:
; Syntax ........: Tcp_GetConnectStatus()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetConnectStatus()
	Return $TcpConnectStatus
EndFunc   ;==>Tcp_GetConnectStatus


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetMainSocket
; Description ...:
; Syntax ........: Tcp_GetMainSocket()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetMainSocket()
	Return $TcpMainSocket
EndFunc   ;==>Tcp_GetMainSocket


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_SetMaxConnections
; Description ...: Set the max. allowed number of connections
; Syntax ........: Tcp_SetMaxConnections($num)
; Parameters ....: $num                 - Max number of connection which will be allowed
; Return values .: None
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetMaxConnections($num)
	$TcpMaxConnections = $num
EndFunc   ;==>Tcp_SetMaxConnections


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetMaxConnections
; Description ...: Retruns the max. allowed number of connections
; Syntax ........: Tcp_GetMaxConnections()
; Parameters ....: None
; Return values .: -1 = $TcpDefConnections 					- No max number of connection defined. Each avalialble connection will be allowed.
;				   >0 										- The max. allowed number of connections
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetMaxConnections()
	Return $TcpMaxConnections
EndFunc   ;==>Tcp_GetMaxConnections


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetSocketListData
; Description ...:
; Syntax ........: Tcp_GetSocketListData($socket)
; Parameters ....: $socket              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetSocketListData($socket)
	Local $avRet[$NumOfSockLstData]
	For $i = 0 To UBound($TcpServerSocketList) - 1
		If($TcpServerSocketList[$i][$Tcp_Socket] = $socket) Then
			For $j = 0 To $NumOfSockLstData - 1
				$avRet[$j] = $TcpServerSocketList[$i][$j]
			Next
		EndIf
	Next
	Return $avRet
EndFunc   ;==>Tcp_GetSocketListData


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_InitTimer
; Description ...:
; Syntax ........: Tcp_InitTimer($threshold)
; Parameters ....: $threshold           - A dll struct value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_InitTimer($threshold)
	Local $timer[$Tcp_NumOfTimerParam]
	$timer[$Tcp_TimerStart] = False
	$timer[$Tcp_TimerThreshold] = $threshold
	$timer[$Tcp_TimerStatus] = 0
	$timer[$Tcp_TimerCounter] = 0
	Return $timer
EndFunc   ;==>Tcp_InitTimer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_StartTimer
; Description ...:
; Syntax ........: Tcp_StartTimer(Byref $timer)
; Parameters ....: $timer               - [in/out] A dll struct value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_StartTimer(ByRef $timer)
	$timer[$Tcp_TimerStart] = True
	$timer[$Tcp_TimerCounter] = TimerInit()
	$timer[$Tcp_TimerStatus] = 0
EndFunc   ;==>Tcp_StartTimer


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetTimerStatus
; Description ...:
; Syntax ........: Tcp_GetTimerStatus(Byref $timer)
; Parameters ....: $timer               - [in/out] A dll struct value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetTimerStatus(ByRef $timer)

	If $timer[$Tcp_TimerStart] = False Then Return SetError(1, 0, 1)

	Local $thrs = $timer[$Tcp_TimerThreshold]
	If TimerDiff($timer[$Tcp_TimerCounter]) > $thrs Then
		$timer[$Tcp_TimerStatus] = 1
		Return SetError(0, 0, 1)
	Else
		$timer[$Tcp_TimerStatus] = 0
		Return SetError(0, 0, 0)
	EndIf
EndFunc   ;==>Tcp_GetTimerStatus


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_ReloadTimer
; Description ...:
; Syntax ........: Tcp_ReloadTimer(Byref $timer)
; Parameters ....: $timer               - [in/out] A dll struct value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_ReloadTimer(ByRef $timer)
	$timer[$Tcp_TimerCounter] = TimerInit()
	$timer[$Tcp_TimerStatus] = 0
EndFunc


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_StopTimer
; Description ...:
; Syntax ........: Tcp_StopTimer(Byref $timer)
; Parameters ....: $timer               - [in/out] A dll struct value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_StopTimer(ByRef $timer)
	$timer[$Tcp_TimerStart] = False
EndFunc


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetSocketListIndex
; Description ...:
; Syntax ........: Tcp_GetSocketListIndex($socket)
; Parameters ....: $socket              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetSocketListIndex($socket)
	For $i = 1 To UBound($TcpServerSocketList,1) - 1
		If $TcpServerSocketList[$i][$Tcp_Socket] = $socket Then Return SetError(0, 0, $i)
	Next
	Return SetError(0, 0, -1)
EndFunc   ;==>Tcp_GetSocketListIndex

; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_SocketToIP
; Description ...:
; Syntax ........: Tcp_SocketToIP($socket)
; Parameters ....: $socket              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SocketToIP($socket)
	Local $sockaddr, $aRet

	$sockaddr = DllStructCreate("short;ushort;uint;char[8]")

	$aRet = DllCall("Ws2_32.dll", "int", "getpeername", "int", $socket, _
			"ptr", DllStructGetPtr($sockaddr), "int*", DllStructGetSize($sockaddr))
	If Not @error And $aRet[0] = 0 Then
		$aRet = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($sockaddr, 3))
		If Not @error Then $aRet = $aRet[0]
	Else
		$aRet = 0
	EndIf

	$sockaddr = 0

	Return $aRet
EndFunc   ;==>Tcp_SocketToIP


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_IsConnected
; Description ...:
; Syntax ........: Tcp_IsConnected()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_IsConnected()
	If Tcp_GetMainSocket() <> -1 And Tcp_GetState() = $Tcp_ClientActive Then Return SetError(0, 0, 1)
	Return SetError(0, 0, -1)
EndFunc   ;==>Tcp_IsConnected


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_IsListen
; Description ...:
; Syntax ........: Tcp_IsListen()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_IsListen()
	If Tcp_GetMainSocket() <> -1 And Tcp_GetState() = $Tcp_ServerActive Then Return SetError(0, 0, 1)
	Return SetError(0, 0, -1)
EndFunc   ;==>Tcp_IsListen


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_SwitchErrorFlagToString
; Description ...:
; Syntax ........: Tcp_SwitchErrorFlagToString($errorFlag)
; Parameters ....: $errorFlag           - An unknown value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SwitchErrorFlagToString($errorFlag)
	Local $retStr
	Switch($errorFlag)
		Case $Tcp_WrongIpAdr
			$retStr = $errorFlag & ": Ip Invalid"
		Case $Tcp_WrongPort
			$retStr = $errorFlag & ": Port Invalid"
		Case $Tcp_WrongState
			$retStr = $errorFlag & ": Tcp Connection in wrong State"
		Case $Tcp_MaxConReached
			$retStr = $errorFlag & ": Max. number of connections reached"
		Case $Tcp_ConDisabled
			$retStr = $errorFlag & ": Disconnected"
		Case $Tcp_Connected
			$retStr = $errorFlag & ": Connected"
		Case $Tcp_ServerDisabled
			$retStr = $errorFlag & ": Server disabled"
		Case $Tcp_AdrAllReadyUse
			$retStr = $errorFlag & ": Address/Port allready in use"
		Case $Tcp_NetWorkDown
			$retStr = $errorFlag & ": Network is down"
		Case $Tcp_NetWorkUnReachable
			$retStr = $errorFlag & ": Host is unreachable"
		Case $Tcp_ConnectionRefused
			$retStr = $errorFlag & ": Connection refused by target computer"
		Case Else
			$retStr = "Unkown Error: " & $errorFlag
	EndSwitch
	Return $retStr
EndFunc   ;==>Tcp_SwitchErrorFlagToString


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_SetTcpCheckConnectSign
; Description ...:
; Syntax ........: Tcp_SetTcpCheckConnectSign($signOrString)
; Parameters ....: $signOrString        - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetTcpCheckConnectSign($signOrString)
	$TcpConnectCheckSign = $signOrString
EndFunc   ;==>Tcp_SetTcpCheckConnectSign


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetTcpCheckConnectSign
; Description ...:
; Syntax ........: Tcp_GetTcpCheckConnectSign()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetTcpCheckConnectSign()
	Return $TcpConnectCheckSign
EndFunc   ;==>Tcp_GetTcpCheckConnectSign


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_Receive
; Description ...:
; Syntax ........: Tcp_Receive($socket[, $maxLen = 2048[, $recType = 0]])
; Parameters ....: $socket              - A string value.
;                  $maxLen              - [optional] An unknown value. Default is 2048.
;                  $recType             - [optional] An unknown value. Default is 0.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_Receive($socket,$maxLen = 2048,$recType = 0)
	Local $ret = TCPRecv($socket,$maxLen,$recType)
	Local $error = @error

		If $ret = "" And @error > 0 Then Return SetError ($error, 0 , -1)
		If $ret = Tcp_GetTcpCheckConnectSign() Then Return SetError($Tcp_NoData,0,-1)
	Return SetError(0,0,$ret)
EndFunc   ;==>Tcp_Receive


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_Send
; Description ...:
; Syntax ........: Tcp_Send($socket, $data)
; Parameters ....: $socket              - A string value.
;                  $data                - An unknown value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_Send($socket, $data)
	Tcp_StopTimer($TcpConnectCheckTimer)
	Local $ret = TCPSend($socket,$data)
	Local $error = @error
	Tcp_StartTimer($TcpConnectCheckTimer)
	Return SetError($error,0,$ret)
EndFunc   ;==>Tcp_Send


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetNumberOfConnectedSockets
; Description ...:
; Syntax ........: Tcp_GetNumberOfConnectedSockets()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetNumberOfConnectedSockets()
	Return UBound($TcpServerSocketList,1) - 1
EndFunc


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_GetSocketByIndex
; Description ...:
; Syntax ........: Tcp_GetSocketByIndex($index)
; Parameters ....: $index               - An integer value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_GetSocketByIndex($index)
	If $index < 0 Or $index >= UBound($TcpServerSocketList) Then Return SetError(1,0,-1)
		If UBound($TcpServerSocketList) = 1 Then Return SetError(2,0,-1)
	Return SetError(0,0,$TcpServerSocketList[$index][$Tcp_Socket])
EndFunc


;--- #INTERNAL_USE_ONLY# --------------------------------------------------------------------------------------------------------

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: Tcp_SetState
; Description ...: Setter function, to set the current state of the TCP connection
; Syntax ........: Tcp_SetState($state)
; Parameters ....: $state               - Current state of the TCP connection.
; Return values .: None
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetState($state)
	$TcpState = $state
EndFunc   ;==>Tcp_SetState

; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_SetConnectStatus
; Description ...:
; Syntax ........: Tcp_SetConnectStatus($status)
; Parameters ....: $status              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetConnectStatus($status)
	$TcpConnectStatus = $status
EndFunc   ;==>Tcp_SetConnectStatus


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_SetMainSocket
; Description ...:
; Syntax ........: Tcp_SetMainSocket($socket)
; Parameters ....: $socket              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetMainSocket($socket)
	$TcpMainSocket = $socket
EndFunc   ;==>Tcp_SetMainSocket


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_SetSocketToList
; Description ...: Adds a socket to the SocketList
; Syntax ........: Tcp_SetServerSocketToList($socket)
; Parameters ....: $socket              - Current Socket of an available connection.
; Return values .: -1 					- An error occurrs
;					1 					- Socket successfully add to list
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_SetSocketToList($socket)
	Local $ret = -1
	If Tcp_GetMaxConnections() = $TcpDefConnections Then
		Tcp_ArrayAdd2D($TcpServerSocketList, $Tcp_Socket, $socket)
		Local $iUbound = UBound($TcpServerSocketList, 1) - 1
		Local $iIpAdr = Tcp_SocketToIP($socket)
		Tcp_ArrayAdd2D($TcpServerSocketList, $Tcp_SocketIp, $iIpAdr, 1, $iUbound)
		$ret = 1
	Else
		If(UBound($TcpServerSocketList) - 1) < Tcp_GetMaxConnections() Then
			Tcp_ArrayAdd2D($TcpServerSocketList, $Tcp_Socket, $socket)
			Local $iUbound = UBound($TcpServerSocketList, 1) - 1
			Local $iIpAdr = Tcp_SocketToIP($socket)
			Tcp_ArrayAdd2D($TcpServerSocketList, $Tcp_SocketIp, $iIpAdr, 1, $iUbound)
			$ret = 1
		EndIf
	EndIf
	Return $ret
EndFunc   ;==>Tcp_SetSocketToList


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_AcceptIncommingConnection
; Description ...: Checks whether a new incomming connection is available and adds this to list
; Syntax ........: Tcp_AcceptIncommingConnection()
; Parameters ....: None
; Return values .: >0 											- current add socket
;				   -1 											- No Connection/ Error see @error for more information
; Author ........: SeidC
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_AcceptIncommingConnection()
	Local $ret
	Local $error
	Local $socket

	If Tcp_GetMainSocket() <> $TcpNoSocket Then
		$socket = TCPAccept(Tcp_GetMainSocket())
		$error = @error
		If $socket <> -1 And $error = 0 Then
			$ret = Tcp_CheckAndAddConnetion($socket)
			If $ret <> -1 Then $ret = $socket
			$error = @error
		Else
			$ret = - 1
		EndIf
	Else
		$ret = -1
		$error = $Tcp_ConDisabled
	EndIf
	Return SetError($error,0,$ret)
EndFunc   ;==>Tcp_AcceptIncommingConnection



; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_CheckAndAddConnetion
; Description ...:
; Syntax ........: Tcp_CheckAndAddConnetion($socket)
; Parameters ....: $socket              - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_CheckAndAddConnetion($socket)
	Local $ret = Tcp_SetSocketToList($socket)
	If $ret = -1 Then
		Return SetError($Tcp_MaxConReached,0,$ret)
	EndIf
	Return SetError(0,0,$ret)
EndFunc   ;==>Tcp_CheckAndAddConnetion


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_InitSocketList
; Description ...:
; Syntax ........: Tcp_InitSocketList()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_InitSocketList()
	$TcpServerSocketList[0][0] = "Socket"
	$TcpServerSocketList[0][1] = "IpAdress"
EndFunc   ;==>Tcp_InitSocketList



; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_ArrayAdd2D
; Description ...:
; Syntax ........: Tcp_ArrayAdd2D(Byref $refArray, $2dPos, $data[, $bNotExtend = -1[, $1dPos = -1]])
; Parameters ....: $refArray            - [in/out] An unknown value.
;                  $2dPos               - An unknown value.
;                  $data                - An unknown value.
;                  $bNotExtend          - [optional] A binary value. Default is -1.
;                  $1dPos               - [optional] An unknown value. Default is -1.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_ArrayAdd2D(ByRef $refArray, $2dPos, $data, $bNotExtend = -1, $1dPos = -1)
	If IsArray($refArray) = 0 Then Return SetError(1, 0, -1)
	If UBound($refArray, 1) = 0 Then Return SetError(2, 0, -1)
	If $2dPos > UBound($refArray, 1) - 1 Then Return SetError(3, 0, -1)
	If $bNotExtend = 1 And $1dPos = -1 Then Return SetError(4, 0, -1)

	Local $1dUbound = UBound($refArray, 1)
	Local $2dUbound = UBound($refArray, 2)

	If $bNotExtend = -1 Then
		ReDim $refArray[$1dUbound + 1][$2dUbound]
		$refArray[$1dUbound][$2dPos] = $data
		Return SetError(0, 0, 1)
	Else
		If $1dPos > UBound($refArray, 1) - 1 Then Return SetError(5, 0, -1)
		$refArray[$1dPos][$2dPos] = $data
	EndIf
	Return SetError(0, 0, 1)
EndFunc   ;==>Tcp_ArrayAdd2D


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_CheckSocketListConnections
; Description ...:
; Syntax ........: Tcp_CheckSocketListConnections($state)
; Parameters ....: $state               - A string value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_CheckSocketListConnections($state)
	Local $dellSock = -1
	If Tcp_GetTimerStatus($TcpConnectCheckTimer) = 1 Then
		If $state = $Tcp_ServerActive Then
			For $i = 1 To UBound($TcpServerSocketList, 1) - 1
				Local $tcpRet = TCPSend($TcpServerSocketList[$i][$Tcp_Socket], Tcp_GetTcpCheckConnectSign())
				Local $error = @error
				If $error Then
					$dellSock = $TcpServerSocketList[$i][$Tcp_Socket]
					_ArrayDelete($TcpServerSocketList, $i)
					ExitLoop
				EndIf
			Next
		ElseIf $state = $Tcp_ClientActive Then
			Local $tcpRet = TCPSend($TcpMainSocket, Tcp_GetTcpCheckConnectSign())
			Local $error = @error
			If $error Then
				Tcp_SetMainSocket($TcpNoSocket)
				Tcp_SetConnectStatus($Tcp_NoConnection)
				Tcp_SetState($Tcp_StartUpOk)
			EndIf
		EndIf
		Tcp_ReloadTimer($TcpConnectCheckTimer)
	EndIf
	Return SetError(0,0,$dellSock)
EndFunc   ;==>Tcp_CheckSocketListConnections



; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_DisonnectAllSockets
; Description ...:
; Syntax ........: Tcp_DisonnectAllSockets()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_DisonnectAllSockets()
	If UBound($TcpServerSocketList, 1) > 1 Then
		For $i = (UBound($TcpServerSocketList, 1) - 1) To 1 Step -1
			If $TcpServerSocketList[$i][$Tcp_Socket] <> -1 Then
				TCPCloseSocket($TcpServerSocketList[$i][$Tcp_Socket])
				_ArrayDelete($TcpServerSocketList, $i)
			EndIf
		Next
	EndIf
EndFunc   ;==>Tcp_DisonnectAllSockets


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_StopServer
; Description ...:
; Syntax ........: Tcp_StopServer()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_StopServer()
	Local $ret = TCPCloseSocket(Tcp_GetMainSocket())
	$error = @error
	If $ret = 1 Then
		Tcp_SetMainSocket($TcpNoSocket)
		Tcp_SetConnectStatus($Tcp_NoConnection)
		Tcp_SetState($Tcp_StartUpOk)
	EndIf
	Return SetError($error, 0, $ret)
EndFunc   ;==>Tcp_StopServer


; #INTERNAL_USE_ONLY# ====================================================================================================================
; Name ..........: Tcp_InitUserDataParams
; Description ...:
; Syntax ........: Tcp_InitUserDataParams()
; Parameters ....:
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_InitUserDataParams()
	$TcpUserDataParams[0][$Tcp_TransmitParam] = "Transmit Parameter"
	$TcpUserDataParams[0][$Tcp_ReceiveParam] = "Receive Parameter"

EndFunc   ;==>Tcp_InitUserDataParams


; #FUNCTION# ====================================================================================================================
; Name ..........: Tcp_AddUserDataParam
; Description ...:
; Syntax ........: Tcp_AddUserDataParam($tParam, $rParam)
; Parameters ....: $tParam              - A dll struct value.
;                  $rParam              - An unknown value.
; Return values .: None
; Author ........: Your Name
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func Tcp_AddUserDataParam($tParam, $rParam)
	Tcp_ArrayAdd2D($TcpUserDataParams, $Tcp_TransmitParam, $tParam)
	$iUbound = UBound($TcpUserDataParams, 1) - 1
	Tcp_ArrayAdd2D($TcpUserDataParams, $Tcp_ReceiveParam, $rParam, 1, $iUbound)
EndFunc   ;==>Tcp_AddUserDataParam