Skip to content

Commit

Permalink
Fix when device comes back from sleep. New enabled/disabled feature
Browse files Browse the repository at this point in the history
  • Loading branch information
harbaum committed Oct 27, 2020
1 parent c6f7c3e commit f3579ab
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 49 deletions.
4 changes: 2 additions & 2 deletions ftDuinoBlue/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ android {
applicationId "org.harbaum.ftduinoblue"
minSdkVersion 22
targetSdkVersion 30
versionCode 2
versionName "1.1"
versionCode 3
versionName "1.2"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
Expand Down Expand Up @@ -41,8 +40,6 @@
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.slider.Slider;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
Expand All @@ -56,8 +53,6 @@
import syntaxhighlight.ParseResult;
import syntaxhighlight.Parser;

import static java.lang.Math.abs;

public class ControlActivity extends AppCompatActivity {
private final static String TAG = ControlActivity.class.getSimpleName();

Expand All @@ -69,8 +64,8 @@ public class ControlActivity extends AppCompatActivity {
private boolean mIsDemo = false;

private SensorManager mSensorManager = null;
private float mSensorAccel[] = new float[3];
private float mSensorMag[] = new float[3];
private float[] mSensorAccel = new float[3];
private float[] mSensorMag = new float[3];
private Handler mHandler = new Handler();
private Runnable mSensorLimiter = null;
private List<LayoutXmlParser.Item> mSensors = new ArrayList<>();
Expand All @@ -88,6 +83,16 @@ void parseMessage(String cmd, String data) {
if (view.getId() == id) {
// use this to update views
switch (cmd.trim().toLowerCase()) {
case "enable":
Log.d(TAG, "Enable " + view.getId());
view.setEnabled(true);
break;

case "disable":
Log.d(TAG, "Disable " + view.getId());
view.setEnabled(false);
break;

case "text":
// this needs another parameter
if(dataParts.length == 2) {
Expand Down Expand Up @@ -147,10 +152,21 @@ void parseMessage(String cmd, String data) {
} catch(IllegalArgumentException e) { /*ignore */ }

if(c != null) {
if (view instanceof TextView) ((TextView) view).setBackgroundColor(c);
if (view instanceof Switch) ((Switch) view).setBackgroundColor(c);
if (view instanceof Button) ((Button) view).setBackgroundColor(c);
if (view instanceof SeekBar) ((SeekBar) view).setBackgroundColor(c);
if (view instanceof TextView)
((TextView) view).setBackgroundColor(c);
if (view instanceof Switch) {
// this doesn't restore the correct color
// ((Switch) view).getBackground().clearColorFilter();
// ((Switch) view).getBackground().setColorFilter(c, PorterDuff.Mode.MULTIPLY);
((Switch) view).setBackgroundColor(c);
}
if (view instanceof Button) {
// ((Button) view).getBackground().clearColorFilter();
// ((Button) view).getBackground().setColorFilter(c, PorterDuff.Mode.MULTIPLY);
((Button) view).setBackgroundColor(c);
}
if (view instanceof SeekBar)
((SeekBar) view).setBackgroundColor(c);
}
}
break;
Expand Down Expand Up @@ -188,6 +204,12 @@ public void onReceive(Context context, Intent intent) {
if (cmd != null && data != null)
parseMessage(cmd, data);
break;

// Hm10 service reports that it's about to be gone ...
case Hm10Service.ACTION_NOTIFY_DESTROYED:
Log.w(TAG, "Hm10 service will be gone");
finish();
break;
}
}
};
Expand Down Expand Up @@ -236,8 +258,8 @@ View addButton(final LayoutXmlParser.Button b) {
button.setLayoutParams(b.layoutParams());

if (b.color() != null) button.setTextColor(b.color());
if (b.bgcolor() != null)
button.getBackground().setColorFilter(b.bgcolor(), PorterDuff.Mode.MULTIPLY);
if (b.bgcolor() != null) button.setBackgroundColor(b.bgcolor());
// button.getBackground().setColorFilter(b.bgcolor(), PorterDuff.Mode.MULTIPLY);

button.setOnTouchListener(new View.OnTouchListener() {
@Override
Expand Down Expand Up @@ -268,8 +290,7 @@ View addSwitch(final LayoutXmlParser.Switch s) {
sw.setLayoutParams(s.layoutParams());

if (s.color() != null) sw.setTextColor(s.color());
if (s.bgcolor() != null)
sw.getBackground().setColorFilter(s.bgcolor(), PorterDuff.Mode.MULTIPLY);
if (s.bgcolor() != null) sw.setBackgroundColor(s.bgcolor());

// send any switch changes as a message to be send via Hm10
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Expand Down Expand Up @@ -362,7 +383,7 @@ public void onMove(int angle, int strength) {
return joystick;
}

public class VerticalSeekBar extends SeekBar {
public class VerticalSeekBar extends androidx.appcompat.widget.AppCompatSeekBar {
public VerticalSeekBar(Context context) {
super(context);
}
Expand Down Expand Up @@ -526,13 +547,29 @@ private String hl(String type, String content) {

// get matching color
int colorIdx = -1;
if(type.equals("tag")) colorIdx = R.color.xmlTag; // tag
else if(type.equals("atn")) colorIdx = R.color.xmlAtn; // attribute name
else if(type.equals("atv")) colorIdx = R.color.xmlAtv; // attribute value
else if(type.equals("com")) colorIdx = R.color.xmlCom; // comment
else if(type.equals("pln")) colorIdx = R.color.xmlPln; // plain text
else if(type.equals("pun")) colorIdx = R.color.xmlPun; // punctuation
else Log.w(TAG, "Unhandled:"+type);
switch (type) {
case "tag":
colorIdx = R.color.xmlTag; // tag
break;
case "atn":
colorIdx = R.color.xmlAtn; // attribute name
break;
case "atv":
colorIdx = R.color.xmlAtv; // attribute value
break;
case "com":
colorIdx = R.color.xmlCom; // comment
break;
case "pln":
colorIdx = R.color.xmlPln; // plain text
break;
case "pun":
colorIdx = R.color.xmlPun; // punctuation
break;
default:
Log.w(TAG, "Unhandled:" + type);
break;
}

// convert color id into color
String color = (colorIdx<0)?"red":String.format("#%06X", (0xFFFFFF & mContext.getResources().getColor(colorIdx)));
Expand Down Expand Up @@ -665,6 +702,7 @@ private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(Hm10Service.ACTION_DISCONNECTED);
filter.addAction(Hm10Service.ACTION_NOTIFY_MESSAGE);
filter.addAction(Hm10Service.ACTION_NOTIFY_DESTROYED);
LocalBroadcastManager.getInstance(this).registerReceiver(mHm10ServiceReceiver, filter);
}

Expand All @@ -682,7 +720,7 @@ public boolean onCreateOptionsMenu(Menu menu) {
}

// map sensor values onto slider/joystick ranges
private int sensor_value(int type, Integer lmax, float vals[]) {
private int sensor_value(int type, Integer lmax, float[] vals) {
float angle = vals[0]; // sensor 1
if (type == 2) angle = vals[1];
if (type == 3) angle = vals[2];
Expand Down Expand Up @@ -771,7 +809,7 @@ public void onSensorChanged(SensorEvent event) {
mSensorMag = null;
mSensorAccel = null;
}
};
}
};

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ public DemoSetup(int id, String name, String address) {
@Override
public IBinder onBind(Intent intent) { return null; }


private final BroadcastReceiver mActivityReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Expand Down Expand Up @@ -400,6 +401,7 @@ public void onScanResult(int callbackType, ScanResult result) {
if (!result.getScanRecord().getServiceUuids().get(0).equals(new ParcelUuid(UUID_UART_SERVICE)))
return;

// Log.d(TAG, "Scan result:" + result.getDevice());
addDevice(result.getDevice());
}
};
Expand Down Expand Up @@ -674,6 +676,8 @@ else if (mBluetoothGatt.getService(UUID_UART_SERVICE) == null)

private
void processLine(String line) {
// Log.w(TAG, "processLine: " + line);

// everything up to first whitespace is the command name
String[] parts = line.split(" +", 2); // split line at first ':'
String cmd = parts[0];
Expand Down Expand Up @@ -763,7 +767,7 @@ void parseLineBytes(byte[] lineBytes) {

processLine(line);
} else
Log.w(TAG, "Checksum failure");
Log.w(TAG, "Checksum failure in line " + new String(lineBytes, StandardCharsets.UTF_8));
} catch (NumberFormatException e) {
// if anything goes wrong we'll just ignore this (broken) message
}
Expand Down Expand Up @@ -870,6 +874,10 @@ public void onDescriptorWrite(BluetoothGatt gatt, final BluetoothGattDescriptor
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();

// disconnect from any device
disconnect();

sendStatus(ACTION_NOTIFY_DESTROYED);
LocalBroadcastManager.getInstance(this).unregisterReceiver(mActivityReceiver);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ public class ScanActivity extends AppCompatActivity implements DeviceViewAdapter
private static final int ENABLE_BLUETOOTH = 2;

private static DeviceViewAdapter adapter;
private Hm10Service hm10Service = null;

private final BroadcastReceiver mHm10ServiceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "Received intent: "+intent);
Log.d(TAG, "Received intent: "+intent);

switch(Objects.requireNonNull(intent.getAction())) {
case Hm10Service.ACTION_NOTIFY_NO_BLE:
Expand Down Expand Up @@ -86,6 +85,8 @@ public void onClick(DialogInterface dialog, int which) {
break;

case Hm10Service.ACTION_DISCONNECTED:
// usually this needs not special action. But this may happen
// while connecting. In that case we need to re-enabled scanning
adapter.setBusy(-1);
findViewById(R.id.scanningBar).setVisibility(View.VISIBLE);
sendRequest(Hm10Service.ACTION_START_SCAN);
Expand All @@ -95,23 +96,24 @@ public void onClick(DialogInterface dialog, int which) {
Log.d(TAG,"hm10 service is gone");
// the hm10 service has sent a notification that it has been
// destroyed. Assume any connection to be gone.
findViewById(R.id.scanningBar).setVisibility(View.GONE);
adapter.setBusy(-1);
adapter.clearList(); // forget everything about devices already detected

// show demo dialog again
findViewById(R.id.initLayout).setVisibility(View.VISIBLE);
break;

case Hm10Service.ACTION_NOTIFY_INITIALIZED:
// only start scanner if it's not already in progress
if(findViewById(R.id.scanningBar).getVisibility() != View.VISIBLE) {
findViewById(R.id.scanningBar).setVisibility(View.VISIBLE);
sendRequest(Hm10Service.ACTION_START_SCAN);
}
Log.d(TAG, "service initialized, start scan");
findViewById(R.id.scanningBar).setVisibility(View.VISIBLE);
sendRequest(Hm10Service.ACTION_START_SCAN);
break;

case Hm10Service.ACTION_NOTIFY_INFORMATION:
String title = intent.getStringExtra("title");
String message = intent.getStringExtra("message");

// TODO: clear current list of known devices? xyz
AlertDialog alertFailDialog = new AlertDialog.Builder(ScanActivity.this).create();
alertFailDialog.setTitle(title);
if(message != null) alertFailDialog.setMessage(message);
Expand All @@ -134,12 +136,30 @@ public void onClick(DialogInterface dialog, int which) {
break;

default:
Log.w(TAG, "Unexpected intent: " + intent);
Log.w(TAG, "Unexpected inteent: " + intent);
break;
}
}
};

@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume(): starting service");
Intent intent = new Intent(this, Hm10Service.class);
try {
startService(intent);
} catch (IllegalStateException e) {
Log.d(TAG, "Failed to start service, will retry later");
}
}

@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

Expand Down Expand Up @@ -216,10 +236,6 @@ protected void onDestroy() {
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 4711) {
Log.w(TAG, "Result for Control Activity: " + resultCode);
}

if (requestCode == ENABLE_BLUETOOTH)
if(resultCode == Activity.RESULT_OK) {
sendRequest(Hm10Service.ACTION_BLUETOOTH_ENABLED);
Expand All @@ -243,7 +259,7 @@ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permis
}

void getLocationAccess() {
Log.w(TAG, "request location access");
Log.d(TAG, "request location access");

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (ScanActivity.this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
Expand Down Expand Up @@ -296,13 +312,6 @@ private void setFilters() {
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart()");

if(hm10Service == null) {
Log.d(TAG, "Starting service");
Intent intent = new Intent(this, Hm10Service.class);
startService(intent);
} else
Log.d(TAG, "Service already running");
}

@Override
Expand All @@ -326,6 +335,7 @@ protected void onCreate(Bundle savedInstanceState) {
ArrayList<DeviceViewAdapter.DeviceEntry> savedDevices = null;
if(savedInstanceState != null) {
savedDevices = savedInstanceState.getParcelableArrayList("foundDevices");
// Log.i(TAG, "found saved devices: " + savedDevices.size());
if(savedDevices != null && savedDevices.size() > 0)
findViewById(R.id.initLayout).setVisibility(View.GONE);
}
Expand Down

0 comments on commit f3579ab

Please sign in to comment.