summaryrefslogtreecommitdiff
path: root/app/src/main/java/com/javispedro/rempe/MainActivity.java
blob: b81b0bae14f3bbd98aa8ddff0dc1297821fd5340 (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
package com.javispedro.rempe;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.dsi.ant.plugins.antplus.pcc.defines.RequestAccessResult;
import com.dsi.ant.plugins.antplus.pccbase.AntPluginPcc;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

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

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "MainActivity";

    private SharedPreferences mPrefs = null;

    private final ArrayList<Integer> mDeviceNumbers = new ArrayList<Integer>();
    private final ArrayList<Device> mDevices = new ArrayList<Device>();

    private DeviceListRecyclerViewListAdapter mDeviceListAdapter;
    private SwipeRefreshLayout mSrlList;
    private RecyclerView mList;

    private Device mSearchDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fabAddDevice);
        fab.setOnClickListener(view -> onConnectButtonClicked());

        mSrlList = findViewById(R.id.srlList);
        mSrlList.setOnRefreshListener(() -> onListRefresh());

        mList = findViewById(R.id.list);
        mList.setLayoutManager(new LinearLayoutManager(mList.getContext()));
        mDeviceListAdapter = new DeviceListRecyclerViewListAdapter();
        mList.setAdapter(mDeviceListAdapter);

        new ItemTouchHelper(mItemTouchHelperCallback).attachToRecyclerView(mList);

        refreshDevices();
    }

    @Override
    protected void onDestroy() {
        disconnectAll();
        mPrefs = null;
        mDeviceListAdapter = null;
        mSrlList = null;
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPrefs.registerOnSharedPreferenceChangeListener(mPrefsListener);
        connectToDevices();
    }

    @Override
    public void onPause() {
        disconnectAll();
        mPrefs.unregisterOnSharedPreferenceChangeListener(mPrefsListener);
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.action_open_antplus_plugin_manager:
                if (!AntPluginPcc.startPluginManagerActivity(this)) {
                    Log.e(TAG, "plugin manager not found");
                    showDependencyRequiredMsg("ANT+ plugin manager", "com.dsi.ant.plugins.antplus");
                }
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void onConnectButtonClicked() {
        searchForNewDevice();
    }

    private void onListRefresh() {
        connectToDevices();
        mSrlList.setRefreshing(false);
    }

    private final ItemTouchHelper.Callback mItemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            final int from = viewHolder.getAdapterPosition();
            final int to = viewHolder.getAdapterPosition();

            Log.d(TAG, "onMove from=" + from + " to=" + to);

            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            final int position = viewHolder.getAdapterPosition();
            removeDeviceByPosition(position);
        }
    };

    private final SharedPreferences.OnSharedPreferenceChangeListener mPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            switch (key) {
                case Preferences.PREFS_DEVICES:
                    refreshDevices();
                    break;
            }
        }
    };

    private final Device.DeviceObserver mSearchDeviceObserver = new Device.DeviceObserver() {
        @Override
        public void onDeviceSearchFinished(RequestAccessResult result) {
            Log.d(TAG, "onDeviceSearchFinished result=" + result);
            if (result == RequestAccessResult.SUCCESS) {
                final Device device = mSearchDevice;
                mSearchDevice.setObserver(null);
                mSearchDevice = null; // Ownership of mSearchDevice passed to addDevice below
                runOnUiThread(() -> addDevice(device));
            } else if (result == RequestAccessResult.DEPENDENCY_NOT_INSTALLED) {
                final String dependency = AntPluginPcc.getMissingDependencyName();
                final String packageName = AntPluginPcc.getMissingDependencyPackageName();
                runOnUiThread(() -> {
                    showDependencyRequiredMsg(dependency, packageName);
                });
            } else if (result != RequestAccessResult.USER_CANCELLED) {
                runOnUiThread(() -> {
                    final String resultText = Device.connectionRequestAccessResultToString(MainActivity.this, result);
                    Snackbar.make(findViewById(R.id.fabAddDevice),
                            getString(R.string.add_device_failed, resultText), Snackbar.LENGTH_INDEFINITE).show();
                });
            }
            if (mSearchDevice != null) {
                mSearchDevice.close();
                mSearchDevice = null;
            }
        }

        @Override
        public void onDeviceInfoChanged() {

        }

        @Override
        public void onDeviceStateChanged() {

        }

        @Override
        public void onDeviceNewReading() {

        }

        @Override
        public void onDeviceRssiChanged() {

        }
    };

    public void showDependencyRequiredMsg(String name, String packageName) {
        Log.d(TAG, "showDependencyRequiredMsg for " + name + " (" + packageName + ")");
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.antplus_required_title)
                .setMessage(getString(R.string.antplus_required_msg, name))
                .setPositiveButton(R.string.antplus_required_go_to_store, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=" + packageName));
                    startActivity(intent);
                })
                .setNeutralButton(R.string.antplus_required_close, (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }

    public void searchForNewDevice() {
        if (mSearchDevice != null) {
            mSearchDevice.close();
        }
        mSearchDevice = new Device();
        mSearchDevice.setObserver(mSearchDeviceObserver);
        mSearchDevice.searchForDevice(this);
    }

    public void addDevice(int deviceNumber) {
        Log.d(TAG, "addDevice deviceNumber=" + deviceNumber);
        if (deviceNumber == Device.INVALID_DEVICE) {
            Log.e(TAG, "trying to add invalid device number; ignoring");
            return;
        }
        List<Integer> list = Preferences.getDeviceNumbers(mPrefs);
        if (list.contains(deviceNumber)) {
            Log.w(TAG, "device already on list!");
            Snackbar.make(findViewById(R.id.fabAddDevice),
                    getString(R.string.add_device_already), Snackbar.LENGTH_INDEFINITE).show();
            return;
        }
        list.add(deviceNumber);
        Preferences.saveDeviceNumbers(mPrefs, list);
    }

    public void addDevice(Device device) {
        final int deviceNumber = device.getDeviceNumber();
        Log.d(TAG, "addDevice device.getDeviceNumber=" + deviceNumber);
        if (deviceNumber == Device.INVALID_DEVICE) {
            Log.e(TAG, "trying to add invalid device number; ignoring");
            return;
        }
        if (mDeviceNumbers.contains(deviceNumber)) {
            Log.w(TAG, "device already on list!");
            Snackbar.make(findViewById(R.id.fabAddDevice),
                    getString(R.string.add_device_already), Snackbar.LENGTH_INDEFINITE).show();
            device.close();
            return;
        }

        mDevices.add(device);
        mDeviceNumbers.add(deviceNumber);

        if (mDeviceListAdapter != null) {
            mDeviceListAdapter.notifyItemInserted(mDevices.size() - 1);
        }

        // Since we have manipulated mDeviceNumbers directly, even if we change the Prefs now
        // Prefs listener should end up doing nothing
        Preferences.saveDeviceNumbers(mPrefs, mDeviceNumbers);
    }

    public void removeDeviceByPosition(int position) {
        Log.d(TAG, "removeDeviceByPosition position=" + position);
        List<Integer> list = Preferences.getDeviceNumbers(mPrefs);
        try {
            list.remove(position);
        } catch (IndexOutOfBoundsException ex) {
            Log.w(TAG, ex);
        }

        Snackbar.make(mList,
                getString(R.string.remove_device_done), Snackbar.LENGTH_SHORT).show();

        // Prefs listener will take care of removing the device from mDevices
        Preferences.saveDeviceNumbers(mPrefs, list);
    }

    public void refreshDevices() {
        Log.d(TAG, "refreshDevices");

        setDeviceNumberList(Preferences.getDeviceNumbers(mPrefs));
    }

    public void connectToDevices() {
        Log.d(TAG, "connectToDevices");
        for (Device dev : mDevices) {
            if (!dev.isOpen()) {
                dev.connect(this);
            }
        }
    }

    public void disconnectAll() {
        Log.d(TAG, "disconnectAll");
        for (Device dev : mDevices) {
            dev.close();
        }
    }

    void setDeviceNumberList(List<Integer> newDeviceNumbers) {
            DiffUtil.DiffResult diff = DiffUtil.calculateDiff(new DiffUtil.Callback() {
            @Override
            public int getOldListSize() {
                return mDeviceNumbers.size();
            }

            @Override
            public int getNewListSize() {
                return newDeviceNumbers.size();
            }

            @Override
            public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
                return mDeviceNumbers.get(oldItemPosition).equals(newDeviceNumbers.get(newItemPosition));
            }

            @Override
            public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
                return areItemsTheSame(oldItemPosition, newItemPosition);
            }
        });

        diff.dispatchUpdatesTo(new ListUpdateCallback() {
            @Override
            public void onInserted(int position, int count) {
                for (int i = 0; i < count; ++i) {
                    final int deviceNumber = newDeviceNumbers.get(position + i);
                    final String deviceName = getString(R.string.device_unnamed, deviceNumber);
                    Device device = new Device(deviceNumber, deviceName);
                    mDeviceNumbers.add(position + i, deviceNumber);
                    mDevices.add(position + i, device);
                }
            }

            @Override
            public void onRemoved(int position, int count) {
                for (int i = 0; i < count; ++i) {
                    mDevices.get(position + i).close();
                }
                mDevices.subList(position, position + count).clear();
                mDeviceNumbers.subList(position, position + count).clear();
            }

            @Override
            public void onMoved(int fromPosition, int toPosition) {
                mDevices.set(toPosition, mDevices.get(fromPosition));
                mDevices.set(fromPosition, null);
                mDeviceNumbers.set(toPosition, mDeviceNumbers.get(fromPosition));
                mDeviceNumbers.set(fromPosition, 0);
            }

            @Override
            public void onChanged(int position, int count, @Nullable Object payload) {
                // Nothing to be done
            }
        });

        if (mDeviceListAdapter != null) {
            mDeviceListAdapter.setDeviceList(mDevices);
            diff.dispatchUpdatesTo(mDeviceListAdapter);
        }
    }

    public List<Integer> getDeviceNumberList() {
        return mDeviceNumbers;
    }
}