简体   繁体   中英

Numato Ethernet Relay Module telnet in c#

I'm creating a windows desktop app (c#) and trying to send telnet command to toggle switch on/off ethernet relay when clicking the "ON" button. the problem is that when I click the button nothing happens.

*IP: 192.168.1.1

UN: samp

PW: samp*

string command = "relay on 1";

client.Send(Encoding.GetEncoding(command).GetBytes("u" + '\n'));

I ready try the code above but nothing happens.

This is the original java code I want to convert to C#.

 String relayNumber = "2"; //Change the Relay Number here when required
            byte[] data = new byte[256];
            data = new byte[256];
            data = (new String("relay off " + relayNumber + "\r\n")).getBytes("UTF-8");
            System.out.println("Info: Command sent to relay on " + relayNumber);
            outstr.write(data, 0, data.length);

If you want to create a UTF-8 encoded command string of the form

relay {on|off} {relayNumber}

You can use something like:

public static byte[] GetRelayCommandBytes(bool onoff, int relayNumber) 
{
     return System.Text.Encoding.UTF8.GetBytes($"relay {(onoff?"on":"off")} {relayNumber}");
}

I am still suspicious about the IP Adress you mentioned in the question. 192.168.1.1 is a somewhat common one for a Router.


Another source of error may be the type of client you are using and how it is set up. By the time of writing this information is not in the question, unfortunately.


I really do not want to disrespect, but whoever gave you that code may rethink his life choices:

String relayNumber = "2"; //Change the Relay Number here when required
byte[] data = new byte[256]; // <- 1. declaration and assignment of array.
data = new byte[256]; // <- 2. assignment of array!! Why??
// vv- 3. assignment, making the prior 2 completely senseless.
data = (new String("relay off " + relayNumber + "\r\n")).getBytes("UTF-8");
//      ^- my Java is rusty, but I am pretty confident, `new String` is not the best of ideas.
System.out.println("Info: Command sent to relay on " + relayNumber);
// => "Logging" successful transmission, when it didn't even write, yet.
outstr.write(data, 0, data.length);

I am just dissecting this for you, so you can make your own informed decision about whether you may want to do your own research on how to speak to the device instead of relying on code of that "quality" as a template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM