タス デザイン グループ

Read Article

WiFiで他のデバイスと連携する

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fxos.androidtips41"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name="com.example.fxos.androidtips41.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textMyDeviceNameLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_device_name_label"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textMyDeviceName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_device_name_label"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id="@+id/buttonsLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/button_margin"
        android:layout_marginTop="@dimen/button_margin"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/buttonDiscoverPeer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="@string/button_discover_peer" />

        <Button
            android:id="@+id/buttonDisconnect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:onClick="onClick"
            android:text="@string/button_disconnect" />
    </LinearLayout>

    <fragment
        android:id="@+id/fragmentList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        class="com.example.fxos.androidtips41.DeviceListFragment"
        android:clickable="false" >
    </fragment>

</LinearLayout>

device_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textDiscoveredDeviceNameLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/discovered_device_name_label"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:drawSelectorOnTop="false" />

    <TextView
        android:id="@id/android:empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/no_data_label"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

values/dimens.xml

<resources>

    <dimen name="button_margin">10dp</dimen>

</resources>

values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Device Cooperation WiFi</string>
    <string name="button_ok">OK</string>
    <string name="button_cancel">Cancel</string>
    <string name="button_discover_peer">Discover Peers</string>
    <string name="button_disconnect">Disconnect</string>
    <string name="my_device_name_label">My Device Name:</string>
    <string name="no_data_label">No devices found.Push Discover Peers button.</string>
    <string name="discovered_device_name_label">Discovered Device Name:</string>
    <string name="title_discovery_setting_error">Setting Error</string>
    <string name="title_connect_confirm">Conncet confirm</string>
    <string name="message_discovery_initiated">Discovery Initiated.</string>
    <string name="message_discovery_failed">Discovery Failed. ReasonCode:</string>
    <string name="message_disconnect_failed">Disconnect Failed. ReasonCode:</string>
    <string name="message_discovery_setting_error">Enable P2P from system settings</string>
    <string name="message_connect_confirm">Do you connect to this device?</string>
    <string name="message_discovering">Discovering Peers</string>
    <string name="message_connect_failed">Connect failed. Retry.</string>
    <string name="message_send_message">Send message from %s</string>
    <string name="message_connecting_to">Connecting to :%s</string>
    <string name="message_aquistion_of_message_failed">Acquisition of message failed</string>

</resources>

MainActivity.java

package com.example.fxos.androidtips41;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends Activity implements ChannelListener, ConnectionInfoListener {
    private static final String ENCODE = "UTF-8";

    private static final int SOCKET_TIMEOUT = 5000;

    private WifiP2pManager mManager;

    private boolean isWifiP2pEnabled = false;

    private Context mContext;

    Channel mChannel;

    BroadcastReceiver mReceiver;

    private boolean isDiscovering = false;

    private TextView mTextMyDeviceName;

    private Socket mClientSocket;

    private ServerSocket mServerSocket;

    IntentFilter mIntentFilter;

    /**
     * @param isWifiP2pEnabled the isWifiP2pEnabled to set
     */
    public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
        this.isWifiP2pEnabled = isWifiP2pEnabled;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        mManager = (WifiP2pManager)getSystemService(WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);
        mReceiver = new WiFiDirectBroadcastReceiver(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);

        mTextMyDeviceName = (TextView)findViewById(R.id.textMyDeviceName);

        // clear previous setting
        mManager.removeGroup(mChannel, new ActionListener() {
            @Override
            public void onFailure(int reasonCode) {
            }

            @Override
            public void onSuccess() {
            }
        });

    }

    /* register the broadcast receiver with the intent values to be matched */
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }

    /* unregister the broadcast receiver */
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    public void setMyDeviceInfo(WifiP2pDevice device) {
        mTextMyDeviceName.setText(device.deviceName);
        mTextMyDeviceName.setTag(device);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonDiscoverPeer:
                if (!isWifiP2pEnabled) {
                    // show error dialog
                    AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
                    dialog.setTitle(R.string.title_discovery_setting_error)
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setMessage(R.string.message_discovery_setting_error)
                            .setPositiveButton(R.string.button_ok,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            // move wireless setting
                                            startActivity(new Intent(
                                                    Settings.ACTION_WIRELESS_SETTINGS));
                                        }
                                    }).show();

                    return;
                }
                // show progress
                ProgressUtil.show(mContext, null, getString(R.string.message_discovering), true,
                        true);
                setDiscovering(true);

                mManager.discoverPeers(mChannel, new ActionListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(mContext, R.string.message_discovery_initiated,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int reasonCode) {
                        Toast.makeText(mContext,
                                getString(R.string.message_discovery_failed) + reasonCode,
                                Toast.LENGTH_LONG).show();
                    }
                });
                break;
            case R.id.buttonDisconnect:
                mManager.removeGroup(mChannel, new ActionListener() {

                    @Override
                    public void onFailure(int reasonCode) {
                        Toast.makeText(mContext,
                                getString(R.string.message_disconnect_failed) + reasonCode,
                                Toast.LENGTH_LONG).show();

                    }

                    @Override
                    public void onSuccess() {
                        setButtonsState(false);
                    }

                });
                break;
        }
    }

    public boolean isDiscovering() {
        return isDiscovering;
    }

    public void setDiscovering(boolean flag) {
        isDiscovering = flag;
    }

    public void setButtonsState(boolean isConnected) {
        if (isConnected) {
            findViewById(R.id.buttonDiscoverPeer).setEnabled(false);
            findViewById(R.id.buttonDisconnect).setEnabled(true);
        } else {
            findViewById(R.id.buttonDiscoverPeer).setEnabled(true);
            findViewById(R.id.buttonDisconnect).setEnabled(false);
        }
    }

    public void connect(WifiP2pConfig config) {
        mManager.connect(mChannel, config, new ActionListener() {

            @Override
            public void onSuccess() {
                // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
            }

            @Override
            public void onFailure(int reason) {
                Toast.makeText(mContext, R.string.message_connect_failed, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

    @Override
    public void onChannelDisconnected() {
    }

    @Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
        // hide progress
        ProgressUtil.hideProgress();

        // act as server
        if (info.groupFormed && info.isGroupOwner) {
            ServerTask serverTask = new ServerTask();
            serverTask.execute();
            // act as client
        } else if (info.groupFormed) {
            ClientTask clientTask = new ClientTask();
            clientTask.execute(info.groupOwnerAddress.getHostAddress());
        }
    }

    public void resetData() {
        setButtonsState(false);
        DeviceListFragment fragmentList = (DeviceListFragment)getFragmentManager()
                .findFragmentById(R.id.fragmentList);
        if (fragmentList != null) {
            fragmentList.clearPeers();
        }
    }

    class ClientTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String host = params[0];
            mClientSocket = new Socket();
            int port = 8988;

            try {
                // send message to server
                mClientSocket.bind(null);
                mClientSocket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);

                OutputStreamWriter osw = new OutputStreamWriter(mClientSocket.getOutputStream());
                osw.write(getString(R.string.message_send_message, mTextMyDeviceName.getText()));
                osw.flush();
                osw.close();
                mClientSocket.close();

                // get server message
                mClientSocket = new Socket();
                mClientSocket.bind(null);
                mClientSocket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
                // Thread.sleep(3000);
                //
                InputStream is = mClientSocket.getInputStream();
                int size = 0;
                byte[] buffer = new byte[2000];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((size = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, size);
                }
                is.close();
                String serverMessage = bos.toString(ENCODE);

                return serverMessage;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (mClientSocket != null) {
                    if (mClientSocket.isConnected()) {
                        try {
                            mClientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String message) {
            if (message == null) {
                Toast.makeText(MainActivity.this, R.string.message_aquistion_of_message_failed,
                        Toast.LENGTH_LONG).show();
            } else {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setMessage(message)
                        .setPositiveButton(R.string.button_ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).show();
            }
        }

    }

    class ServerTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                // get client message
                mServerSocket = new ServerSocket(8988);
                Socket client;
                client = mServerSocket.accept();
                InputStream is = client.getInputStream();
                int size = 0;
                byte[] buffer = new byte[2000];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((size = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, size);
                }
                is.close();
                client.close();

                String clientMessage = bos.toString(ENCODE);

                // send message to client
                client = mServerSocket.accept();
                OutputStreamWriter osw = new OutputStreamWriter(client.getOutputStream());
                osw.write(getString(R.string.message_send_message, mTextMyDeviceName.getText()));
                osw.close();

                client.close();

                mServerSocket.close();

                return clientMessage;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String message) {
            if (message == null) {
                Toast.makeText(MainActivity.this, R.string.message_aquistion_of_message_failed,
                        Toast.LENGTH_LONG).show();
            } else {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setMessage(message)
                        .setPositiveButton(R.string.button_ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).show();
            }
        }

    }
}

DeviceListFragment.java

package com.example.fxos.androidtips41;

import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class DeviceListFragment extends ListFragment implements PeerListListener {
    private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();

    View mContentView = null;

    private WiFiPeerListAdapter mWiFiPeerListAdapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWiFiPeerListAdapter = new WiFiPeerListAdapter(getActivity(),
                android.R.layout.simple_list_item_1, peers);
        this.setListAdapter(mWiFiPeerListAdapter);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.device_list, null);
        return mContentView;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        final WifiP2pDevice device = (WifiP2pDevice)getListAdapter().getItem(position);

        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.title_connect_confirm)
                .setMessage(R.string.message_connect_confirm)
                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // connect device
                        WifiP2pConfig config = new WifiP2pConfig();
                        config.deviceAddress = device.deviceAddress;
                        config.wps.setup = WpsInfo.PBC;

                        ProgressUtil.show(getActivity(), null,
                                getString(R.string.message_connecting_to, device.deviceAddress),
                                true, true);
                        ((MainActivity)getActivity()).connect(config);

                    }
                }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {
        peers.clear();
        peers.addAll(peerList.getDeviceList());
        mWiFiPeerListAdapter.notifyDataSetChanged();
        if (peers.size() == 0) {
            return;
        }
    }

    private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {

        private int textViewResourceId;

        private List<WifiP2pDevice> items;

        /**
         * @param context
         * @param textViewResourceId
         * @param objects
         */
        public WiFiPeerListAdapter(Context context, int textViewResourceId,
                List<WifiP2pDevice> objects) {
            super(context, textViewResourceId, objects);
            this.textViewResourceId = textViewResourceId;
            items = objects;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(textViewResourceId, null);
            }
            WifiP2pDevice device = items.get(position);
            if (device != null) {
                TextView top = (TextView)v.findViewById(android.R.id.text1);
                if (top != null) {
                    top.setText(device.deviceName);
                }
            }

            return v;

        }
    }

    public void clearPeers() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                peers.clear();
                mWiFiPeerListAdapter.notifyDataSetChanged();
            }
        }, 100);
    }

}

ProgressUtil.java

package com.example.fxos.androidtips41;

import android.app.ProgressDialog;
import android.content.Context;

public class ProgressUtil {
    private static ProgressDialog mProgressDialog = null;

    // show progress dialog
    public static void show(Context context, CharSequence title, CharSequence message,
            boolean indeterminate, boolean cancelable) {
        // hide bofore show
        hideProgress();

        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setTitle(title);
        mProgressDialog.setMessage(message);
        mProgressDialog.setIndeterminate(indeterminate);
        mProgressDialog.setCancelable(cancelable);
        mProgressDialog.show();
    }

    // hide progress dialog
    public static void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

}

WiFiDirectBroadcastReceiver.java

package com.example.fxos.androidtips41;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;

/**
 * A BroadcastReceiver that notifies of important Wi-Fi p2p events.
 */
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
    private WifiP2pManager mManager;

    private Channel mChannel;

    private MainActivity mActivity;

    public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
            MainActivity activity) {
        super();
        this.mManager = manager;
        this.mChannel = channel;
        this.mActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
            // Check to see if Wi-Fi is enabled and notify appropriate activity
            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                // Wifi P2P is enabled
                mActivity.setIsWifiP2pEnabled(true);
            } else {
                // Wi-Fi P2P is not enabled
                mActivity.setIsWifiP2pEnabled(false);
            }
        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
            // Call WifiP2pManager.requestPeers() to get a list of current peers
            if (mManager != null) {
                if (mActivity.isDiscovering()) {
                    ProgressUtil.hideProgress();
                    mActivity.setDiscovering(false);
                }
                mManager.requestPeers(mChannel, (PeerListListener)mActivity.getFragmentManager()
                        .findFragmentById(R.id.fragmentList));
            }
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
            // Respond to new connection or disconnections
            if (mManager == null) {
                return;
            }

            NetworkInfo networkInfo = (NetworkInfo)intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

            if (networkInfo.isConnected()) {
                mActivity.setButtonsState(true);

                mManager.requestConnectionInfo(mChannel, mActivity);
            } else {
                // It's a disconnect
                mActivity.resetData();
            }
        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
            WifiP2pDevice device = (WifiP2pDevice)intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
            mActivity.setMyDeviceInfo(device);
        }
    }

}

manifest.webapp

{
  "name": "device_cooperation_WiFi",
  "description": "41_device_cooperation_WiFi",
  "launch_path": "/index.html",
  "type": "certified",
  "icons": {
    "64": "/img/icon/app-icon64.png",
    "128": "/img/icon/app-icon128.png"
  },
  "developer": {
    "name": "TAS Design Group",
    "url": "http://tasdg.co.jp/"
  },
  "default_locale": "ja",
  "permissions": {
    "tcp-socket" : {},
    "wifi-manage": {}
  }
}

CSS (style/style.css)

@charset "UTF-8";

html {
  height: 100%;
  font-size: 62.5%;
}

body {
  margin: 0;
  height: 100%;
  display: block;
  overflow: hidden;
  font-family: sans-serif;
}

index.html

<!DOCTYPE html>
<html lang="ja" dir="ltr">
<head>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
  <meta charset="utf-8">
  <title>Connection with another device on TCPSocket.</title>
  <link rel="stylesheet" href="style/style.css" type="text/css">
  <script src="js/main.js" type="text/javascript"></script>
</head>
<body>
  <section>
    <header>
      <h1>Connection with another device on TCPSocket.</h1>
    </header>
    <p class='exp'>This application use two firefoxos devices. One device is sensor server. it gets ambient light value. the other device is display client. It get sensor value from sensor server every 5 second, and if recieved value is less than 10 background color set green. more than 10 background color set red.</p>
    <p>
      <label><input id="input_s" type="radio" name="type" value="sencer" checked>Sencer(Server)</label>
    </p>
    <p>
      <label><input id="input_d" type="radio" name="type" value="display">Display(client)</label>
    </p>
    <p>
      ServerIPAddress:&nbsp;<input id="ipadr" type="text" value="192.168.1.105">
    </p>
    <p>
      <button id='btn'>START</button>
    </p>
    <div id="adr"></div>
    <div id="status"></div>
    <div id="sensor"></div>
    <div id="recieve"></div>
  </section>
</body>
</html>

main.js

window.addEventListener('load', function() {

  var mode = 'MODE_SERVER';
  var service = server;

  var dom = {};
  var ids = ['input_s', 'input_d', 'ipadr', 'adr', 'btn'];
  ids.forEach(function createElementRef(name) {
    dom[name] = document.getElementById(name);
  });

  dom.input_s.onchange = function() {
    mode = 'MODE_SERVER';
    service = server;
    dom.ipadr.disabled = true;
  };
  dom.input_d.onchange = function() {
    mode = 'MODE_CLIENT';
    service = client;
    dom.ipadr.disabled = false;
  };

  stat.init();
  sencer.init();
  dom.adr.innerHTML = 'CurrentIP:' + getIPAddress();

  var toggle = true;
  dom.btn.onclick = function() {
    if (toggle) {
      service.start();
      stat.put('Service Start');
      dom.btn.textContent = 'STOP';
    } else {
      service.stop();
      stat.put('Service STOP');
      dom.btn.textContent = 'START';
    }
    toggle = !toggle;
  };

  function getIPAddress() {
    var WifiManager = navigator.mozWifiManager;
    if (!WifiManager) {
      console.log('wifi NotSupport');
      return 0;
    }
    return WifiManager.connectionInformation.ipAddress;
  }
});

//---------------------
var stat = {
  message: 0,
  init: function() {
    this.message = document.getElementById('status');
    this.put('Service STOP');
  },
  put: function(msg) {
    this.message.innerHTML = msg;
  }
};

//---------------------
var sencer = {
  light: 0,

  init: function() {
    window.addEventListener('devicelight', (e) => {
      this.light = e.value;
      var msg = document.getElementById('sensor');
      msg.innerHTML = 'light: ' + e.value;
    });
  },
  getCurrentValue: function() {
    return this.light;
  }
};
//---------------------
var server = {
  svrsoc: 0,
  start: function() {
    var tcpsocket = navigator.mozTCPSocket;
    this.svrsoc = tcpsocket.listen(8080);
    document.bgColor = '#FFFFFF';
    this.svrsoc.onconnect = function(e) {
      stat.put('connect');
      e.ondata = function(c) {
        console.log(c.data);
        e.send('light:' + sencer.getCurrentValue());
        e.close();
      };
      e.onclose = function() {
        stat.put('disconnect');
      };
    };

    this.svrsoc.onerror = function() {
      console.log('sv_onerror');
    };
  },

  stop: function() {
    if(!!this.svrsoc) this.svrsoc.close();
  }
};
//---------------------
var client = {
  con: 0,
  start: function() {
    var tcpsocket = navigator.mozTCPSocket;
    setInterval(function() {
      var ipaddress = document.getElementById('ipadr').value;
      this.con = tcpsocket.open(ipaddress, 8080);
      con.onopen = function() {
        console.log('socket open');
        this.con.send('client to server message');
      };
      con.ondata = function(e) {
        console.log(e.data);
        var msg = document.getElementById('recieve');
        msg.innerHTML = e.data;
        var res = e.data.split(':');
        var value = Number(res[1]);
        if (value > 10) document.bgColor = '#FF0000';
        else document.bgColor = '#00FF00';
      };
    }, 5000);
  },

  stop: function() {
    if(!!this.con) this.con.close();
  }
};
Return Top