aboutsummaryrefslogtreecommitdiffstats
path: root/ccnxandroidmetis/MetisControl/src/main/java/com/metis/ccnx/ccnxsdk/metiscontrol/MetisStatusFragment.java
blob: 370a53b45fca6139d36e4ea177dc0ffbcdfa9f07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 * Copyright (c) 2017 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.metis.ccnx.ccnxsdk.metiscontrol;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.metis.ccnx.ccnxsupportlibrary.Metis;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.List;


public class MetisStatusFragment extends Fragment implements IMetisNamedFragment {

    private static final String ARG_PAGER_INDEX = "metisstatus_pager_number";
    private static final String TAG = "CCNXMetis SF";

    // TODO: Rename and change types of parameters
    private int mPagerIndex;

    private Switch mSwitchMetisOnOff = null;
    private Spinner mSpinnerLogLevel = null;
    private Switch mSwitchContentStoreOnOff = null;
    private TextView mTVNumInterests = null;
    private TextView mTVNumContentObjects = null;
    private TextView mTVNumInterestReturns = null;
    private TextView mTVNumControlMessages = null;
    private TextView mTVNumPITEntries = null;
    private TextView mPathTextView = null;

    // Stats counters, updated by background task.
    private long mNumInterests = 0;
    private long mNumCOs = 0;
    private long mNumInterestReturns = 0;
    private long mNumControl = 0;
    private long mNumPITENtries = 0;

    private boolean mIsStatsQueryRunning = false;


    //private PortalFactory mPortalFactory = null;

    private OnFragmentVisibleListener mListener;


    /**
     * Create a Handler and a Runnable to be called every few seconds to query
     * Metis (when running) for stats.
     */
    private Handler mStatusUpdaterHandler = new Handler();
    private Runnable mStatusUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            // This runs on the main thread, so start an AsyncTask
            // Repeat this the same runnable code block again another few seconds
            //new GetStatusTask(null).execute(mPortalFactory);
            //if (mIsStatsQueryRunning) {
                //mStatusUpdaterHandler.postDelayed(mStatusUpdateRunnable, 2 * 1000);
            //}
        }
    };


    public MetisStatusFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment MetisStatusFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MetisStatusFragment newInstance(int pagerIndex) {
        MetisStatusFragment fragment = new MetisStatusFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGER_INDEX, pagerIndex);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onStart() {
        Metis metis = Metis.getInstance();
        mSwitchMetisOnOff.setChecked(metis.isRunning());
        super.onStart();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPagerIndex = getArguments().getInt(ARG_PAGER_INDEX);
        }


        Log.d(TAG, "Creating new PortalFactory");
        //Identity identity = CCNxUtils.createCCNxIdentity(getContext(),
        //        "password", "ccnxsdkdemo", 1024, 30);
        //mPortalFactory = new PortalFactory(identity);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_metis_status, container, false);

        mSwitchMetisOnOff = (Switch) view.findViewById(R.id.switchMetisOnOff);
        mSwitchContentStoreOnOff = (Switch) view.findViewById(R.id.switchMetisContentStoreOnOff);
        mSpinnerLogLevel = (Spinner) view.findViewById(R.id.spinnerMetisLoggingLevel);
        mPathTextView = (TextView) view.findViewById(R.id.pathText) ;

        mSpinnerLogLevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String loggingLevel = mSpinnerLogLevel.getSelectedItem().toString();
                updateMetisLoggingLevel(loggingLevel);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mSwitchMetisOnOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    startMetis();
                    //mSpinnerLogLevel.setEnabled(true);
                    //Log.d(TAG, "################# Start periodic query for stats");
                    //if (!mIsStatsQueryRunning) {
                    //    mStatusUpdaterHandler.postDelayed(mStatusUpdateRunnable, 500);
                     //   mIsStatsQueryRunning = true;
                     //   String loggingLevel = mSpinnerLogLevel.getSelectedItem().toString();
                     //   if (!loggingLevel.equalsIgnoreCase("off")) {
                     //       updateMetisLoggingLevel(loggingLevel);
                     //   }
                    //}
                } else {
                    Log.d(TAG, "################# Stop periodic query for stats");
                    //mStatusUpdaterHandler.removeCallbacks(mStatusUpdateRunnable);
                    //mIsStatsQueryRunning = false;
                    stopMetis();
                    //mSpinnerLogLevel.setEnabled(false);
                    //mSpinnerLogLevel.setSelection(0);
                }
            }
        });

        mTVNumInterests = (TextView) view.findViewById(R.id.tvStatsNumInterests);
        mTVNumContentObjects = (TextView) view.findViewById(R.id.tvStatsNumContentObjects);
        mTVNumInterestReturns = (TextView) view.findViewById(R.id.tvStatsNumInterestReturns);
        mTVNumControlMessages = (TextView) view.findViewById(R.id.tvStatsNumControl);
        mTVNumPITEntries = (TextView) view.findViewById(R.id.tvStatsPITSize);

        mTVNumInterests.setText(String.valueOf(mNumInterests));
        mTVNumContentObjects.setText(String.valueOf(mNumCOs));
        mTVNumControlMessages.setText(String.valueOf(mNumControl));
        mTVNumInterestReturns.setText(String.valueOf(mNumInterestReturns));
        mTVNumPITEntries.setText("");

        return view;
    }

    private void startMetis() {
        mPathTextView.setEnabled(false);
        Metis metis = Metis.getInstance();
        if (!metis.isRunning()) {
            Intent intent = new Intent(getActivity(), MetisService.class);
            intent.putExtra("path", mPathTextView.getText());
            getActivity().startService(intent);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    createExternalListeners();
                }
            }, 1000);
        }
    }

    private void stopMetis() {
        mPathTextView.setEnabled(true);
        Intent intent = new Intent(getActivity(), MetisService.class);

        getActivity().stopService(intent);

    }

    private void updateMetisLoggingLevel(String loggingLevel) {
        /*Metis metis = Metis.getInstance();
        if (metis.isRunning()) {
            // Send an Interest control message to Metis with the new logging level.
            String commandURI = MetisConstants.CCNxNameMetisCommand_Set + "/" + MetisConstants.MetisCommand_LogLevel + "/" + loggingLevel;
            Name name = new Name(commandURI);
            SendInterestTask task = new SendInterestTask(name, null, new SendInterestTask.OnInterestSentListener() {
                @Override
                public void onInterestSent(Message message) {
                    if (message instanceof ContentObject) {

                        String responseString = new String(((ContentObject) message).payload());
                        Snackbar snackbar = Snackbar
                                .make(mSwitchMetisOnOff, responseString, Snackbar.LENGTH_SHORT);

                        snackbar.show();
                    } else {
                        Log.d(TAG, "Unexpected non-Content response from sent Interest");
                    }
                }
            });

            task.execute(mPortalFactory);
        }*/
    }

    private void createExternalListeners() {

        /*Metis metis = Metis.getInstance();

        if (metis.isRunning()) {

            List<InetAddress> ipAddresses = CCNxUtils.getLocalIpAddress();

            for (InetAddress addr : ipAddresses) {

                // For the moment, just listen on the IPV4 addresses. The V6 addresses should work,
                // but it's not yet tested.

                if (addr instanceof Inet4Address) {

                    String ipAddress = addr.getHostAddress();

                    Log.d(TAG, "Adding external listener on: " + ipAddress);

                    String linkURI = "tcp://" + ipAddress + ":" + MetisConstants.MetisDefaultListenerPort + "/listener";

                    Name name = new Name(MetisConstants.CCNxNameMetisCommand_LinkConnect);

                    SendInterestTask task = new SendInterestTask(name, linkURI.getBytes(), new SendInterestTask.OnInterestSentListener() {
                        @Override
                        public void onInterestSent(Message message) {
                            if (message instanceof ContentObject) {

                                String responseString = new String(((ContentObject) message).payload());
                                Snackbar snackbar = Snackbar
                                        .make(mSwitchMetisOnOff, responseString, Snackbar.LENGTH_SHORT);

                                snackbar.show();
                            } else {
                                Log.d(TAG, "Unexpected non-Content response from sent Interest");
                            }
                        }
                    });

                    task.execute(mPortalFactory);
                }
            }
        }*/
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentVisibleListener) {
            mListener = (OnFragmentVisibleListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Metis metis = Metis.getInstance();

        if (isVisibleToUser) {
            mListener.onFragmentVisible(this);

            if (metis.isRunning()) {
                // Begin updating stats.
                if (!mIsStatsQueryRunning) {
                    mStatusUpdaterHandler.postDelayed(mStatusUpdateRunnable, 100);
                    mIsStatsQueryRunning = true;
                }
            }
        } else {
            mStatusUpdaterHandler.removeCallbacks(mStatusUpdateRunnable);
            mIsStatsQueryRunning = false;
        }
    }

    @Override
    public void onDetach() {
        mStatusUpdaterHandler.removeCallbacks(mStatusUpdateRunnable);
        mIsStatsQueryRunning = false;
        super.onDetach();
        mListener = null;
    }

    @Override
    public String getFragmentName() {
        return "Status";
    }

    public interface OnFragmentVisibleListener {
        // TODO: Update argument type and name
        void onFragmentVisible(Fragment which);
    }

    /*private class GetStatusTask extends AsyncTask<PortalFactory, String, Integer> {

        private boolean mSuccess = false;
        private PortalFactory mPortalFactory = null;


        public GetStatusTask(String unused) {
        }

        @Override
        protected Integer doInBackground(PortalFactory... args) {
            Thread.currentThread().setName("GetStatusTask-Async");

            mPortalFactory = args[0];
            try {
                Name controlName = new Name(MetisConstants.CCNxNameMetisCommand_Stats);

                Interest interest = new Interest(controlName);

                try {
                    Portal portal = mPortalFactory.getPortal();

                    portal.send(interest, 0L);

                    Message m = portal.receive(0L);

                    if (m instanceof ContentObject) {
                        mSuccess = true;
                        ContentObject co = (ContentObject) m;
                        byte[] payload = co.payload();

                        if (payload != null) {
                            String jsonString = new String(payload, Charset.defaultCharset());
                            //Log.d(TAG, "Received: XX " + jsonString + " XX");
                            try {
                                JSONObject jo = new JSONObject(jsonString);
                                //Log.d(TAG, "JSON2: " + jo.toString(2));

                                mNumInterests = jo.getLong("numProcessedInterests");
                                mNumCOs = jo.getLong("numProcessedContentObjects");
                                mNumControl = jo.getLong("numProcessedControlMessages");
                                mNumInterestReturns = jo.getLong("numProcessedInterestReturns");
                            } catch (JSONException ex) {
                                Log.e(TAG, "Could not parse returned JSON: " + ex.getMessage());
                            }
                        }
                    }
                    portal.close();
                } catch (Portal.CommunicationsError ex) {
                    Log.e(TAG, "Error sending AddLink command: " + ex.getMessage());
                }
            } catch (Exception ex) {
                Log.e(TAG, "Error adding link: " + ex.getMessage());
            }

            return 1;
        }

        @Override
        protected void onPostExecute(Integer ignored) {

            if (mSuccess) {
                mTVNumInterests.setText(String.valueOf(mNumInterests));
                mTVNumContentObjects.setText(String.valueOf(mNumCOs));
                mTVNumControlMessages.setText(String.valueOf(mNumControl));
                mTVNumInterestReturns.setText(String.valueOf(mNumInterestReturns));
                mTVNumPITEntries.setText("");
            }
        }
    }*/

}