TCP Server UDF in Windows with AutoIt. Shutdown PC from App. Start notepad.exe. Upload file to PC. WiFi

In this topic we saw how we can communicate with a PC (Windows) via Bluetooth through a code made with AutoIt:

[AutoIt Downloads - AutoIt] (AutoIt Downloads - AutoIt) (free) (18 MB)

Now we are going to communicate our App with our PC (Windows) via WiFi.
We will send an order to shut down the PC and another order to start the notepad.exe

We will rely on this code:

https://github.com/jesobreira/TCPServerUDF

Tutorial Autoit (Spanish)
http://kio4.com/autoit/index.htm

2 Likes

1.- App Inventor.

p119B_WiFiAutoit.aia (2.0 KB)

IP of PC.
App sends "shutdown" or "notepad"

wifi_apagar

2.- AutoIt codes.

It needs TCPServer.au3

I have modified the following code, I have only enabled the received function.

This code does not offer information return.

example.au3

#include "TCPServer.au3"

; First we set the callback functions for the three events (none of them is mandatory)
;_TCPServer_OnConnect("connected")
;_TCPServer_OnDisconnect("disconnect")
_TCPServer_OnReceive("received")


; And some parameters
_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

; Finally we start the server at port 8081 at any interface
_TCPServer_Start(8081)

Func connected($iSocket, $sIP)
	MsgBox(0, "Client connected", "Client " & $sIP & " connected!")
	_TCPServer_Broadcast('new client connected guys', $iSocket)
	_TCPServer_Send($iSocket, "Hey! Write something ;)" & @CRLF)
	_TCPServer_SetParam($iSocket, "will write")
EndFunc   ;==>connected

Func disconnect($iSocket, $sIP)
	MsgBox(0, "Client disconnected", "Client " & $sIP & " disconnected from socket " & $iSocket)
EndFunc   ;==>disconnect

Func received($iSocket, $sIP, $sData, $sPar)
	  MsgBox(0, "Data received from " & $sIP, $sData & @CRLF & "Parameter: " & $sPar)
	 ;_TCPServer_Send($iSocket, "You wrote: " & $sData)
	 ;_TCPServer_SetParam($iSocket, 'will write again')
	       $iPosition = StringInStr($sData, "notepad")
		   if $iPosition <> 0 Then
              Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		   EndIf
	       $iPosition = StringInStr($sData, "shutdown")
		   if $iPosition <> 0 Then
             Shutdown(64)
		   EndIf
EndFunc   ;==>received

While 1
	Sleep(100)
WEnd

1 Like

3.- Improved code. Information return.

Using this code, PC returns the information: "Notepad running." Received by the Web.GotText block.

example_return.au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)

Func received($iSocket, $sIP, $sData, $sParam)
      $iPosition = StringInStr($sData, "notepad")
		   if $iPosition <> 0 Then
              Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		   EndIf

	  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
					"Content-Type: text/html" & @CRLF & @CRLF & _
					"Notepad running.")
	_TCPServer_Close($iSocket)
EndFunc   ;==>received

While 1
	Sleep(100)
WEnd

http://kio4.com/autoit/119B_Apagar_wifi.htm

1 Like

4.- Run Notepad and Kill Notepad.

wifi_apagar4

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)

Func received($iSocket, $sIP, $sData, $sParam)
	   $iPosition = StringInStr($sData, "notepad")
	   if $iPosition <> 0 Then
		  Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Notepad running.")
	     _TCPServer_Close($iSocket)
	   EndIf

	   $iPosition = StringInStr($sData, "kill")
	   if $iPosition <> 0 Then
		   Run(@ComSpec & " /c " & 'taskkill /IM "notepad.exe" /F', "", @SW_HIDE)
		  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Killing Notepad.")
	     _TCPServer_Close($iSocket)
	   EndIf


EndFunc   ;==>received
1 Like

5.- Upload image file to PC.

p119B_WiFiAutoit_Archivo.aia (92.0 KB)

Two examples:

a) Copy foto5.png from the asset to the ASD.
Convert it to Base64 using an extension.
Upload the string to the PC

b) Take Picture with cam.
Convert Picture to Base64 using an extension.
Upload the string to the PC.

The Autoit code receives the string, decodes the Base64 and saves it in the imagen1.png file, in the same directory as the script.

archivo.au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)


Func received($iSocket, $sIP, $sData, $sPar)

Sleep(100)
$BASE64_DATA = $sData
$BASE64_DATA = StringReplace ($BASE64_DATA, @CR, "")
$BASE64_DATA = StringReplace ($BASE64_DATA, @LF, "")

$base64_code =  StringSplit($BASE64_DATA, "gzip", 1)
$BASE64_DATA =$base64_code[2]

    Local $hFile = 0
	$sImageName = "imagen1.png"
    $hFile=FileOpen($sImageName, 18)
    FileWrite($hFile, _Encoding_Base64Decode($BASE64_DATA))
    FileClose($hFile)

    _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Recibido.")
	     _TCPServer_Close($iSocket)

EndFunc   ;==>received

While 1
	Sleep(100)
WEnd


Func _Encoding_Base64Decode($sData)
    Local $struct = DllStructCreate("int")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $sData, _
            "int", 0, _
            "int", 1, _
            "ptr", 0, _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(1, 0, "") ; error calculating the length of the buffer needed
    EndIf

    Local $a = DllStructCreate("byte[" & DllStructGetData($struct, 1) & "]")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $sData, _
            "int", 0, _
            "int", 1, _
            "ptr", DllStructGetPtr($a), _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(2, 0, "") ; error decoding
    EndIf

    Return BinaryToString(DllStructGetData($a, 1))
EndFunc   ;==>_Encoding_Base64Decode

Shutdown PC from App? Well, I hope my wife doesn't see this :joy:

1 Like

6.- Copy file from PC to App.

p119B_WiFiAutoit_Get_File.aia (25.4 KB)

wifi_apagar8

  • We write the absolute address of a file on our PC, for example:
    C:\Users\juan\Documents\foto6.png

  • The server will receive that address, take the file and convert it to a Base64 string.

  • The server will send the string, it will be obtained by the Web.GotText block via responseContent.

  • The KIO4_Base64 extension will take the string, convert it to a file and save it to the ASD with the name image_PC.png

  • image_PC will be displayed in an Image component.

Important: Addresses with intervening spaces are not supported.

Credits:

Base64 Converter by
https://www.autoitscript.com/forum/topic/145526-base64-converter-files-and-strings-can-be-modified-easily

http://kio4.com/autoit/119B_Apagar_wifi.htm

archivo_pasar.au3

Summary
#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)
Global $__b64___B64_list[64]


Func received($iSocket, $sIP, $sData, $sPar)

$receive = StringSplit($sData, "gzip", 1)
$address = $receive[2]
$address = StringStripWS($address, 1) ; remove white space
$encoded = B64Encode($address, 0, 64, 1)
; MsgBox(0, 'Completed', $encoded)


    _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				 $encoded)
	_TCPServer_Close($iSocket)

EndFunc   ;==>received

While 1
	Sleep(100)
WEnd


; ======================= Functions: =========================
Func B64Encode($__b64_input = '', $__b64_mode = 0, $__b64_linebreak = 0, $__b64_isfile = 0)
If $__b64_input = '' Then MsgBox(0, 'Hint', 'B64Encode($InputData, 0 = ANSI 1 = is UTF-8, 0-76 Linebreak, 1 = is a file (filename)')
__init_b64_dictionary()
If $__b64_linebreak > 76 Then
MsgBox(0, 'Error', 'Base64 encode linebreak cannot exceed 76 characters.')
Exit
EndIf
If $__b64_mode = 0 Then
$__b64_mode = 1
Else
$__b64_mode = 4
EndIf
Local $__b64_TheBitStream, $__b64_4_SixBitChunks, $__b64_FinalOutput, $__b64_tempvalue, $__b64_FinalOutput2
If Not $__b64_isfile Then
$__b64_o_UTF_8 = StringTrimLeft(StringToBinary($__b64_input, $__b64_mode), 2)
Else
$__b64_openfile = FileOpen($__b64_input, 16)
$__b64_o_UTF_8 = StringTrimLeft(FileRead($__b64_openfile), 2)
FileClose($__b64_openfile)
EndIf
For $__b64_a = 1 To StringLen($__b64_o_UTF_8) Step 2
$__b64_TheBitStream &= __init_b64_EightBitBinary('0x' & StringMid($__b64_o_UTF_8, $__b64_a, 2))
Next
For $__b64_a = 1 To StringLen($__b64_TheBitStream) Step +6
$__b64_Number = __init_b64_FromSixBitBinary(StringMid($__b64_TheBitStream, $__b64_a, 6))
$__b64_FinalOutput &= $__b64___B64_list[$__b64_Number]
Next
While Floor(StringLen($__b64_FinalOutput) / 4) <> (StringLen($__b64_FinalOutput) / 4)
$__b64_FinalOutput &= '='
WEnd
If $__b64_linebreak > 0 Then
For $__b64_a = 1 To StringLen($__b64_FinalOutput) Step $__b64_linebreak
$__b64_FinalOutput2 &= StringMid($__b64_FinalOutput, $__b64_a, $__b64_linebreak)
If $__b64_linebreak > 0 Then
If StringLen(StringMid($__b64_FinalOutput, $__b64_a, $__b64_linebreak)) = $__b64_linebreak And $__b64_a <= (StringLen($__b64_FinalOutput) - $__b64_linebreak) Then $__b64_FinalOutput2 &= @CRLF
EndIf
Next
Else
$__b64_FinalOutput2 = $__b64_FinalOutput
EndIf
Return $__b64_FinalOutput2
EndFunc ;==>B64Encode

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_dictionary
; Description ...: Used to initialize the base64 dictionary used in conversions
; Syntax ........: __init_b64_dictionary()
; Parameters ....: None
; Return values .: None
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: Creates an array with base64 dictionary. Also creates variables with direct names for easy and quick access while decoding letters to numbers.
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_dictionary()

For $__b64_a = 0 To 63
Select
Case $__b64_a < 26
$__b64___B64_list[$__b64_a] = ChrW(65 + $__b64_a)
Assign('U' & ChrW(65 + $__b64_a), $__b64_a, 2)
Case $__b64_a < 52
$__b64___B64_list[$__b64_a] = ChrW(71 + $__b64_a)
Assign('N' & ChrW(71 + $__b64_a), $__b64_a, 2)
Case $__b64_a < 62
$__b64___B64_list[$__b64_a] = ChrW($__b64_a - 4)
Assign('N' & ChrW($__b64_a - 4), $__b64_a, 2)
Case $__b64_a = 62
$__b64___B64_list[$__b64_a] = ChrW(43)
Assign('N' & ChrW(43), $__b64_a, 2)
Case $__b64_a = 63
$__b64___B64_list[$__b64_a] = ChrW(47)
Assign('N' & ChrW(47), $__b64_a, 2)
EndSelect
Next
EndFunc ;==>__init_b64_dictionary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_EightBitBinary
; Description ...: Outputs an 8-bit binary string from an input integer between 0 and 255
; Syntax ........: __init_b64_EightBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] Integer between 0 and 255 Default is 0.
; Return values .: 8-bit binary string representing the input integer
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: An 8-bit binary string looks like 10101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_EightBitBinary($__b64_input = 0)
If $__b64_input < 256 Then
$__b64_tmpbitstream = ''
$__b64_start = 128
While $__b64_start >= 1
If Floor($__b64_input / $__b64_start) Then
$__b64_tmpbitstream &= 1
$__b64_input -= ($__b64_start * Floor($__b64_input / $__b64_start))
Else
$__b64_tmpbitstream &= 0
EndIf
$__b64_start /= 2
WEnd
Else
$__b64_tmpbitstream = 0
EndIf
Return $__b64_tmpbitstream
EndFunc ;==>__init_b64_EightBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_SixBitBinary
; Description ...: Outputs a 6-bit binary string from an input integer between 0 and 63
; Syntax ........: __init_b64_SixBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] An integer between 0 and 63. Default is 0.
; Return values .: A 6-bit binary string representing the input integer
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: A 6-bit binary string looke like 101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_SixBitBinary($__b64_input = 0)
If $__b64_input < 64 Then
$__b64_tmpbitstream = ''
$__b64_start = 32
While $__b64_start >= 1
If Floor($__b64_input / $__b64_start) Then
$__b64_tmpbitstream &= 1
$__b64_input -= ($__b64_start * Floor($__b64_input / $__b64_start))
Else
$__b64_tmpbitstream &= 0
EndIf
$__b64_start /= 2
WEnd
Else
$__b64_tmpbitstream = 0
EndIf
Return $__b64_tmpbitstream
EndFunc ;==>__init_b64_SixBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_FromSixBitBinary
; Description ...: Outputs an integer between 0 and 63 based on a 6-bit binary input.
; Syntax ........: __init_b64_FromSixBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] 6-bit binary input. Default is 0.
; Return values .: Integer between 0 and 63
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: A 6-bit binary string looke like 101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_FromSixBitBinary($__b64_input = 0)
$__b64_base = 32
$__b64_tempvalue = 0
For $__b64_a = 1 To 6
If StringMid($__b64_input, $__b64_a, 1) = 1 Then
$__b64_tempvalue += $__b64_base
EndIf
$__b64_base /= 2
Next
Return $__b64_tempvalue
EndFunc ;==>__init_b64_FromSixBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_FromEightBitBinary
; Description ...: Outputs an integer between 0 and 255 from an 8-bit binary input.
; Syntax ........: __init_b64_FromEightBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] An 8-bit binary string. Default is 0
; Return values .: Integer between 0 and 255
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: An 8-bit binary string looks like 10101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_FromEightBitBinary($__b64_input = 0)
$__b64_base = 128
$__b64_tempvalue = 0
For $__b64_a = 1 To 8
If StringMid($__b64_input, $__b64_a, 1) = 1 Then
$__b64_tempvalue += $__b64_base
EndIf
$__b64_base /= 2
Next
Return $__b64_tempvalue
EndFunc ;==>__init_b64_FromEightBitBinary