Send Byte Command via socket to a python controller?

Asked

Viewed 180 times

1

Hello guys I am trying to send commands to a Controller "Commbox", this controller has the objective to open and close gates, traffic lights and other things. I am able to send command in Java but I need to do the same command in Python. As I am beginner in the language I am not succeeding. Below is the code in Java and Python:

package teste2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;


public class teste {

    public static void main(String[] args){
        Socket socket = new Socket();
        OutputStream out;
        InputStream in;



        try {
            socket.setSoTimeout(10000);
            socket.setTcpNoDelay(false);
            socket.connect(new InetSocketAddress("192.168.1.210", 4091), 1000);
            out = socket.getOutputStream();
            in = socket.getInputStream();
            byte[] b =  {-86, 85, -86, 85, 0, 0, 0, 1, 0, 0, 0, 18, 0, 0, 0, 0, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 6, 20, 0, 0, 0, 1, 0, 0, 0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            out.write(b);
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Python:

import socket

sockt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    sockt.settimeout(10000)
    sockt.connect(('192.168.1.210', 4091))
    b = bytearray()
    lista = [42, 213, 42, 213, 128, 128, 128, 129, 128, 128, 128, 146, 128, 128, 128, 128, 127, 127, 127, 127, 128, 128, 128, 128, 128, 128, 134, 148, 128, 128, 128, 129, 128,
         128, 128, 132, 130, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]

    for i in range(lista.__len__()):
        b.append(lista[i])

    print(b)

    sockt.send(b)
    resposta = sockt.recv(4091)
    print(resposta)

finally:
    exit()

Note: The command is different because I was not able to assemble an array of negative bytes in python, searching I saw that bytes in java go from -128 to 127 and Python from 0 to 256. So I tried to change the values.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.