2017年5月21日 星期日

第二章:Android Socket設計

RD腦講解著
當設計完ESP8266MQTT後,由於需要告知ESP8266Station mode時,要連接到家中哪個AP,所以我們用Socket丟到ESP8266 AP mode,當AP mode收到設定的帳號及密碼後,ESP8266將會轉為Station mode 

你在繞口令嗎? PM腦說

總之就是用AndroidSocketESP8266! RD腦說
Android需要丟一個字串,包括:
1、家裡的AP帳號
2、家裡的AP密碼
3、這個燈座的名字,例如放在房間就叫room,廁所就叫bathroom
4、GPS位置


所以Android呈現出來會如下圖

surf house - 是我家放衝浪板的地方,哦不! 是我家放AP的地方
…..           - 就是AP的密碼
room        - 代表著我把這個燈座放在房間裡
點下Set Position就會出現GPS經緯度
點下 Set 代表要送SocketESP8266


主要程式碼如下:
public class APointSetting extends Activity implements OnClickListener {
    WifiManager mainWifiObj;
    WifiScanReceiver wifiReciever;
    ListView list;
    Spinner sp;
    String wifis[];
    Context mContext;
   
    EditText editTextMessage,editTextMessage1;
   
    GPSTracker gps;
   
     private static final String TAG = "Client";
    private Socket socket;
   public SeekBar seekBar;
    private static int SERVERPORT_MAIN = 0;
    private static String SERVER_MAIN = "";
    private String serverinputdata = null;
    private String serveroutputdata = null;
    public EditText et;
    private Handler mHandler;
    public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
       
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_point_setting);
        sp = (Spinner) findViewById(R.id.my_spinner1);
        mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiReciever = new WifiScanReceiver();
        mainWifiObj.startScan();
       
        SERVERPORT_MAIN = 5000;
        SERVER_MAIN = "192.168.4.1"; //esp8266
        //SERVER_MAIN = "192.168.1.1"; //ameba
        new Thread(new ClientThread()).start();
        mHandler = new Handler();
       
        final TextView TextViewMessage = (TextView)findViewById(R.id.editText2);
       
        final TextView TextViewMessage1 = (TextView)findViewById(R.id.editText3);
       
        editTextMessage = (EditText)findViewById(R.id.editText1);
        editTextMessage1 = (EditText)findViewById(R.id.editText0);
                 
        TextView skip,Setposition;

        skip = (TextView) findViewById(R.id.set);
        Setposition = (TextView) findViewById(R.id.setposition);
               
        Setposition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               
                // create class object
                gps = new GPSTracker(APointSetting.this);

                // check if GPS enabled    
                if(gps.canGetLocation()){
                 
                  double latitude = gps.getLatitude();
                  double longitude = gps.getLongitude();
                 
                 
                  CharSequence cs=String.valueOf(latitude);
                  CharSequence cs1=String.valueOf(longitude);
                  TextViewMessage.setText(cs);
                  TextViewMessage1.setText(cs1);
                   
                }else{
                  gps.showSettingsAlert();
                }
               
            }
        });
       
        skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               
             try {
                
                 PrintWriter out = new PrintWriter(new BufferedWriter(
                         new OutputStreamWriter(socket.getOutputStream())),
                         true);
//以下就是整段程式的重點阿!!! 不用擔心地球 Socket !
serveroutputdata = "\\"+(String) sp.getSelectedItem()+"\\"+editTextMessage.getText().toString()+"\\"+TextViewMessage.getText().toString()+"\\"+TextViewMessage1.getText().toString()+"\\"+editTextMessage1.getText().toString()+"\\"+"\r\n";
                 out.println(serveroutputdata);
//以上就是整段程式的重點阿!!! 不用擔心地球 Socket    !

             } catch (UnknownHostException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
             } catch (Exception e) {
                 e.printStackTrace();
             }
               
                TextView tv = (TextView) v;
                Toast.makeText(APointSetting.this, "Setting Success", Toast.LENGTH_SHORT).show();
               
                finish(); //terminated this activity
               
            }
        });
       
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {
           
            BufferedReader br;
           
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_MAIN);
                socket = new Socket(serverAddr, SERVERPORT_MAIN);
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               
                while (true) {
                    serverinputdata=br.readLine();
                    Log.i(TAG, "DATA:"+ serverinputdata);

                }
               
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onPause() {
        unregisterReceiver(wifiReciever);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(wifiReciever, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    class WifiScanReceiver extends BroadcastReceiver {
        @SuppressLint("UseValueOf")
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
            wifis = new String[wifiScanList.size()];
            for (int i = 0; i < wifiScanList.size(); i++) {
                wifis[i] = ((wifiScanList.get(i).SSID));
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(APointSetting.this, android.R.layout.simple_spinner_item, wifis);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sp.setAdapter(adapter);
        }
    }
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
    }
}

哦哦哦!太簡單啦! 可惡! 為什麼我不會寫程式!!! PM腦握著拳頭說

RD腦聳著肩說:不會上Coursera或台北E大線上學習,怪我囉?

( !這時候應該搭配HowFun來個業配免費線上學程式什麼的! )

本體:眼尖的讀者也許會發現被mark掉的這一行
//SERVER_MAIN = "192.168.1.1"; //ameba
沒錯,我們有試著使用Ameba,但發現一些尚未能解決的問題
就決定放著不理它,至於是什麼問題,就留待系列文章結束後再說明吧!

沒有留言:

張貼留言

FB設定搶先看的方式

設定搶先看的兩種方式 A1. 先到我家的日常粉絲團按下 …( 紅框處 ) A2. 按下追蹤中 ( 紅框處 ) A3. 按下搶先看 ( 紅框處 ) A4. 完成!!! 另一種方式 ...