Version:0.9 StartHTML:0000000105 EndHTML:0000050648 StartFragment:0000001053 EndFragment:0000050632
program HelloWorldWebServerX4_Arduino_Sensor;
//{$APPTYPE CONSOLE minimal -extend autotimer IP Hoster to Arduino event}
// get a temp value from arduino to serve with socks on a browser
//#sign: max: MAXBOX8: 18/01/2017 18:48:51
//uses SysUtils, IdContext, IdCustomHTTPServer, IdHTTPServer;
Const
COMPORT = 'COM3';
IPPORT = 8080;
LOGFILE = 'arduino_temp36log7.txt';
JSCRIPT = 'C:\maXbox\softwareschule\IBZ_2016\IBZ_Prozesstechnik_2016\Uebungen\date_time.js';
var hlog1: THotlog;
artimer: TTimer;
jsload, tmpval,tmp2,aremoteip, HStarttime: string;
function connectAndGetValue: string; forward;
procedure HTTPServerCommandGet(thread: TIdPeerThread;
ReqInfo: TIdHTTPRequestInfo; RespInfo: TIdHTTPResponseInfo);
begin
RespInfo.ResponseNo:= 200;
//RespInfo.ContentText:= 'IBZ TimeTempServe: '//charset=UTF-8'
// +DateTimeToInternetStr(Now,true)+': '+tmpval;
reqinfo.document := exepath+'/';
aremoteip:= ReqInfo.remoteIP;
RespInfo.ContentType:= 'text/HTML';
RespInfo.ContentText := '<!DOCTYPE html><html><head>'+
'<META HTTP-EQUIV="Refresh" CONTENT=5>'+
'<title>My Arduino mXResponse</title>'+
//'<script type="text/javascript" src="date_time.js"></script>'+
'<script type="text/javascript">'+jsload+'</script>'+
CRLF+'</head>'+CRLF+'<body>'+CRLF+
'<h1>Welcome OpenC° & maXbox4 temptime </h1>'+
'<h1>************************************</h1>'+
'Command: ' +ReqInfo.Command+' of Temperature C°: <b>'+tmpval+'</b>'+
'<p><br>Host: ' + ReqInfo.Host + ' C°: '+tmp2+
'<br>RemoteIP: '+ ReqInfo.remoteIP +
'<br>Version: ' + ReqInfo.Version +
'<br>Docpath: ' + ReqInfo.Document +
'<br>Client: <span id="date_time"></span>'+
'<script type="text/javascript">window.onload=date_time(''date_time'');</script>'+
'<br>Host Starttime: '+ HStarttime+
'<br>URI: ' + ReqInfo.URI +
'<br>ServerContent SW: '+RespInfo.ServerSoftware+
'<br>UserAgent: ' + ReqInfo.UserAgent+'</p>'+
'<IMG SRC="http://www.softwareschule.ch/images/atom_ani.gif"'+
' ALIGN="BOTTOM" BORDER="0" COLOR="#fffed3">'+
'</body></html>'; //*)
tmp2:= tmpval;
hlog1.AddStr(DateTimeToStr(Now)+': '+tmpval+'>'+ReqInfo.remoteIP);
end;
procedure eventActTimer(sender: TObject);
begin
tmpval:= connectAndGetValue;
writeln(datetimetostr(now)+' C°: '+tmpval+'° >'+aremoteIP)
end;
procedure StartLogger;
begin
if not FileExists(ExePath+LOGFILE) then begin
CloseFileHandle(FileCreate(ExePath+LOGFILE));
sleep(500);
end;
hlog1:= THotlog.create;
hlog1.hlWriter.hlFileDef.filename:= LOGFILE;
hlog1.hlWriter.hlFileDef.path:= exepath;
hlog1.hlWriter.hlFileDef.append:= true;
writeln('Logfile: '+hlog1.hlWriter.hlFileDef.filename)
//SetHotLogHeader(hlog1);
hlog1.StartLogging;
sleep(200)
hlog1.Add('>>>> Start {App_name} v {App_ver}{40@}{now}');
hlog1.Add('{@12}From : '+'maxform1.appname');
end;
function connectAndGetValue: string;
begin
with TBlockSerial.Create do begin
Config(9600,8,'N',1,true,false);
Connect(COMPORT);
result:= RecvString(1800) //com timeout
CloseSocket;
Free;
end;
end;
begin //@main
jsload:= filetostring(JSCRIPT)
tmp2:= '0';
HStarttime:= DateTimeToInternetStr(Now,true)
//TWebServerCreate;
with TIdHTTPServer.Create(Nil) do begin
sr:= GetIPfromHost(getHostName) //'172.16.10.80';
try
Bindings.Add.IP:= sr;
Bindings.Add.Port:= IPPORT;
OnCommandGet:= @HTTPServerCommandGet;
Active:= True;
except
writeln(ExceptionToString(ExceptionType, ExceptionParam));
Active:= False; Free;
end;
try
StartLogger;
If IsCOMPort then begin
writeln('SerialPortNames Init: '+GetSerialPortNames);
with TBlockSerial.Create do begin
SetCommState;
Free;
end;
end;
arTimer:= TTimer.Create(Self);
arTimer.Enabled:= true;
arTimer.Interval:= 2000;
arTimer.OnTimer:= @eventActTimer;
//ConnectArduinoSense;
Writeln('Hello Temp/Web server start at: '+sr);
ShowMessageBig('maXbox HellTempWeb server at: '+sr+':'+itoa(IPPORT)+#1310+
' Press OK to quit webserver!'+#13);
finally
writeln('SocketServer stop: '+timetoStr(now)); //Destroy;
Active:= False; Free;
hlog1.Add('<<<< Stop socktimer {App_name}{40@}{now}');
hlog1.Free;
arTimer.enabled:= false;
arTimer.Free;
end;
end;
End.
Ref:
https://rosettacode.org/wiki/Hello_world/Web_server#Delphi
add bindings & contenttype for more convention
SetCommState;
//'<br />URI: ' + ARequestInfo.params[1] +
To Do Task:
- log the exceptions
- reduce latency with open comport
- fix the host start time
Exception: Could not bind socket. Address and port are already in use.
PrintF('Command %s received: %s of temperature C°: %s',
[RequestInfo.Command,thread.connection.Socket.binding.PeerIP,tmp2]);
Doc:
Function DateTimeToInternetStr( const Value : TDateTime; const AIsGMT : Boolean) : String
Function GetIPAddress( const HostName : string) : string
Function GetIP( const HostName : string) : string
Function GetIPHostByName(const AComputerName: String): String;
function GetIPFromHost(const HostName: string): string;
HTTPServer1.Bindings.Add.IP := '127.0.0.1';
HTTPServer1.Bindings.Add.Port := 50001;
writeln(GetIPAddress(getHostName));
writeln(GetIP(getHostName));
writeln(GetIPHostByName(gethostname));
writeln(GetIPfromhost(gethostname));
//writeln(RecvBlock(1000))
//SendString('8')
This is a common newbie mistake. You are creating two bindings, one bound to 127.0.0.1:DefaultPort, and one bound to 0.0.0.0:50001. You need one binding instead, that is bound to 127.0.0.1:50001 instead.
with HTTPServer1.Bindings.Add do begin
IP := '127.0.0.1';
Port := 50001;
end;
client call example:
procedure TDataFormbtnHTTPSendGetClick(Sender: TObject);
var
HTTPClient : TIdHTTP;
responseStream : TMemoryStream;
begin
HTTPClient := TIdHTTP.Create(Nil);
responseStream := TMemoryStream.Create;
try
try
HTTPClient.Get1('http://127.0.0.1:8080', responseStream);
responseStream.Seek(0, soFromBeginning);
SetLength(Sr, responseStream.Size);
responseStream.Read(Sr, responseStream.Size);
writeln('response: '+sr)
//writeln(': '+streamtoString3(responseStream))
except
//on e : Exception do begin
showmessage('Could not send get request to localhost, port 8080');
end;
//end;
finally
//FreeAndNil(HTTPClient);
HTTPClient.Free;
HTTPClient:= Nil;
responseStream.Free;
end;
end;
//******************************Arduino Uno************************
int incomingByte = 0;
int gndPin = A1; // select the input pin for the potentiometer
int sensePin = 2; //analog in
int ledPin = 13; // select the pin for the LED
int plusPin = A3; // variable to store the value coming from the sensor
int cnt = 0;
int ledPin8 = 8;
int val = 0;
void setup(){
Serial.begin(9600);
pinMode(ledPin8,OUTPUT); // declare the LED's pin as output
pinMode(gndPin, OUTPUT);
digitalWrite(gndPin, LOW);
pinMode(plusPin, OUTPUT);
digitalWrite(plusPin, HIGH);
//Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop(){
//data=analogRead(rfReceivePin); //listen for data on Analog pin 0
/*if (Serial.available() > 0) {
incomingByte = Serial.read();
Serial.println(incomingByte, DEC);
}*/
incomingByte = 0;
int raw = analogRead(sensePin);
float volts = raw / 205.0;
float tempC = 100.0 * volts - 50;
float tempF = tempC * 9.0/5.0+32.0;
Serial.print(cnt);
//Serial.print(DateTimeStrings());
Serial.print(" C.temp: ");
Serial.println(tempC);
// turn the ledPin on
val = Serial.read(); // read the serial port
if (val=='8'){
digitalWrite(ledPin8,HIGH);
}
if (val=='H'){
digitalWrite(ledPin8,LOW);
}
//if (timeStatus()!= timeNotSet) {
//digitalClockDisplay();
//delay(1000);
//digitalClockDisplay();
delay(1000);
}
----code_cleared_checked_clean----