I am trying to capture the net weight from a IND560 using C#'s streamReader and streamWriter classes. It seems a connection is made, but no matter the command I send, I get a response back: 83 Command not recognized. I see the command (wt0111) in the IND560 under Communications>Template>output for template1.
The code is below if anyone has any suggestions to help me move forward it would be much appreciated!
static void writeToStream(string cmd)
{
if (tcpClient.Connected)
{
Console.WriteLine("Sending CMD: {0}\\n", cmd);
// tried with appending a \r, \n, and \r\n same result: 83 command not found
clientStreamWriter.Write(cmd + '\n');
clientStreamWriter.Flush();
}
}
Here is a sample output of the program showing the response 83:
You would need to use read command for the purpose (according to link here)
Format: read SDV#1 SDV#2
Example 1: read wt0101 wt0103
Response 1: 00R003~ 17.08~lb~
So, in your case
read wt0101
read wt0111
In your case you would need to prepend "read" before the field ID (wt0101).
if (tcpClient.Connected)
{
Console.WriteLine("Sending CMD: {0}\\n", cmd);
clientStreamWriter.Write($"read {cmd}" + '\n');
clientStreamWriter.Flush();
}
I would suggest to provide your users an option to input the command to "read" "write", "help", along with field name, in case you are intending to support more command.
Related
I am writing my own terminal and want to add the ability to execute CMD commas. I found this code on Microsoft website:
using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
namespace ProcessStandardInputSample
{
class StandardInputTest
{
static void Main()
{
Console.WriteLine("Ready to sort one or more text lines...");
// Start the Sort.exe process with redirected input.
// Use the sort command to sort the input text.
using (Process myProcess = new Process())
{
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
StreamWriter myStreamWriter = myProcess.StandardInput;
// Prompt the user for input text lines to sort.
// Write each line to the StandardInput stream of
// the sort command.
String inputText;
int numLines = 0;
do
{
Console.WriteLine("Enter a line of text (or press the Enter key to stop):");
inputText = Console.ReadLine();
if (inputText.Length > 0)
{
numLines++;
myStreamWriter.WriteLine(inputText);
}
} while (inputText.Length > 0);
// Write a report header to the console.
if (numLines > 0)
{
Console.WriteLine($" {numLines} sorted text line(s) ");
Console.WriteLine("------------------------");
}
else
{
Console.WriteLine(" No input was sorted");
}
// End the input stream to the sort command.
// When the stream closes, the sort command
// writes the sorted text lines to the
// console.
myStreamWriter.Close();
// Wait for the sort process to write the sorted text lines.
myProcess.WaitForExit();
}
}
}
}
I tested this code on several commands and everything worked fine, without errors. But I decided to test running python scripts with this code. I decided to run sqlmap through my terminal with the command:
python C:\sqlmap\sqlmap.py --wizard
I got the following result:
___
__H__
___ ___["]_____ ___ ___ {1.6.11.3#dev}
|_ -| . [(] | .'| . |
|___|_ ["]_|_|_|__,| _|
|_|V... |_| https://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting # 22:26:59 /2022-12-07/
[22:26:59] [INFO] starting wizard interface
Please enter full target URL (-u):
At this stage, everything works properly, without errors.
When I enter any link, I always get the same result:
POST data (--data) [Enter for None]:
Injection difficulty (--level/--risk). Please choose:
[1] Normal (default)
[2] Medium
[3] Hard
> 1
Enumeration (--banner/--current-user/etc). Please choose:
[1] Basic (default)
[2] Intermediate
[3] All
> 1
sqlmap is running, please wait..
The problem is that after entering the link in the future, the program does not expect any input from the user, all the parameters in the above result were not entered by the user
I did not find an answer to my question on the Internet, why the parameters are set themselves, without user participation. I would be very grateful if I get an answer to my question, because I do not understand what exactly the problem is
I wanted all parameters to be requested from the user, and not set without his knowledge.
Im trying to send a string over an serial port using C#.
I've accomplished to send this string via the terminal on my RaspBerry pi ( Raspbian) using the following command:
echo "TestMode On" > /dev/ttyAMC0
This works! but this is in the terminal only. What I would like to do is execute this specific command using C# What my current approach is is this :
public bool DoSomething(){
MySerial = new SerialPort("/dev/ttyACM0");
MySerial.Open();
MySerial.ReadTimeout = 400;
string s = "echo \"TestMode On\"\r";
Log.Information(s);
return SendData(s);
}
private bool SendData(string command)
{
MySerial.Write(command);
return true;
}
I'm Using Serilog to log information and in that console window I can see that the string really is:
echo "TestMode On"
What am I missing here?.
Thanks in advance,
Herm L.
Echo sends a newline by default and you would not include the quotes:
This line:
string s = "echo \"TestMode On\"\r";
Becomes:
string s = "TestMode On\n";
The solution in this case is to change the encoding on the serial port from ASCII to UTF8. Apperantly this makes a difference here. Thanks everyone for their time and efforts!
I'm trying to convert TCL code, used to communicate with a serial port to a "robot", to C#. But for some reason my commands are not getting responses.
This is the serial com init in TCL:
proc openUart {} {
set robot::fd_ [open COM${robot::port_num}: w+]
fconfigure $robot::fd_ -mode 9600,e,7,1
fconfigure $robot::fd_ -blocking 0
fconfigure $robot::fd_ -buffering none
fileevent $robot::fd_ readable ""
}
A "command" is sent like this:
proc SendCmd {command} {
set commandlen [string length $command]
for {set i 0} {$i < $commandlen} {incr i} {
set letter [string index $command $i]
after 10
puts -nonewline $robot::fd_ $letter
}
after [expr 2 * 10]
puts -nonewline $robot::fd_ "\n"
flush $robot::fd_
}
This is how I translated this to C#. Opening the port:
private void Initialize(string com)
{
_comPort = new SerialPort(com,9600,Parity.Even,7,StopBits.One)
{
Encoding = Encoding.ASCII,
NewLine = "\n"
};
_comPort.Open();
}
And sending a command:
private string SendCommand(Commands cmd)
{
string commandToWrite = Command(cmd);
for (int i = 0; i < CommandLen; i++)
{
Thread.Sleep(10);
_comPort.Write(commandToWrite.ToCharArray(), i, 1);
}
Thread.Sleep(10 * 2);
_comPort.Write("\n");
_comPort.BaseStream.Flush();
}
I connected my PC to the robot with a serial to USB cable and ran both TCL and C# programs -
The TCL script turns on a LED on the robot.
My C# code doesn't turn the LED on, meaning the robot did not recognize the command.
I'm using the same com port, so I believe the problem is one of these:
I did not initialize the com port correctly in C#. How do you set the blocking and buffering?
Could there be an encoding issue in C#? isn't ASCII the default encoding in TCL?
Could there be a timing difference in how I'm sending the command letter-by-letter between the two languages?
Issue resolved!
I finally looped back the cable into my PC using another serial cable and 2 blue wires, crossing the RX\TX (thanks don_q for the idea!).
Using a simple serial monitor, "UART Terminal", I sniffed the commands, and to my surprise the TCL script was adding a '\r' before the '\n'!
So in fact the robot was expecting this command format -
:010508010000F1\r\n
I changed the NewLine property in C# to be "\r\n", and now I finish a command by using -
_comPort.WriteLine("");
And now everything works.
I have a windows application for sending SMS connecting to a GSM Modem. I only use AT Commands for connecting to port and sending text.
My problem is I can't send a message more that one part (each part is 160 characters for English and 70 characters for Farsi).
Here is the part I command the port to send sms using AT commands:
ExecCommand(port, "AT", 300, "No phone connected at " + strPortName + ".");
ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
var command = "AT+CSCS=\"" + "HEX" + "\"";
ExecCommand(port, command, 300, "Failed to support unicode");
ExecCommand(port, "AT+CSMP=1,167,0,8", 300, "Failed to set message properties.");
command = "AT+CMGS=\"" + phoneNo + "\"";
ExecCommand(port, command, 300, "Failed to accept phoneNo");
message = message.ToCharArray().Select(Convert.ToInt32).Select(value => String.Format("{0:X}", value)).Aggregate("", (current, hexOutput) => current + hexOutput.PadLeft(4, '0'));
command = message + char.ConvertFromUtf32(26) + "\r";
var recievedData = ExecCommand(port, command, 3000, "Failed to send message");
And here is ExecCommand method
public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
{
try
{
// receiveNow = new AutoResetEvent();
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
//Thread.Sleep(3000); //3 seconds
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw new ApplicationException(errorMessage, ex);
}
}
General AT command handling
You are on the right track, I am pleased to see several basic things done right (terminating AT command lines with \r, waiting for "\r\n> " for AT+CMGS, and waiting for the OK final result code instead of sleeping), very good start!
You do need however to change the structure somewhat. First you need to handle all the other final result codes and not just OK. And you should treat the AT+CMGS command differently from the other commands since you should wait for two things (first the prefix and later the final result code after sending the message text) for that command compared to waiting only for one thing (e.g. the final result code) for those. Also all responses from the modem are complete lines (except the "\r\n> " prefix), so change your algorithm to process the response(s) line by line.
String input;
do {
input = ReadLine(port, responseTimeout);
} while (!isFinalResultCode(input));
None of the commands you are using in the question produces an intermediate response for consumption, but if you were to run a command like AT+CPBR you would consume those intermediate responses inside that loop (and you would have to move the final result test into the loop before attempting to consume the line as an intermediate response).
You can see the is_final_result function in atinout or corresponding functions in ST-Ericsson's U300 RIL (see link and notes in this answer).
Multipart SMS
I think this is not possible in text mode. See the link suggested by Naser Asadi for details on multipart SMS in PDU mode. Also some useful information at
http://mobiletidings.com/2009/02/18/combining-sms-messages/ and http://developer.nokia.com/community/discussion/showthread.php/109602-Concatenated-SMS-in-PDU-Mode.
I'm trying to call my own REST API that returns JSON using a simple C# GUI application, and am looking for the simplest way to do so:
http://danielmiessler.com:44821/token/dGVxdWllcm8=
I am opening a file containing tokens and reading the contents line by line to get the final part of the URL:
StreamReader input = new StreamReader(openFileDialog1.OpenFile());
while ((line = input.ReadLine()) != null) {
This is going back into a textbox:
textBox2.Text += ("\t" + result + "\r\n");
Here is the Ruby code I'm trying to reproduce:
# Get our libraries
require 'httparty'
require 'json'
# Get our input from the command line
input = ARGV[0]
# Loop through the file
File.open("#{input}", "r").each_line do |line|
# Request the URL
response = HTTParty.get("http://danielmiessler.com:44821/token/#{line.chomp}")
# Go through the responses
case response.code
when 400
print "Improper input…\n"
# Feel free to remove this line if you want to reduce output.
when 200
json = JSON.parse(response.body)
print "Your input is #{json['type']} of the word: #{json['value']}\n"
when 404
print "There is no meaning in your token…\n"
# Feel free to remove this line if you want to reduce output.
end
end
Any ideas how to make the calls based on the tokens in the file and output to the text box?
You can use HttpClient for that.
This is a minimal example to get you started:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
Console.WriteLine(
"First 50 countries listed by The World Bank...");
foreach (var country in readTask.Result[1])
{
Console.WriteLine(" {0}, Country Code: {1}, " +
"Capital: {2}, Latitude: {3}, Longitude: {4}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}