WIFI android控制加湿器助手(附详解+源码)
来源:互联网 发布:昂立新课程网络教育 编辑:程序博客网 时间:2024/03/29 17:01
因为一大堆同学大创结不了题,求我帮忙,所以这两天一直怼app控制硬件.今天是wifi.
思路还是比较简单的.无非建立通讯流,然后交换信息,通讯方法都差不多.
界面
大体思路
如上图
一共只有3个类,一个通讯类,一个活动,一个广播.
WIFI通信
通讯类思路是通过 new Socket("192.168.4.1",5000);
建立通讯,两个形参,第一个是host,第二个是端口.
然后output = new PrintStream(socket.getOutputStream(),true,"gbk");
来建立输入流. new BufferedInputStream(socket.getInputStream())
可以获得输出流,接受信息
通过output.print()就可以发送信息,.
UI
UI主要还是通过 Handler 和 localBroadCast进行交互.下次用 AsyncTask来玩吧.
曲线图还是使用的框架.
源码 :https://github.com/QQ951127336/Wifi_humidifier_controuler
贴代码了
MainActivity
package com.tree.max.humidifier;import android.content.BroadcastReceiver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.graphics.Color;import android.graphics.PointF;import android.net.wifi.p2p.WifiP2pManager;import android.os.Handler;import android.os.Message;import android.support.v4.content.LocalBroadcastManager;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.ToggleButton;import com.idtk.smallchart.chart.LineChart;import com.idtk.smallchart.data.LineData;import com.idtk.smallchart.interfaces.iData.ILineData;import java.util.ArrayList;public class MainActivity extends AppCompatActivity { final int HUMIDIFIER = 1;//用于handler判断 //绘图曲线图 LineChart lineChart; LineData lineData; ArrayList<ILineData> dataList; ArrayList<PointF> linePointList ; PointF pointF; //坐标 int[] x = new int[12]; int[] y = new int[12]; //本地广播 控制UI LocalReceiver localReceiver; //监听WIFI状态 WifiP2pManager mManager; WifiP2pManager.Channel mChannel; BroadcastReceiver mReceiver; IntentFilter mIntentFilter; //布局控件 Button connectButton; Button autoButton; Button handButton; TextView current_humidifier; TextView aim_humidifier; EditText input_humidifier ; ToggleButton stateButton ; //通讯线程 AcceptThread acceptThread; //接受到的信息 static String number = "" ; //判断是否已连接 private boolean isConnecting= false; //显示数据 ,更新曲线图 final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case HUMIDIFIER: current_humidifier.setText("当前湿度:"+number); lineChart.invalidate(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); acceptThread = new AcceptThread(MainActivity.this); init();//初始化 MainOnClickListener mainOnClickListener = new MainOnClickListener(); connectButton.setOnClickListener(mainOnClickListener); autoButton.setOnClickListener(mainOnClickListener); handButton.setOnClickListener(mainOnClickListener); for (int i = 1;i<=9;i++) { y[i-1] = y[i]; } y[0] = 100; y[1] = 0; linePointList.clear(); for (int i = 0 ; i<=10;i++) { linePointList.add(new PointF(x[i],y[i])); } lineData.setValue(linePointList); dataList.clear(); dataList.add(lineData); lineData.setColor(Color.CYAN); lineData.setPaintWidth(1); lineData.setTextSize(4); lineChart.isAnimated = false; lineChart.setDataList(dataList); } @Override protected void onResume() { super.onResume(); registerReceiver(mReceiver,mIntentFilter);//注册广播 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("IVE_LOCAL_BROAD_RECECHANGED");//本地UI线程广播 localReceiver= new LocalReceiver(); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.registerReceiver(localReceiver,intentFilter); } @Override protected void onPause(){ super.onPause(); unregisterReceiver(mReceiver); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(localReceiver); } public void init() { lineChart = (LineChart)findViewById(R.id.times_data_view); lineData = new LineData(); linePointList = new ArrayList<>(); dataList = new ArrayList<>(); for (int j= 0; j<12;j++) { x[j] = (j-2); } x[1] = 0; x[0] = 0; x[2] = 0; for (int j =2;j<12;j++) { x[j] +=0.2*(j-1); } for (int j =3 ;j<12;j++) { x[j] += (j-2)*0.1; } connectButton = (Button)findViewById(R.id.connectButton); autoButton = (Button)findViewById(R.id.autoButton); handButton = (Button)findViewById(R.id.handButton); //监听wifi状态 mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mReceiver = new WifiBroadcastReceiver(mManager, mChannel, this); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); aim_humidifier = (TextView)findViewById(R.id.aim_humidifier); current_humidifier = (TextView)findViewById(R.id.current_humidifier); stateButton = (ToggleButton)findViewById(R.id.stateButton); input_humidifier = new EditText(this); } class MainOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.connectButton: if (isConnecting) { isConnecting = false; if (acceptThread.isAlive()) acceptThread.interrupt(); Log.e("Main","connectButton is touched"); connectButton.setText("连接仪器"); } else { isConnecting = true; connectButton.setText("断开连接"); if (acceptThread.isAlive()) acceptThread.interrupt(); acceptThread.start(); } break; case R.id.autoButton: aim_humidifier.setText("设置湿度:60"); if (acceptThread.isAlive()) acceptThread.interrupt(); acceptThread = new AcceptThread(60); acceptThread.start(); break; case R.id.handButton: new AlertDialog.Builder(MainActivity.this).setTitle("设置湿度") .setView(input_humidifier = new EditText(MainActivity.this)).setPositiveButton("确定",onClickListener) .setNegativeButton("取消",null) .show(); break; case R.id.stateButton: if (stateButton.isChecked()) { if (acceptThread.isAlive()) { acceptThread.interrupt(); } acceptThread = new AcceptThread("@CH1",1); acceptThread.start(); } else { if (acceptThread.isAlive()) { acceptThread.interrupt(); } acceptThread = new AcceptThread("@CH0",1); acceptThread.start(); } break; } } } DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String input =input_humidifier.getText().toString(); aim_humidifier.setText("设置湿度:"+input); if (acceptThread.isAlive()) acceptThread.interrupt(); acceptThread = new AcceptThread(Integer.valueOf(input)); acceptThread.start(); } }; private class LocalReceiver extends BroadcastReceiver{ Bundle bundle; @Override public void onReceive(Context context, Intent intent) { switch(intent.getAction()) { case "IVE_LOCAL_BROAD_RECECHANGED": Message msg = new Message(); bundle = intent.getExtras(); number = bundle.getString("humidifier"); msg.what = HUMIDIFIER; for (int i = 3;i<=10;i++) { y[i-1] = y[i]; } y[10] = Integer.valueOf(number); linePointList.clear(); for (int i = 0 ; i<11;i++) { pointF = new PointF(x[i],y[i]); linePointList.add(pointF); } handler.sendMessage(msg); break; } } }}
AcceptThread
package com.tree.max.humidifier;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Message;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.io.PrintWriter;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import java.security.PrivateKey;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by max on 17-5-20. */public class AcceptThread extends Thread { private PrintStream output; private BufferedInputStream bufferedInputStream; private Socket socket; Bundle bundle; LocalBroadcastManager localBroadcastManager; Intent intent = new Intent("IVE_LOCAL_BROAD_RECECHANGED"); String patter = "(\\d+)"; Pattern r = Pattern.compile(patter); Matcher matcher; int relay = 0; String relay_state = ""; int aim_humidifier = 0; int humidifier_setting = 0; public AcceptThread(Context context) { localBroadcastManager = LocalBroadcastManager.getInstance(context); bundle = new Bundle(); } public AcceptThread(String s, int i) { relay = i; relay_state =s ; } public AcceptThread(int i) { aim_humidifier = i; humidifier_setting = 1; } @Override public void run() { initClientSocket(); String receive; while (true) { byte[] data = receiveData(); if (data.length>1) { receive = new String(data); matcher =r.matcher(receive); if (matcher.find()) receive = matcher.group(1); else receive = "-1"; if (receive.startsWith("0")) receive = receive.substring(1); bundle = new Bundle(); bundle.putString("humidifier",receive); intent.putExtras(bundle); localBroadcastManager.sendBroadcast(intent); } } } public void initClientSocket(){ try{ socket = new Socket("192.168.4.1",5000); output = new PrintStream(socket.getOutputStream(),true,"gbk"); } catch (UnknownHostException e) { Log.e("init","host wrong"); e.printStackTrace(); } catch (IOException e) { Log.e("init","IO"); e.printStackTrace(); } if (relay==1) { sendMessage(); relay = 0; } if (humidifier_setting == 1) { output.print(aim_humidifier); humidifier_setting = 0; } } private void sendMessage() { output.print(relay_state); } public byte[] receiveData(){ if (socket == null || socket.isClosed()){ try{ socket = new Socket("192.168.4.1",5000); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } byte[] buffer =new byte[254]; int length; if (socket.isConnected()) { try{ bufferedInputStream = new BufferedInputStream(socket.getInputStream()); length = bufferedInputStream.read(buffer); } catch (IOException e) { e.printStackTrace(); } } else { buffer = new byte[1]; } return buffer; }}
WifiBroad
package com.tree.max.humidifier;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.wifi.p2p.WifiP2pManager;import android.util.Log;import android.widget.Toast;/** * Created by max on 17-5-20. */public class WifiBroadcastReceiver extends BroadcastReceiver { private WifiP2pManager mManager; private WifiP2pManager.Channel mChannel; private MainActivity mainActivity; public WifiBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel channel,MainActivity mainActivity) { this.mainActivity = mainActivity; this.mChannel = channel; this.mManager = mManager; } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { Toast.makeText(mainActivity,"WIFI已打开",Toast.LENGTH_LONG).show(); } else { Toast.makeText(mainActivity,"WIFI已关闭",Toast.LENGTH_LONG).show(); } } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { // Call WifiP2pManager.requestPeers() to get a list of current peers } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { // Respond to new connection or disconnections } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { // Respond to this device's wifi state changing } }}
阅读全文
0 0
- WIFI android控制加湿器助手(附详解+源码)
- Android CursorLoader实例详解(附源码)
- Android 生命周期详解【附demo源码】
- android Wifi 控制
- android控制wifi状态
- Android 中 控制 wifi
- android控制wifi状态
- Android控制wifi开关
- Android wifi控制
- android 瀑布流的实现详解,附源码
- android SQLite数据库用法图文详解(附源码)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- Android中Canvas绘图基础详解(附源码下载)
- 二维码Zxing的使用
- vmware workstation 12 密钥
- 链栈的定义及相关操作
- CSS变形transform(2d)
- 理解Android Framework
- WIFI android控制加湿器助手(附详解+源码)
- DOM的高级应用-------关于Ul中的 li 的排序
- GitHub之URL方式建立仓库
- 动态查找之-二叉排序树
- Java线程并发中的锁——ReentrantLock(重入锁)原理详解
- 最短路径Dijkstra算法
- C语言数据结构——矩阵的加减乘除
- 深入理解CSS变形transform(3d)
- windows同时安装多个Python版本