74 lines
2.0 KiB
PowerShell
74 lines
2.0 KiB
PowerShell
$filePath = 'c:\Users\MyName\Desktop\PLC_Comm_D13_VCL\uMain.pas'
|
|
$lines = Get-Content $filePath -Encoding Default
|
|
$startIdx = -1
|
|
$endIdx = -1
|
|
|
|
for ($i = 0; $i -lt $lines.Count; $i++) {
|
|
if ($lines[$i] -match '^procedure TfMain\.OnMQTTMessage\(const ATopic, APayload: string\);') {
|
|
$startIdx = $i
|
|
}
|
|
if ($startIdx -ne -1 -and $lines[$i] -match '^end;') {
|
|
$endIdx = $i
|
|
break
|
|
}
|
|
}
|
|
|
|
if ($startIdx -ne -1 -and $endIdx -ne -1) {
|
|
$newCode = @"
|
|
procedure TfMain.OnMQTTMessage(const ATopic, APayload: string);
|
|
var
|
|
JsonObj: TJSONObject;
|
|
i, DONum: Integer;
|
|
Pair: TJSONPair;
|
|
KeyStr, ValStr: string;
|
|
begin
|
|
// mmMQTTmsg.Lines.Add(ATopic+' '+APayload);
|
|
Edit2.Text := ATopic+' '+APayload;
|
|
|
|
try
|
|
JsonObj := TJSONObject.ParseJSONValue(APayload) as TJSONObject;
|
|
if Assigned(JsonObj) then
|
|
begin
|
|
try
|
|
for i := 0 to JsonObj.Count - 1 do
|
|
begin
|
|
Pair := JsonObj.Pairs[i];
|
|
KeyStr := Pair.JsonString.Value;
|
|
ValStr := Pair.JsonValue.Value;
|
|
|
|
if (Length(KeyStr) >= 5) and (Copy(KeyStr, 1, 3) = 'DO_') then
|
|
begin
|
|
DONum := StrToIntDef(Copy(KeyStr, 4, Length(KeyStr) - 3), -1);
|
|
if DONum > 0 then
|
|
begin
|
|
if ValStr = '1' then
|
|
SendModbus(slvID, cmdFSC, 15 + DONum, 1)
|
|
else if ValStr = '0' then
|
|
SendModbus(slvID, cmdFSC, 15 + DONum, 0);
|
|
end;
|
|
end;
|
|
end;
|
|
finally
|
|
JsonObj.Free;
|
|
end;
|
|
end;
|
|
except
|
|
on E: Exception do printlog('MQTT Msg Error: ' + E.Message);
|
|
end;
|
|
end;
|
|
"@
|
|
|
|
$head = @($lines[0..($startIdx - 1)])
|
|
$tail = @($lines[($endIdx + 1)..($lines.Count - 1)])
|
|
|
|
$newLines = @()
|
|
$newLines += $head
|
|
$newLines += $newCode -split "`r?`n"
|
|
$newLines += $tail
|
|
|
|
Set-Content -Path $filePath -Value $newLines -Encoding Default
|
|
Write-Host "Replaced successfully. Start: $startIdx, End: $endIdx"
|
|
} else {
|
|
Write-Host "Could not find OnMQTTMessage function bounds. Start: $startIdx, End: $endIdx"
|
|
}
|