Skip to content

how to send encoded messaged through udp? #2

Open

Description

@mcsY

Guillaume,

I am having a problem sending Mavlink messages generated from your code through UDP client to my quadcopter.

I followed your instructions below:
Use encode() method on MAVLink message to generate a byte buffer so you can send it in a Data Output Stream. {{{

    msg_heartbeat hb = new msg_heartbeat(sysId, componentId);
    hb.sequence = sequence++;
    hb.autopilot = MAV_AUTOPILOT.MAV_AUTOPILOT_PX4;
    hb.base_mode = MAV_MODE_FLAG.MAV_MODE_FLAG_STABILIZE_ENABLED;
    hb.custom_mode = custom_mode;
    hb.mavlink_version = 3;
    hb.system_status = MAV_STATE.MAV_STATE_POWEROFF;
    byte[] result = hb.encode();
    dos.put(result);

}}}

Can you explain in more detail on how to get the quadcopter to receive this message. I am not that great at java programming, so I am not really sure want I need to do. I included my program below.
I think I am not just doing this correctly.

public class Client {
public static void main(String[] args) throws IOException{

    final int REMOTE_PORT= 14550;
    final String REMOTE_IP ="localhost"; //modify this accordingly if you want to test remote
    int sequence = 0;
    final int sysId = 255;
    final int componentId =1



     // heartbeat cmd
     msg_heartbeat hb = new msg_heartbeat(sysId, componentId);
     hb.sequence = sequence++;
     hb.autopilot = MAV_AUTOPILOT.MAV_AUTOPILOT_ARDUPILOTMEGA;
     hb.base_mode = MAV_MODE_FLAG.MAV_MODE_FLAG_STABILIZE_ENABLED;
     hb.custom_mode = 2;
     hb.mavlink_version = 3;
     hb.system_status = MAV_STATE.MAV_STATE_UNINIT;
     byte[] result = hb.encode();



     //create a new datagram channel
     try(DatagramChannel datagramChannel = DatagramChannel.open(StandardProtocolFamily.INET)){

         //set some options
         datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4*1024);
         datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4*1024);



         //check if the channel was successfully  opened
         if (datagramChannel.isOpen()){
             System.out.println("Echo server was successfully opened");



             //connect to remote address
            datagramChannel.connect(new InetSocketAddress(REMOTE_IP, REMOTE_PORT));
            System.out.println("Echo server was binded on: /" + REMOTE_IP+":"+REMOTE_PORT);

            //check if the channel was successfully connected
            if (datagramChannel.isConnected()){
            System.out.println("Echo server is ready to echo...");

                //transmitting data packets

            final ByteArrayOutputStream baos=new ByteArrayOutputStream();
            final DataOutputStream dos=new DataOutputStream(baos);

             dos.write(result);



                System.out.println("I have successfully sent bytes to the Echo Server!");


            } else{
                System.out.println("The channel cannot be connected!");
                }
         } else {
             System.out.println("The channel cannot be opened");
         }
     } catch (Exception ex){
         if (ex instanceof ClosedChannelException){
             System.err.println("The channel was unexpected closed ...");
         }
         if (ex instanceof SecurityException){
             System.err.println("A security exception occured ...");
         }
         if (ex instanceof IOException){
             System.err.println("An I/O error occured ...");
         }

         System.err.println("\n" + ex);
     }
}

}

Activity

  1. anandbhaskaran commented on Oct 3, 2016

    @anandbhaskaran

    Hello! I am using this library to send encoded message through UDP. Do you still need help with this?

  2. mcsY commented on Oct 4, 2016

    @mcsY
    Author

    Yes I still do need help. I had to try a different approach but I didn't to use the library which is probably not the best approach.

    On Oct 3, 2016, at 5:01 AM, Anand notifications@github.com wrote:

    Hello! I am using this librar to send encoded message through UDP. Do you still need help with this?

    —
    You are receiving this because you authored the thread.
    Reply to this email directly, view it on GitHub, or mute the thread.

  3. anandbhaskaran commented on Oct 4, 2016

    @anandbhaskaran

    Hello mcsY,

    Here is the pseudo code to send and receive the mavlink message over UDP. I am not sure that this is an efficient way, but it works fine for me.

     public static BlockingQueue<byte[]> sendQueue = new LinkedBlockingQueue<>();
     DatagramSocket dsocket = new DatagramSocket(port);
    
     byte[] buffer = new byte[2048];
     DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    
    DatagramPacket out;
    MAVLinkReader reader = new MAVLinkReader();
    MAVLinkMessage mesg;
    SocketAddress address;
    

    After this initialization to receive the messages I use a double while loop

    while(1){
        dsocket.setSoTimeout(1000);
        // Wait to receive a datagram
        dsocket.receive(packet);
        mesg = reader.getNextMessage(packet.getData(), packet.getLength());
       while (mesg != null) {
        //Do things with the incomming message
           address = packet.getSocketAddress()
        packet.setLength(buffer.length);
        if (reader.nbUnreadMessages() != 0) {
            mesg = reader.getNextMessageWithoutBlocking();
        } else {
                 break; // Go out of the loop and get new packet
        }
        }
    
    // Send packets to the UAV if any pending
        if (!sendQueue.isEmpty()) {
        byte[] sendBuffer = sendQueue.take();
        out = new DatagramPacket(sendBuffer, sendBuffer.length, address);
        dsocket.send(out);
        }
    }
    

    You can store a list of address to manage multiple drones. I also run this in a thread, so whenever my program wants to send message to the drone it puts the bytes into the sendQueue, which will be sent to the drone by this thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions