"Android Development-smart home series" (iv): UDP communication Send instructions

Source: Internet
Author: User
Tags parse string sendmsg

Thinking review

"1" Mobile connection WiFi module
"2" UDP communication to the WiFi module to send instructions to stay connected with the WiFi module
"3" UDP traffic sends instructions to the WiFi module, allowing it to search for available wireless networks and return to the WiFi list
"4" Send command to allow WiFi module to access the specified route
"5" Mobile Connection routing
"6" Send instructions to get the dynamic IP address of the WiFi module

UDP Communication Thread Class
Package Com.jczb.smartlife.common;Import java.io.IOException;Import Java.net.DatagramPacket;Import Java.net.DatagramSocket;Import java.net.InetAddress;Import java.net.InetSocketAddress;Import java.net.SocketException;Import java.net.UnknownHostException;Import Android.os.Handler;Import Android.os.Message;Import Com.jczb.smartlife.common.Tool;PublicClassGetinfothreadExtendsThread {Private Handler Handler;Private Datagramsocket socket;Privateint msgtype;PrivateFinal String IP ="255.255.255.255";Broadcast AddressPrivateint PORT =26000;/** * 48899 Port: C32X series Port, the user can change the * 49000 Port with the AT command: In addition to the C32X series, the other WiFi module port * 1902 Port: Someone control the port of the PO series products * *Privateint targetport =49000;PrivateBoolean receive =True/** * *@param handler incoming listener handler of this thread *@param intmsg Incoming Listener message type */PublicGetinfothread (Handler Handler,int Msgtype) {This.handler = handler;This.msgtype=msgtype; Init (); }PublicvoidInit () {try {socket =New Datagramsocket (NULL); Socket.setbroadcast (true); Socket.setreuseaddress (true); Socket.bind (New Inetsocketaddress (PORT)); }catch (SocketException e) {e.printstacktrace (); Senderrormsg ("Search Thread init fail");Return } }PublicvoidRun () {if (socket = =NULL) {Return }try {byte[] data =Newbyte[1024];Create an empty Datagrampacket object datagrampacket revpacket =New Datagrampacket (data, data.length);while (receive) {The server receives data socket.receive (Revpacket);IfNull!=handler) {byte[] Realdata =NewByte[revpacket.getlength ()]; System.arraycopy (data,0, Realdata,0, Realdata.length); Message msg =handler.obtainmessage (Msgtype,realdata); Handler.sendmessage (msg); } } }catch (Exception e) {e.printstacktrace (); Socket.close ();}}PublicvoidClose () {if (socket = =NullReturn Socket.close (); }PrivatevoidSenderrormsg (String info) {}/** * Send data *@param msg */PublicvoidSendmsg (Byte[] msg) {if (Socket! =NULL) {try {System.out.println ("Targetport------------------->" +targetport); Datagrampacket Sendpacket =New Datagrampacket (msg, msg.length, Inetaddress.getbyname (IP), targetport); Socket.send (Sendpacket); }catch (Unknownhostexception e) {e.printstacktrace (); System.out.println ("Send Failed"); } catch (IOException e) {e.printstacktrace (); System.out.println ("Send Failed");}} Public  void setreceive (Boolean receive) { this.receive = receive;} public void settargetport (int targetport) { this.targetport = Targetport;} public void setmsgtype (int msgtype) { this.msgtype=msgtype;}}     

The thread class that sent the message
/** * Send Message queue, each time the data is sent, only need to call PUTMSG (byte[] data) method * *@author Usr_liujinqi * * * *PrivateClassSendmsgthreadExtendsThread {Queue for sending messagesPrivate queue<Byte[]> Sendmsgquene =New linkedlist<Byte[]> ();Whether to send a messagePrivateBoolean send =TruePrivate Getinfothread SS;PublicSendmsgthread (Getinfothread ss) {THIS.SS = SS; }PublicSynchronizedvoidPutmsg (Byte[] msg) {Wake-Up threadif (sendmsgquene.size () = =0) notify (); Sendmsgquene.offer (msg); }public void Run () { synchronized (a) { while (send) { ///When a message in the queue has been sent, the thread waits while (SENDM Sgquene.size () > 0) { byte[] msg = Sendmsgquene.poll (); if (ss! = null) ss.sendmsg (msg);} try {Wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} }} public void Setsend (boolean send) { this.send = send;}}     

Application

"Example" send a search WiFi module instructions

1. The user obtains the IP address, MAC address, module name instruction of the WiFi module in the thermostatPrivateFinalByte[] Getinfocode=Newbyte[]{(Byte0x480x460x2D,0x410x310x310x410x530x530x490x530x540x480x52,0x45,0x41,0x44}; public static final int rec_module=0x04;  Search for information about the WiFi module (including IP, MAC, name)//Instantiate a thread, the user obtains the module information (IP,MAC, name) //parameter to listen to the handler for this thread, and the message type sent to handler after successful reception Getinfothread = new Getinfothread (Handler,tool.rec_module); Getinfothread.start (); //thread that sends the message SMT = new Sendmsgthread (Getinfothread); Smt.start (); //Set the destination port number to send Getinfothread.settargetport (Integer.parseint ("48899")); Smt.putmsg (Getinfocode)   ; 

WiFi module After receiving the instruction, will reply to the message, the following handler is to reply to the information to parse processing and other operations.

Processing message Handler Private Handler handler= new Handler () {public void Handlemessage (message msg) {Swit CH (msg. What) {case Tool. rec_module://parse the received data//set the destination port number to send Getinfothread. Settargetport (Integer. parseint ("48899")); Getinfothread. Setmsgtype (Tool. REC_OK); Smt. Putmsg (Okcode); Setserver (); SETDHCP (); byte[] data = (byte[]) msg. obj; Convert decimal data to hexadecimal data String strtemp= Tool. bytestohexstring (data); Parse string Strdecode=tool after removing a space in hexadecimal. Decodehex (strtemp. replace (" ","")); Remove Ip,mac address, module name DECODEIP (strdecode); Toast. Maketext (connectwifiactivity. This,"Get the WiFi module name successfully!" "+modulename, Toast. Length_short). Show ();Break; Case Tool. Rec_server:byte[] DataServer = (byte[]) msg. obj; Convert decimal data to hexadecimal data String strserver= Tool. bytestohexstring (DataServer); If"2b 6f 6b 0d 0a 0d 0a". Equals (Strserver)) {Toast. Maketext (connectwifiactivity. This,"Set the server to success!" ", Toast. Length_short). Show (); }Break; Case Tool. Rec_ssid:byte[] datassid= (byte[]) msg. obj; Tool. bytestohexstring (DATASSID); Decodedata (DATASSID);Break; Case Tool. Rec_at:byte[] Dataid = (byte[]) msg. obj; Convert decimal data to hexadecimal data String strtempid= Tool. bytestohexstring (Dataid); Parse string Strdecodeid=tool after removing a space in hexadecimal. Decodehex (strtempid. replace (" ",""));Break; Case Tool. Rec_dhcp:byte[] Datadhcp = (byte[]) msg. obj; Convert decimal data to hexadecimal data String strdhcp= Tool. bytestohexstring (DATADHCP); If"2b 6f 6b 0d 0a 0d 0a". Equals (Strdhcp)) {Toast. Maketext (connectwifiactivity. This, "set the DHCP network parameters successfully!" ", Toast. Length_short). Show ();} break; default:byte[] data1 = (byte[]) msg. obj;//convert the decimal data into a hexadecimal data String strtemp1= Tool. Bytestohexstring (data1); Toast. Maketext (connectwifiactivity. This, strTemp1, toast. Length_short). Show (); break;}} };

Summarize

If you need to send instructions to the WiFi module, you need to use the above two thread classes, as well as a handler to process the return information. Just send the instructions that are not the same as the code above, as indicated above is the search for the WiFi module hex instructions. Regardless of whether the WiFi module is in AP mode or STA mode, the first step of communication is to search for the module, then obtain its IP and Mac, immediately reply to the +ok instruction, you can maintain the connection status.

Demo download

UDP Communication Send command demo

"Android Development-smart home series" (iv): UDP communication Send instructions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.