Jump to content

Send Keys with TCPRecv?


Recommended Posts

Ok, so what I'm trying to do is have a client app send a string of data to a sever, which this part works.

The string would look like "i12i31i231", etc etc

i is just to identify the next string of numbers.

To read the string it would be 1 for 2 seconds, 3 for 1 second, and 2 for 31 seconds. The first number is always the number I want to send. The numbers after the first, and up till the next "i" are always the time intervals I want to wait on the send keys.

So what I need is something to take out the i's, take the first number separate. Send that and then the enter key to the keyboard. Then pause the script for the identified time.

Is this possible?

Is their an example anywhere?

NOTE:

Of course the i's are arbitrary; however, I figured it would be useful in identifying the next key to send because the time could be any amount.

Yeah I'm not the greatest at DarkBasic either, but I'm good enough for a link :D A Thread of a W.I.P. that im making

Link to comment
Share on other sites

Oh, and my code :mellow: :

Client:

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GuiListView.au3>

Global $send = ""
Global $ConnectedSocket
GUInterface()

ProcessClose("RunLED.exe")

Func GUInterface()
    Local $msg
    Local $lightnum = 0
    Local $timing = 0
    Local $lighttext
    Local $firstcheck = 1
    
    GUICreate("Lights to Go -- PLC") ; will create a dialog box that when displayed is centered
    GUISetState(@SW_SHOW) ; will display an empty dialog box

;   Create Radio Buttons: G,Y,R,GY,GR,YR,GYR,Off
        $one = GUICtrlCreateRadio("Green", 20, 20)
        $two  = GUICtrlCreateRadio("Yellow", 20, 40)
        $four  = GUICtrlCreateRadio("Red", 20, 60)
        $three  = GUICtrlCreateRadio("Green and Yellow", 20, 80)
        $five  = GUICtrlCreateRadio("Green and Red", 20, 100)
        $six  = GUICtrlCreateRadio("Yellow and Red", 20, 120)
        $seven = GUICtrlCreateRadio("Green, Yellow, and Red", 20 , 140)
        $eight  = GUICtrlCreateRadio("Off", 20, 160)
;   Create Time Input w/ Label
        $time = GUICtrlCreateInput("", 20, 185, 30, 20)
        $timeLabel = GUICtrlCreateLabel("Time (in Seconds)", 55, 190)
;   Create Add to Sequence Button
        $add = GUICtrlCreateButton("  Add  ", 20, 215)
;   Create Loop Checkbox and Set default to selected
        $loop = GUICtrlCreateCheckbox("  Loop  ", 20, 245)
        GUICtrlSetState($loop,1)
;   Create List w/ arrows and clear
        $orderbox = GUICtrlCreateListView("  Color  | Time ", 250, 20, 100, 200)
        $Clear    = GUICtrlCreateButton("  Clear  ", 275, 220)
;   Create OK and Close Buttons.
        $sendtolight = GuiCtrlCreateButton("   Send To Traffic Light   ", 20, 350)
        $close = GUICtrlCreateButton("  Close  ", 285, 350)
;   Run the GUI until the dialog is closed
    Do
        $msg = GUIGetMsg()
;   Check for the send and close buttons
            if $msg = $close then 
                $send = "close"
                SendOutput()
                $msg = $GUI_EVENT_CLOSE
            EndIf
            if $msg = $sendtolight  then SendOutput()
;   Get Light Number and Light Text
        if $msg = $one then 
            $lightnum = "i1" 
            $lighttext = "Green"
        EndIf
        if $msg = $two then
            $lightnum = "i2"
            $lighttext = "Yellow"
        EndIf
        if $msg = $three then 
            $lightnum = "i3" 
            $lighttext = "G & Y"
        EndIf
        if $msg = $four then
            $lightnum = "i4" 
            $lighttext = "Red"
        EndIf   
        if $msg = $five then
            $lightnum = "i5"
            $lighttext = "G & R"
        EndIf
        if $msg = $six then
            $lightnum = "i6"
            $lighttext = "Y & R"
        EndIf
        if $msg = $seven then
            $lightnum = "i7"
            $lighttext = "G, Y, & R"
        EndIf
        if $msg = $eight then
            $lightnum = "i8"
            $lighttext = "Off"
        EndIf
;   Get Timer
        if GUICtrlRead($time) > 0  then 
            $timing = GUICtrlRead($time)
        else
            $timing = 0
        EndIf
;   Add Button Sequence
        if $msg = $add Then
            $nextitemID = GUICtrlCreateListViewItem(($lighttext & " | " & $timing), $orderbox)
                if $send = "17" and $lightnum <> 1 and $timing <> 7 then
                   $send = $lightnum & $timing
                ElseIf $send = "17" and $lightnum = 1 and $timing = 7 and $firstcheck = 1 then
                    $send = "17"
                    $firstcheck = 0
                Else
                   $send = $send & $lightnum & $timing
                EndIf
        EndIf
;   Clear Button Sequence
        if $msg = $clear Then _GUICtrlListView_DeleteItemsSelected($orderbox)
;   Set Loop Variable
    Until $msg = $GUI_EVENT_CLOSE
EndFunc   ;==>GUInterface

Func  SendOutput()

Opt('MustDeclareVars', 1)

    ; Set Some reusable info
    ;--------------------------
    
    Local $szData
    ; Set $szIPADDRESS to wherever the SERVER is. We will change a PC name into an IP Address
;   Local $szServerPC = @ComputerName
;   Local $szIPADDRESS = TCPNameToIP($szServerPC)
    Local $szIPADDRESS
    Local $nPORT
        
    if $ConnectedSocket <> -1 Then
        $szIPADDRESS = InputBox("Input IP Address", "Input the IP Address of host.")
        $nPort = InputBox("Input Port Number", "Input the Port Number of host.", 33891)
    EndIf
    ; Start The TCP Services
    ;==============================================
    TCPStartup()
    ; Initialize a variable to represent a connection
    ;==============================================
    $ConnectedSocket = -1

    ;Attempt to connect to SERVER at its IP and PORT 33891
    ;=======================================================
    $ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)

    ; If there is an error... show it
    If @error Then
        MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)
        ; If there is no error loop an inputbox for data
        ;   to send to the SERVER.
    Else
        ; We should have data in $send... lets attempt to send it through our connected socket.
            TCPSend($ConnectedSocket, $send)
            ; If the send failed with @error then the socket has disconnected
            ;----------------------------------------------------------------
    EndIf
        
    TCPCloseSocket($ConnectedSocket)    
    TCPShutdown()   
EndFunc

Host:

#include <GUIConstantsEx.au3>

Opt('MustDeclareVars', 1)

;==============================================
;==============================================
;SERVER!! Start Me First !!!!!!!!!!!!!!!
;==============================================
;==============================================

While 1
    Example()
WEnd

Func Example()
    ; Set Some reusable info
    ; Set your Public IP address (@IPAddress1) here.
;   Local $szServerPC = @ComputerName
;   Local $szIPADDRESS = TCPNameToIP($szServerPC)
    Local $szIPADDRESS = @IPAddress1
    Local $nPORT = 33891
    Global $MainSocket, $GOOEY, $edit, $ConnectedSocket, $szIP_Accepted
    Local $msg, $recv

    ; Start The TCP Services
    ;==============================================
    TCPStartup()

    ; Create a Listening "SOCKET".
    ;   Using your IP Address and Port 33891.
    ;==============================================
    $MainSocket = TCPListen($szIPADDRESS, $nPORT)

    ; If the Socket creation fails, exit.
    If $MainSocket = -1 Then Exit


    ; Create a GUI for messages
    ;==============================================
    $GOOEY = GUICreate("My Server (IP: " & $szIPADDRESS & ")", 300, 200)
    $edit = GUICtrlCreateEdit("", 10, 10, 280, 180)
    GUISetState()


    ; Initialize a variable to represent a connection
    ;==============================================
    $ConnectedSocket = -1


    ;Wait for and Accept a connection
    ;==============================================
    WaitForConnection()

    ; Get IP of client connecting
    $szIP_Accepted = SocketToIP($ConnectedSocket)

    ; GUI Message Loop
    ;==============================================
    While 1
        $msg = GUIGetMsg()

        ; GUI Closed
        ;--------------------
        If $msg = $GUI_EVENT_CLOSE Then ExitLoop

        ; Try to receive (up to) 2048 bytes
        ;----------------------------------------------------------------
        $recv = TCPRecv($ConnectedSocket, 2048)

        ; If the receive failed with @error then the socket has disconnected
        ;----------------------------------------------------------------
        If @error Then 
            $ConnectedSocket = -1
            WaitForConnection()
        EndIf

        ; Update the edit control with what we have received
        ;----------------------------------------------------------------
        If $recv <> "" Then GUICtrlSetData($edit, _
                $szIP_Accepted & " > " & $recv & @CRLF & GUICtrlRead($edit))
        If $recv = "close" then ExitLoop
    WEnd


    If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)

    TCPShutdown()
EndFunc   ;==>Example

; Function to return IP Address from a connected socket.
;----------------------------------------------------------------------
Func SocketToIP($SHOCKET)
    Local $sockaddr, $aRet
    
    $sockaddr = DllStructCreate("short;ushort;uint;char[8]")

    $aRet = DllCall("Ws2_32.dll", "int", "getpeername", "int", $SHOCKET, _
            "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   ;==>SocketToIP

Func WaitForConnection()
    Do
        $ConnectedSocket = TCPAccept($MainSocket)
    Until $ConnectedSocket <> -1
EndFunc

Yeah I'm not the greatest at DarkBasic either, but I'm good enough for a link :D A Thread of a W.I.P. that im making

Link to comment
Share on other sites

You can split the string into an array then further split each element of the array to get what you need. Here's a little demo, should work for your purposes unless I'm confused...which I often am Posted Image

$theString = "i12i31i231"

;Split string by each "i" so we're left with an array of 5 elements in this example...'4', '', '12', '31', '231'
$aString = StringSplit($theString, "i")

;Start with third element (index 2) of array because the first element
;is just a count and the second element is empty because the string starts with an "i"
For $i = 2 To $aString[0]
;Return the first character of the element, this is the key you want to send
$sendKey = StringLeft($aString[$i], 1)

;Trim the first character from the left and use the rest of the element as the number of seconds to wait
$sleepTime = StringTrimLeft($aString[$i], 1)

;Display values of the variables just created
ConsoleWrite(@CRLF & "Press " & $sendKey & " then sleep for " & $sleepTime & " seconds." & @CRLF)

;Demo loop
For $j = $sleepTime To 1 Step -1
  ConsoleWrite($j & "...")
  Sleep(1000)
Next
Next

Exit
Link to comment
Share on other sites

Another way:

#include <Array.au3>    ; for illustration purpose
Local $str = 'i12i31i231'
$res = StringRegExp($str, 'i(\d)(\d+)', 3)
_ArrayDisplay($res)     ; for illustration purpose
For $i = 0 To UBound($res) - 1 Step 2
    ConsoleWrite($res[$i])
    Sleep($res[$i + 1] * 1000)
Next

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

I got the client and server fully communicating! Much thanks to both of you. I ended up using the second example, with a little modification. I just can't seem to get the console write working... no errors show, but it doesn't write to my application.

Here is the code I did use:

If $recv <> "" Then 
    $res = StringRegExp($recv, 'i(\d)(\d+)', 3)
    For $i = 0 To UBound($res) - 1 Step 2
        Send(($res[$i]))
        Send("{enter}")
        Sleep($res[$i + 1] * 1000)
    Next

    EndIf

Now, I just need to figure out that clear button in the client script. I would assume I need StringRight somewhere, but I'm not sure. Any ideas?

Yeah I'm not the greatest at DarkBasic either, but I'm good enough for a link :D A Thread of a W.I.P. that im making

Link to comment
Share on other sites

O yes, the console was just for quick and dirty display under SciTe. The console doesn't show up in GUI application, lest particular code to this effect.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...