initial upload

This commit is contained in:
sunwoods
2025-03-24 00:45:25 +08:00
parent 4cb4186ef0
commit dab111ddd8
79 changed files with 6219 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
+3
View File
@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
</selectionStates>
</component>
</project>
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveExternalAnnotations" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
+1
View File
@@ -0,0 +1 @@
/build
+42
View File
@@ -0,0 +1,42 @@
plugins {
alias(libs.plugins.android.application)
}
android {
namespace 'com.example.epaperuploader'
compileSdk 34
defaultConfig {
applicationId "com.example.epaperuploader"
minSdk 24
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation libs.appcompat
implementation libs.material
implementation libs.activity
implementation libs.constraintlayout
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
implementation 'com.google.code.gson:gson:2.10.1'
implementation("com.vanniktech:android-image-cropper:4.6.0")
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.example.epaperuploader;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.epaperuploader", appContext.getPackageName());
}
}
+70
View File
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.EPaperUploader"
android:usesCleartextTraffic="true"
android:preserveLegacyExternalStorage="true"
tools:targetApi="31">
<activity
android:name=".SpiPinEditActivity"
android:exported="false" />
<activity
android:name=".SpiPinConfigActivity"
android:exported="false" />
<activity
android:name=".DeviceScanActivity"
android:exported="false" />
<activity
android:name=".FilteringActivity"
android:exported="false" />
<activity
android:name=".CropImageActivity"
android:exported="false" />
<activity
android:name=".DisplaysActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".BluetoothLeService"
android:enabled="true" />
</application>
</manifest>
@@ -0,0 +1,35 @@
package com.example.epaperuploader;
import android.bluetooth.BluetoothDevice;
/**
* 作者:yeqianyun on 2019/11/6 17:22
* 邮箱:1612706976@qq.com
*
* BLE蓝牙设备
*/
public class BLEDevice {
private BluetoothDevice bluetoothDevice; //蓝牙设备
private int RSSI; //蓝牙信号
public BLEDevice(BluetoothDevice bluetoothDevice, int RSSI) {
this.bluetoothDevice = bluetoothDevice;
this.RSSI = RSSI;
}
public BluetoothDevice getBluetoothDevice() {
return bluetoothDevice;
}
public void setBluetoothDevice(BluetoothDevice bluetoothDevice) {
this.bluetoothDevice = bluetoothDevice;
}
public int getRSSI() {
return RSSI;
}
public void setRSSI(int RSSI) {
this.RSSI = RSSI;
}
}
@@ -0,0 +1,362 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.example.epaperuploader;
import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
public static BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"EXTRA_DATA";
public final static UUID UUID_HEART_RATE_MEASUREMENT =
UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
gatt.readPhy();
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
MainActivity.handlerBt.handleUploadingStage();
}
@Override
public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
super.onPhyRead(gatt, txPhy, rxPhy, status);
Log.e(TAG, "onPhyRead: txPhy:" + txPhy + ", rxPhy:" + rxPhy);
gatt.setPreferredPhy(BluetoothDevice.PHY_LE_2M, BluetoothDevice.PHY_LE_2M,
BluetoothDevice.PHY_OPTION_NO_PREFERRED);
}
@Override
public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
super.onPhyUpdate(gatt, txPhy, rxPhy, status);
Log.e(TAG, "onPhyRead: txPhy:" + txPhy + ", rxPhy:" + rxPhy);
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
}
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind is calling:" + mBinder);
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
*
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
@SuppressLint("MissingPermission")
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
@SuppressLint("MissingPermission")
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
@SuppressLint("MissingPermission")
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic The characteristic to read from.
*/
@SuppressLint("MissingPermission")
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
@SuppressLint("MissingPermission")
public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.writeCharacteristic(characteristic);
}
/**
* Enables or disables notification on a give characteristic.
*
* @param characteristic Characteristic to act on.
* @param enabled If true, enable notification. False otherwise.
*/
@SuppressLint("MissingPermission")
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
}
@@ -0,0 +1,91 @@
package com.example.epaperuploader;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.canhub.cropper.CropImageView;
import com.example.epaperuploader.image_processing.EPaperDisplay;
import java.io.File;
import java.io.IOException;
public class CropImageActivity extends AppCompatActivity {
private Uri sourceUri;
private Uri saveUri;
private CropImageView vCropImageView;
private final ActivityResultLauncher<String> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.GetContent(),
uri -> vCropImageView.setImageUriAsync(uri));
private Button btnRotation;
private Button btnCrop;
private int width = EPaperDisplay.getDisplays()[EPaperDisplay.epdInd].width;
private int height = EPaperDisplay.getDisplays()[EPaperDisplay.epdInd].height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop_image);
vCropImageView = findViewById(R.id.cropImageView);
vCropImageView.setOnSetImageUriCompleteListener(new CropImageView.OnSetImageUriCompleteListener() {
@Override
public void onSetImageUriComplete(@NonNull CropImageView cropImageView, @NonNull Uri uri, @Nullable Exception e) {
sourceUri = uri;
vCropImageView.setAspectRatio(width, height);
}
});
vCropImageView.setOnCropImageCompleteListener(new CropImageView.OnCropImageCompleteListener() {
@Override
public void onCropImageComplete(@NonNull CropImageView cropImageView, @NonNull CropImageView.CropResult cropResult) {
Intent intent = new Intent();
intent.putExtra("FILE_NAME", saveUri);
setResult(RESULT_OK, intent);
finish();
}
});
btnRotation = findViewById(R.id.btnRotation);
btnRotation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vCropImageView.rotateImage(90);
vCropImageView.setAspectRatio(width, height);
}
});
btnCrop = findViewById(R.id.btnCrop);
btnCrop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
saveUri = Uri.fromFile(File.createTempFile("esp32_image_crop", "png"));
vCropImageView.croppedImageAsync(
Bitmap.CompressFormat.PNG,
30,
width,
height,
CropImageView.RequestSizeOptions.NONE,
saveUri
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
activityResultLauncher.launch("image/*");
}
}
@@ -0,0 +1,344 @@
package com.example.epaperuploader;
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.
*/
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
//public class DeviceScanActivity extends ListActivity {
public class DeviceScanActivity extends AppCompatActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private ListView deviceList;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
/**
* This block is for requesting permissions up to Android 12+
*
*/
private static final int PERMISSIONS_REQUEST_CODE = 191;
private static final String[] BLE_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
};
@SuppressLint("InlinedApi")
private static final String[] ANDROID_12_BLE_PERMISSIONS = new String[]{
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.ACCESS_FINE_LOCATION
};
public static void requestBlePermissions(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
ActivityCompat.requestPermissions(activity, ANDROID_12_BLE_PERMISSIONS, requestCode);
else
ActivityCompat.requestPermissions(activity, BLE_PERMISSIONS, requestCode);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_scan);
getSupportActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
requestBlePermissions(this, PERMISSIONS_REQUEST_CODE);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_scan) {
mLeDeviceListAdapter.clear();
scanLeDevice(true);
} else if (itemId == R.id.menu_stop) {
scanLeDevice(false);
}
return true;
}
@SuppressLint("MissingPermission")
@Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
deviceList = findViewById(R.id.device_list);
deviceList.setAdapter(mLeDeviceListAdapter);
deviceList.setOnItemClickListener(new OnDevListItemClick());
scanLeDevice(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
@SuppressLint("MissingPermission")
private class OnDevListItemClick implements AdapterView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// 停止扫描
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
final BLEDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
Intent intent = new Intent();
intent.putExtra("DEVICE", device.getBluetoothDevice());
setResult(RESULT_OK, intent);
finish();
}
}
@SuppressLint("MissingPermission")
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BLEDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BLEDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public boolean isRepeat(List rawList, BLEDevice bleDevice) {
int Num = rawList.size();
if(Num==0)
{
return false;
}
String devName = bleDevice.getBluetoothDevice().getName();
String devAddress = bleDevice.getBluetoothDevice().getAddress();
for(int i =0;i<Num;i++)
{
String a1 = mLeDevices.get(i).getBluetoothDevice().getName();
String a2 = mLeDevices.get(i).getBluetoothDevice().getAddress();
if(Objects.equals(a1, devName) & Objects.equals(a2, devAddress))
{
return true;
}
}
return false;
}
public void addDevice(BLEDevice device) {
if(mLeDevices == null){
return;
}
if(!isRepeat(mLeDevices, device)){
mLeDevices.add(device);
}
}
public BLEDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
@Override
public int getCount() {
return mLeDevices.size();
}
@Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
viewHolder.deviceRSSI = (TextView) view.findViewById(R.id.device_rssi);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BLEDevice device = mLeDevices.get(i);
@SuppressLint("MissingPermission") final String deviceName = device.getBluetoothDevice().getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getBluetoothDevice().getAddress());
viewHolder.deviceRSSI.setText("RSSI: " + device.getRSSI());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String devName = device.getName();
if (devName != null && devName.length() > 0) {
BLEDevice bleDevice = new BLEDevice(device, rssi);
// mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.addDevice(bleDevice);
mLeDeviceListAdapter.notifyDataSetChanged();
}
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
TextView deviceRSSI;
}
}
@@ -0,0 +1,71 @@
package com.example.epaperuploader;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.epaperuploader.image_processing.EPaperDisplay;
public class DisplaysActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
// View of displays list
//---------------------------------------------------------
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displays);
getSupportActionBar().setTitle(R.string.disp);
// ListView, its adapter and listener
//--------------------------------------
listView = findViewById(R.id.displays_list);
listView.setAdapter(new DisplayListAdapter(this, EPaperDisplay.getDisplays()));
listView.setOnItemClickListener(this);
}
public void onCancel(View view) {
onBackPressed();
}
@Override
public void onBackPressed() {
setResult(RESULT_CANCELED, new Intent());
finish();
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
EPaperDisplay.epdInd = i;
setResult(RESULT_OK, new Intent());
finish();
}
//---------------------------------------------------------
// File list adapter
//---------------------------------------------------------
private class DisplayListAdapter extends ArrayAdapter<EPaperDisplay> {
public DisplayListAdapter(Context context, EPaperDisplay[] array) {
// Standard one-line item layout
//-------------------------------------------------
super(context, android.R.layout.simple_list_item_1, array);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
if (view != null) view.setText(EPaperDisplay.getDisplays()[position].title);
return view;
}
}
}
@@ -0,0 +1,259 @@
package com.example.epaperuploader;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.epaperuploader.image_processing.EPaperDisplay;
import com.example.epaperuploader.image_processing.EPaperPicture;
/**
* <h1>Filtering activity</h1>
* The activity offers to select one of available image filters,
* which converts the loaded image for better pixel format
* converting required for selected display.
*
* @author Waveshare team
* @version 1.0
* @since 8/18/2018
*/
public class FilteringActivity extends AppCompatActivity
{
// View
//------------------------------------------
private Button button;
private TextView textView;
private ImageView imageView;
private Button btnLevelMono;
private Button btnLevelColor;
private Button btnDitherMono;
private Button btnDitherMono2;
private Button btnDitherColor;
private Button btnDitherColor2;
private ImageView imgLevelMono;
private ImageView imgLevelColor;
private ImageView imgDitherMono;
private ImageView imgDitherMono2;
private ImageView imgDitherColor;
private ImageView imgDitherColor2;
private final static String TAG = FilteringActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filtering);
getSupportActionBar().setTitle(R.string.filt);
// View
//------------------------------------------
textView = findViewById(R.id.txt_indexed);
imageView = findViewById(R.id.img_indexed);
btnLevelMono = findViewById(R.id.btn_wb_l);
btnLevelColor = findViewById(R.id.btn_wbrl);
btnDitherMono = findViewById(R.id.btn_wb_d);
btnDitherMono2 = findViewById(R.id.btn_wb_d2);
btnDitherColor = findViewById(R.id.btn_wbrd);
btnDitherColor2 = findViewById(R.id.btn_wbrd2);
imgLevelMono = findViewById(R.id.img_level_mono);
imgLevelColor = findViewById(R.id.img_level_color);
imgDitherMono = findViewById(R.id.img_dither_mono);
imgDitherMono2 = findViewById(R.id.img_dither_mono2);
imgDitherColor = findViewById(R.id.img_dither_color);
imgDitherColor2 = findViewById(R.id.img_dither_color2);
// Disable unavailable palettes
//------------------------------------------
boolean redIsEnabled = (EPaperDisplay.getDisplays()[EPaperDisplay.epdInd].index & 1) != 0;
btnLevelColor.setEnabled(redIsEnabled);
btnDitherColor.setEnabled(redIsEnabled);
btnDitherColor2.setEnabled(redIsEnabled);
// Disable unavailable palettes just for 5.65f e-Paper
//------------------------------------------
if(EPaperDisplay.epdInd == 25 || EPaperDisplay.epdInd == 37 || EPaperDisplay.epdInd == 43 || EPaperDisplay.epdInd == 47)
{
redIsEnabled = false;
btnLevelMono.setEnabled(redIsEnabled);
btnDitherMono.setEnabled(redIsEnabled);
btnDitherMono2.setEnabled(redIsEnabled);
}
// 通过模拟点击,来实现预览
if (btnLevelMono.isEnabled()) {
btnLevelMono.callOnClick();
}
if (btnLevelColor.isEnabled()) {
btnLevelColor.callOnClick();
}
if (btnDitherMono.isEnabled()) {
btnDitherMono.callOnClick();
}
if (btnDitherMono2.isEnabled()) {
btnDitherMono2.callOnClick();
}
if (btnDitherColor.isEnabled()) {
btnDitherColor.callOnClick();
}
if (btnDitherColor2.isEnabled()) {
btnDitherColor2.callOnClick();
}
}
public void onImgClick(View view) {
int img_id = view.getId();
String name = "";
Button btn;
if (img_id == R.id.img_level_mono) {
btn = btnLevelMono;
} else if (img_id == R.id.img_level_color) {
btn = btnLevelColor;
} else if (img_id == R.id.img_dither_mono) {
btn = btnDitherMono;
} else if (img_id == R.id.img_dither_mono2) {
btn = btnDitherMono2;
} else if (img_id == R.id.img_dither_color) {
btn = btnDitherColor;
} else if (img_id == R.id.img_dither_color2) {
btn = btnDitherColor2;
} else {
return;
}
name = btn.getText().toString();
Log.e("TAG", "Image id: " + img_id + ", Name: " + name);
Intent intent = new Intent();
intent.putExtra("NAME", name);
btn.callOnClick();
setResult(RESULT_OK, intent);
finish();
}
// Accept the selected
public void onOk(View view)
{
// If palette is not selected, then exit
//-----------------------------------------------------
if (button == null) return;
// Close palette activity and return palette's name
//-----------------------------------------------------
Intent intent = new Intent();
intent.putExtra("NAME", button.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
public void onCancel(View view)
{
onBackPressed();
}
@Override
public void onBackPressed()
{
setResult(RESULT_CANCELED);
finish();
}
public void onButtonClick(View view) {
int btnId = view.getId();
boolean isLvl;
boolean isRed;
boolean isEnhance = false;
if (btnId == R.id.btn_wb_l) {
isLvl = true;
isRed = false;
} else if (btnId == R.id.btn_wbrl) {
isLvl = true;
isRed = true;
} else if (btnId == R.id.btn_wb_d) {
isLvl = false;
isRed = false;
} else if (btnId == R.id.btn_wb_d2) {
isLvl = false;
isRed = false;
isEnhance = true;
} else if (btnId == R.id.btn_wbrd) {
isLvl = false;
isRed = true;
} else if (btnId == R.id.btn_wbrd2) {
isLvl = false;
isRed = true;
isEnhance = true;
} else {
Log.e(TAG, "Error id: " + btnId + ", name: " + view.getTransitionName());
return;
}
button = (Button)view;
run(isLvl, isRed, isEnhance);
}
public void run(boolean isLvl, boolean isRed, boolean isEnhance)
{
// Image processing
//-----------------------------------------------------
MainActivity.indTableImage = EPaperPicture.createIndexedImage(isLvl, isRed, isEnhance);
// Image view size calculation
//-----------------------------------------------------
int size = textView.getWidth();
imageView.setMaxHeight(Math.min(300, size));
imageView.setMinimumHeight(Math.min(200, size / 2));
imageView.setImageBitmap(MainActivity.indTableImage);
ImageView sampleImageView;
if (isLvl) {
if (isRed) {
sampleImageView = imgLevelColor;
} else {
sampleImageView = imgLevelMono;
}
} else {
if (isRed) {
if (isEnhance) {
sampleImageView = imgDitherColor2;
} else {
sampleImageView = imgDitherColor;
}
} else {
if (isEnhance) {
sampleImageView = imgDitherMono2;
} else {
sampleImageView = imgDitherMono;
}
}
}
sampleImageView.setMaxHeight(Math.min(300, size));
sampleImageView.setMinimumHeight(Math.min(200, size / 2));
sampleImageView.setImageBitmap(MainActivity.indTableImage);
// Show selected image filter
//-----------------------------------------------------
textView.setText(button.getText());
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.example.epaperuploader;
import java.util.HashMap;
/**
* This class includes a small subset of standard GATT attributes for demonstration purposes.
*/
public class SampleGattAttributes {
private static HashMap<String, String> attributes = new HashMap();
public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
static {
// Sample Services.
attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");
// Sample Characteristics.
attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
// 增加墨水屏的UUID定制
attributes.put("6e400001-b5a3-f393-e0a9-e50e24dcca9e", "E-Paper");
attributes.put("6e400003-b5a3-f393-e0a9-e50e24dcca9e", "Read WiFi IP");
attributes.put("6e400004-b5a3-f393-e0a9-e50e24dcca9e", "Write msg");
attributes.put("6e400005-b5a3-f393-e0a9-e50e24dcca9e", "Write data");
}
public static String lookup(String uuid, String defaultName) {
String name = attributes.get(uuid);
return name == null ? defaultName : name;
}
}

Some files were not shown because too many files have changed in this diff Show More