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

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

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.LinearLayoutManager;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;

import com.dsi.ant.plugins.antplus.pcc.AntPlusEnvironmentPcc;
import com.dsi.ant.plugins.antplus.pcc.defines.DeviceState;
import com.dsi.ant.plugins.antplus.pcc.defines.RequestAccessResult;
import com.dsi.ant.plugins.antplus.pccbase.AntPluginPcc;
import com.dsi.ant.plugins.antplus.pccbase.PccReleaseHandle;
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 SharedPreferences.OnSharedPreferenceChangeListener mPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            switch (key) {
                case Preferences.PREFS_DEVICES:
                    refreshDevices();
                    break;
            }
        }
    };

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

    private DeviceListRecyclerViewListAdapter mDeviceListAdapter;

    private PccReleaseHandle<AntPlusEnvironmentPcc> mPccSearchHandle;

    @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());

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

        refreshDevices();
    }

    @Override
    protected void onDestroy() {
        disconnectAll();
        mPrefs = null;
        mDeviceListAdapter = 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_remove_all:
                removeAllDevices();
                return true;
            case R.id.action_settings:
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void onConnectButtonClicked() {
        searchForNewDevice();
    }

    public void searchForNewDevice() {
        Log.d(TAG, "searchForNewDevice");
        if (mPccSearchHandle != null) {
            mPccSearchHandle.close();
            mPccSearchHandle = null;
        }
        mPccSearchHandle = AntPlusEnvironmentPcc.requestAccess(this, this, mResultReceiver, mDeviceStateChangeReceiver);
    }

    private AntPluginPcc.IPluginAccessResultReceiver<AntPlusEnvironmentPcc> mResultReceiver = new AntPluginPcc.IPluginAccessResultReceiver<AntPlusEnvironmentPcc>() {
        @Override
        public void onResultReceived(AntPlusEnvironmentPcc result, RequestAccessResult resultCode, DeviceState initialDeviceState) {
            Log.d(TAG, "onResultReceived resultCode=" + resultCode);
            if (resultCode == RequestAccessResult.SUCCESS) {
                int deviceNumber = result.getAntDeviceNumber();
                result.releaseAccess();
                runOnUiThread(() -> addDevice(result.getAntDeviceNumber()));
            } else if (resultCode != RequestAccessResult.USER_CANCELLED) {
                runOnUiThread(() -> {
                    final String resultText = Device.connectionRequestAccessResultToString(MainActivity.this, resultCode);
                    Snackbar.make(findViewById(R.id.fabAddDevice),
                            getString(R.string.add_device_failed, resultText), Snackbar.LENGTH_INDEFINITE).show();
                });
            }
            mPccSearchHandle.close();
            mPccSearchHandle = null;
        }
    };

    private AntPluginPcc.IDeviceStateChangeReceiver mDeviceStateChangeReceiver = new AntPluginPcc.IDeviceStateChangeReceiver() {
        @Override
        public void onDeviceStateChange(DeviceState newDeviceState) {
            Log.d(TAG, "onDeviceStateChange newDeviceState=" + newDeviceState);
        }
    };

    public void addDevice(int deviceNumber) {
        Log.d(TAG, "addDevice " + deviceNumber);
        List<Integer> list = Preferences.getDeviceNumbers(mPrefs);
        if (list.contains(deviceNumber)) {
            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 removeAllDevices() {
        List<Integer> list = new ArrayList<Integer>();
        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);
                    Device device = new Device(deviceNumber);
                    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;
    }
}