react-native-web-serial-api 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -0
  3. package/android/build.gradle +62 -0
  4. package/android/gradle.properties +6 -0
  5. package/android/src/main/AndroidManifest.xml +21 -0
  6. package/android/src/main/java/dev/webserialapi/NativeUsbSerialModule.java +704 -0
  7. package/android/src/main/java/dev/webserialapi/NativeUsbSerialPackage.java +46 -0
  8. package/android/src/main/java/dev/webserialapi/PortPickerActivity.java +235 -0
  9. package/android/src/main/java/dev/webserialapi/UsbDetachReceiver.java +37 -0
  10. package/android/src/main/res/xml/device_filter.xml +13 -0
  11. package/babel.config.js +3 -0
  12. package/biome.json +35 -0
  13. package/example/.watchmanconfig +1 -0
  14. package/example/App.tsx +71 -0
  15. package/example/__tests__/App.test.tsx +16 -0
  16. package/example/android/app/build.gradle +120 -0
  17. package/example/android/app/debug.keystore +0 -0
  18. package/example/android/app/proguard-rules.pro +10 -0
  19. package/example/android/app/src/debug/AndroidManifest.xml +9 -0
  20. package/example/android/app/src/main/AndroidManifest.xml +38 -0
  21. package/example/android/app/src/main/java/dev/uzlopak/MainActivity.kt +22 -0
  22. package/example/android/app/src/main/java/dev/uzlopak/MainApplication.kt +41 -0
  23. package/example/android/app/src/main/res/drawable/rn_edit_text_material.xml +37 -0
  24. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png +0 -0
  25. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png +0 -0
  26. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png +0 -0
  27. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png +0 -0
  28. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png +0 -0
  29. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png +0 -0
  30. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png +0 -0
  31. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  32. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  33. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  34. package/example/android/app/src/main/res/values/strings.xml +3 -0
  35. package/example/android/app/src/main/res/values/styles.xml +9 -0
  36. package/example/android/build.gradle +22 -0
  37. package/example/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  38. package/example/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  39. package/example/android/gradle.properties +47 -0
  40. package/example/android/gradlew +252 -0
  41. package/example/android/gradlew.bat +94 -0
  42. package/example/android/settings.gradle +6 -0
  43. package/example/app.json +4 -0
  44. package/example/babel.config.js +21 -0
  45. package/example/biome.json +47 -0
  46. package/example/deploy.sh +11 -0
  47. package/example/index.html +26 -0
  48. package/example/index.js +9 -0
  49. package/example/index.web.js +8 -0
  50. package/example/jest.config.js +12 -0
  51. package/example/metro.config.js +58 -0
  52. package/example/package-lock.json +14510 -0
  53. package/example/package.json +48 -0
  54. package/example/react-native.config.js +17 -0
  55. package/example/src/components/AppBar.tsx +73 -0
  56. package/example/src/components/Menu.tsx +90 -0
  57. package/example/src/components/SingleChoiceDialog.tsx +120 -0
  58. package/example/src/screens/ConnectScreen.tsx +195 -0
  59. package/example/src/screens/DevicesScreen.tsx +141 -0
  60. package/example/src/screens/TerminalScreen.tsx +564 -0
  61. package/example/src/settings.ts +43 -0
  62. package/example/src/theme.ts +19 -0
  63. package/example/src/util/TextUtil.ts +129 -0
  64. package/example/tsconfig.json +10 -0
  65. package/example/vite.config.mjs +55 -0
  66. package/lib/commonjs/NativeUsbSerial.js +11 -0
  67. package/lib/commonjs/NativeUsbSerial.js.map +1 -0
  68. package/lib/commonjs/NativeUsbSerial.web.js +12 -0
  69. package/lib/commonjs/NativeUsbSerial.web.js.map +1 -0
  70. package/lib/commonjs/UsbSerial.js +149 -0
  71. package/lib/commonjs/UsbSerial.js.map +1 -0
  72. package/lib/commonjs/WebSerial.js +852 -0
  73. package/lib/commonjs/WebSerial.js.map +1 -0
  74. package/lib/commonjs/index.js +44 -0
  75. package/lib/commonjs/index.js.map +1 -0
  76. package/lib/commonjs/package.json +1 -0
  77. package/lib/commonjs/serial.android.js +13 -0
  78. package/lib/commonjs/serial.android.js.map +1 -0
  79. package/lib/commonjs/serial.js +13 -0
  80. package/lib/commonjs/serial.js.map +1 -0
  81. package/lib/commonjs/serial.web.js +11 -0
  82. package/lib/commonjs/serial.web.js.map +1 -0
  83. package/lib/typescript/src/NativeUsbSerial.d.ts +51 -0
  84. package/lib/typescript/src/NativeUsbSerial.d.ts.map +1 -0
  85. package/lib/typescript/src/NativeUsbSerial.web.d.ts +3 -0
  86. package/lib/typescript/src/NativeUsbSerial.web.d.ts.map +1 -0
  87. package/lib/typescript/src/UsbSerial.d.ts +97 -0
  88. package/lib/typescript/src/UsbSerial.d.ts.map +1 -0
  89. package/lib/typescript/src/WebSerial.d.ts +236 -0
  90. package/lib/typescript/src/WebSerial.d.ts.map +1 -0
  91. package/lib/typescript/src/index.d.ts +7 -0
  92. package/lib/typescript/src/index.d.ts.map +1 -0
  93. package/lib/typescript/src/serial.android.d.ts +2 -0
  94. package/lib/typescript/src/serial.android.d.ts.map +1 -0
  95. package/lib/typescript/src/serial.d.ts +2 -0
  96. package/lib/typescript/src/serial.d.ts.map +1 -0
  97. package/lib/typescript/src/serial.web.d.ts +4 -0
  98. package/lib/typescript/src/serial.web.d.ts.map +1 -0
  99. package/package.json +78 -0
  100. package/react-native.config.js +9 -0
  101. package/scripts/deploy-release.sh +127 -0
  102. package/src/NativeUsbSerial.ts +124 -0
  103. package/src/NativeUsbSerial.web.ts +5 -0
  104. package/src/UsbSerial.ts +305 -0
  105. package/src/WebSerial.ts +1084 -0
  106. package/src/index.ts +23 -0
  107. package/src/lib/dom-exception.ts +161 -0
  108. package/src/lib/event-target.ts +170 -0
  109. package/src/lib/promise.ts +19 -0
  110. package/src/serial.android.ts +1 -0
  111. package/src/serial.ts +1 -0
  112. package/src/serial.web.ts +6 -0
  113. package/tsconfig.build.json +7 -0
  114. package/tsconfig.json +20 -0
@@ -0,0 +1,46 @@
1
+ package dev.webserialapi;
2
+
3
+ import androidx.annotation.Nullable;
4
+ import com.facebook.react.BaseReactPackage;
5
+ import com.facebook.react.ReactPackage;
6
+ import com.facebook.react.bridge.NativeModule;
7
+ import com.facebook.react.bridge.ReactApplicationContext;
8
+ import com.facebook.react.module.model.ReactModuleInfo;
9
+ import com.facebook.react.module.model.ReactModuleInfoProvider;
10
+
11
+ import java.util.HashMap;
12
+ import java.util.Map;
13
+
14
+ // `implements ReactPackage` is redundant (BaseReactPackage already implements
15
+ // it) but lets the React Native CLI's autolinking detect this package class —
16
+ // its matcher only recognizes `implements ReactPackage` / `extends TurboReactPackage`.
17
+ public class NativeUsbSerialPackage extends BaseReactPackage implements ReactPackage {
18
+
19
+ @Nullable
20
+ @Override
21
+ public NativeModule getModule(String name, ReactApplicationContext reactContext) {
22
+ if (name.equals(NativeUsbSerialModule.NAME)) {
23
+ return new NativeUsbSerialModule(reactContext);
24
+ }
25
+ return null;
26
+ }
27
+
28
+ @Override
29
+ public ReactModuleInfoProvider getReactModuleInfoProvider() {
30
+ return () -> {
31
+ Map<String, ReactModuleInfo> map = new HashMap<>();
32
+ map.put(
33
+ NativeUsbSerialModule.NAME,
34
+ new ReactModuleInfo(
35
+ NativeUsbSerialModule.NAME,
36
+ NativeUsbSerialModule.NAME,
37
+ false,
38
+ false,
39
+ false,
40
+ true
41
+ )
42
+ );
43
+ return map;
44
+ };
45
+ }
46
+ }
@@ -0,0 +1,235 @@
1
+ package dev.webserialapi;
2
+
3
+ import android.content.BroadcastReceiver;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+ import android.content.IntentFilter;
7
+ import android.hardware.usb.UsbDevice;
8
+ import android.hardware.usb.UsbManager;
9
+ import android.os.Build;
10
+ import android.os.Bundle;
11
+
12
+ import androidx.appcompat.app.AlertDialog;
13
+ import androidx.appcompat.app.AppCompatActivity;
14
+ import androidx.fragment.app.DialogFragment;
15
+
16
+ import com.hoho.android.usbserial.driver.UsbSerialDriver;
17
+ import com.hoho.android.usbserial.driver.UsbSerialPort;
18
+ import com.hoho.android.usbserial.driver.UsbSerialProber;
19
+
20
+ import java.util.ArrayList;
21
+ import java.util.List;
22
+
23
+ public class PortPickerActivity extends AppCompatActivity {
24
+
25
+ public static final String EXTRA_DEVICE_ID = "dev.webserialapi.DEVICE_ID";
26
+ public static final String EXTRA_PORT_NUMBER = "dev.webserialapi.PORT_NUMBER";
27
+ public static final String EXTRA_FILTERS_VENDOR_IDS = "dev.webserialapi.FILTER_VENDOR_IDS";
28
+ public static final String EXTRA_FILTERS_PRODUCT_IDS = "dev.webserialapi.FILTER_PRODUCT_IDS";
29
+ public static final String EXTRA_TITLE_SELECT_PORT = "dev.webserialapi.LABEL_DIALOG_TITLE";
30
+ public static final String EXTRA_TITLE_NO_PORTS_AVAILABLE = "dev.webserialapi.LABEL_NO_DEVICES_TITLE";
31
+ public static final String EXTRA_MESSAGE_NO_PORTS_AVAILABLE = "dev.webserialapi.LABEL_NO_DEVICES_MESSAGE";
32
+
33
+ private static final String DEFAULT_TITLE_SELECT_PORT = "Select Serial Port";
34
+ private static final String DEFAULT_TITLE_NO_PORTS_AVAILABLE = "No devices found";
35
+ private static final String DEFAULT_MESSAGE_NO_PORTS_AVAILABLE = "No USB serial devices are connected.";
36
+
37
+ private static final String TAG_PICKER_DIALOG = "port_picker_dialog";
38
+
39
+ private UsbManager usbManager;
40
+ private int[] filterVendorIds;
41
+ private int[] filterProductIds;
42
+ private String titleSelectPort;
43
+ private String titleNoPortsAvailable;
44
+ private String messageNoPortsAvailable;
45
+
46
+ // No dialog handle needed – the DialogFragment manages its own lifecycle
47
+ private final BroadcastReceiver usbStateReceiver = new BroadcastReceiver() {
48
+ @Override
49
+ public void onReceive(Context context, Intent intent) {
50
+ String action = intent.getAction();
51
+ if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action) ||
52
+ UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
53
+ // Dismiss stale dialog and rebuild with the updated device list
54
+ PortPickerDialogFragment old =
55
+ (PortPickerDialogFragment) getSupportFragmentManager()
56
+ .findFragmentByTag(TAG_PICKER_DIALOG);
57
+ if (old != null) old.dismissAllowingStateLoss();
58
+ showPickerDialog();
59
+ }
60
+ }
61
+ };
62
+
63
+ @Override
64
+ protected void onCreate(Bundle savedInstanceState) {
65
+ super.onCreate(savedInstanceState);
66
+
67
+ usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
68
+ filterVendorIds = getIntent().getIntArrayExtra(EXTRA_FILTERS_VENDOR_IDS);
69
+ filterProductIds = getIntent().getIntArrayExtra(EXTRA_FILTERS_PRODUCT_IDS);
70
+ titleSelectPort = getIntent().getStringExtra(EXTRA_TITLE_SELECT_PORT);
71
+ titleNoPortsAvailable = getIntent().getStringExtra(EXTRA_TITLE_NO_PORTS_AVAILABLE);
72
+ messageNoPortsAvailable = getIntent().getStringExtra(EXTRA_MESSAGE_NO_PORTS_AVAILABLE);
73
+
74
+ // RECEIVER_NOT_EXPORTED is required from Android 14 (API 34) onwards
75
+ IntentFilter usbFilter = new IntentFilter();
76
+ usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
77
+ usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
78
+
79
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
80
+ registerReceiver(usbStateReceiver, usbFilter, Context.RECEIVER_NOT_EXPORTED);
81
+ } else {
82
+ registerReceiver(usbStateReceiver, usbFilter);
83
+ }
84
+
85
+ // Show dialog only on first launch, not after a configuration change (e.g. rotation)
86
+ if (savedInstanceState == null) {
87
+ showPickerDialog();
88
+ }
89
+ }
90
+
91
+ private List<UsbSerialDriver> getFilteredDrivers() {
92
+ List<UsbSerialDriver> drivers =
93
+ UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
94
+
95
+ if (filterVendorIds == null || filterVendorIds.length == 0) {
96
+ return drivers;
97
+ }
98
+
99
+ // Guard against mismatched array lengths to avoid ArrayIndexOutOfBoundsException
100
+ int filterCount = Math.min(filterVendorIds.length,
101
+ filterProductIds != null ? filterProductIds.length : 0);
102
+
103
+ List<UsbSerialDriver> filtered = new ArrayList<>();
104
+ for (UsbSerialDriver driver : drivers) {
105
+ int vid = driver.getDevice().getVendorId();
106
+ int pid = driver.getDevice().getProductId();
107
+ for (int i = 0; i < filterCount; i++) {
108
+ boolean vidMatch = vid == filterVendorIds[i];
109
+ boolean pidMatch = filterProductIds[i] == -1 || pid == filterProductIds[i];
110
+ if (vidMatch && pidMatch) {
111
+ filtered.add(driver);
112
+ break;
113
+ }
114
+ }
115
+ }
116
+ return filtered;
117
+ }
118
+
119
+ private void showPickerDialog() {
120
+ PortPickerDialogFragment dialog = PortPickerDialogFragment.newInstance(
121
+ this,
122
+ getFilteredDrivers(),
123
+ resolve(titleSelectPort, DEFAULT_TITLE_SELECT_PORT),
124
+ resolve(titleNoPortsAvailable, DEFAULT_TITLE_NO_PORTS_AVAILABLE),
125
+ resolve(messageNoPortsAvailable, DEFAULT_MESSAGE_NO_PORTS_AVAILABLE)
126
+ );
127
+ dialog.show(getSupportFragmentManager(), TAG_PICKER_DIALOG);
128
+ }
129
+
130
+ private static String resolve(String override, String defaultValue) {
131
+ return (override != null && !override.isEmpty()) ? override : defaultValue;
132
+ }
133
+
134
+ /** Called by the DialogFragment when the user selects a port. */
135
+ void onPortSelected(UsbDevice device, int portNumber) {
136
+ Intent result = new Intent();
137
+ result.putExtra(EXTRA_DEVICE_ID, device.getDeviceId());
138
+ result.putExtra(EXTRA_PORT_NUMBER, portNumber);
139
+ setResult(RESULT_OK, result);
140
+ finish();
141
+ }
142
+
143
+ /** Called by the DialogFragment when the user cancels. */
144
+ void onPickerCancelled() {
145
+ setResult(RESULT_CANCELED);
146
+ finish();
147
+ }
148
+
149
+ @Override
150
+ protected void onDestroy() {
151
+ super.onDestroy();
152
+ try { unregisterReceiver(usbStateReceiver); } catch (Exception ignored) {}
153
+ }
154
+
155
+ // -------------------------------------------------------------------------
156
+ // Static DialogFragment – survives configuration changes such as rotation
157
+ // -------------------------------------------------------------------------
158
+ public static class PortPickerDialogFragment extends DialogFragment {
159
+
160
+ // Not passed via Bundle argument because UsbSerialDriver is not Serializable/Parcelable
161
+ private List<UsbSerialDriver> drivers;
162
+ private PortPickerActivity host;
163
+ private String titleSelectPort;
164
+ private String titleNoPortsAvailable;
165
+ private String messageNoPortsAvailable;
166
+
167
+ static PortPickerDialogFragment newInstance(
168
+ PortPickerActivity host,
169
+ List<UsbSerialDriver> drivers,
170
+ String titleSelectPort,
171
+ String titleNoPortsAvailable,
172
+ String messageNoPortsAvailable) {
173
+ PortPickerDialogFragment f = new PortPickerDialogFragment();
174
+ f.host = host;
175
+ f.drivers = drivers;
176
+ f.titleSelectPort = titleSelectPort;
177
+ f.titleNoPortsAvailable = titleNoPortsAvailable;
178
+ f.messageNoPortsAvailable = messageNoPortsAvailable;
179
+ return f;
180
+ }
181
+
182
+ @Override
183
+ public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
184
+ Context ctx = requireContext();
185
+
186
+ if (drivers == null || drivers.isEmpty()) {
187
+ return new AlertDialog.Builder(ctx)
188
+ .setTitle(titleNoPortsAvailable)
189
+ .setMessage(messageNoPortsAvailable)
190
+ .setPositiveButton(android.R.string.ok, (d, w) -> cancelAndFinish())
191
+ .setOnCancelListener(d -> cancelAndFinish())
192
+ .create();
193
+ }
194
+
195
+ List<String> labels = new ArrayList<>();
196
+ List<UsbSerialDriver> flatDrivers = new ArrayList<>();
197
+ List<Integer> flatPortNumbers = new ArrayList<>();
198
+
199
+ for (UsbSerialDriver driver : drivers) {
200
+ UsbDevice device = driver.getDevice();
201
+ List<UsbSerialPort> ports = driver.getPorts();
202
+ String driverName = driver.getClass().getSimpleName()
203
+ .replace("SerialDriver", "")
204
+ .replace("Serial", "");
205
+ for (int i = 0; i < ports.size(); i++) {
206
+ String label = ports.size() > 1
207
+ ? String.format("%s · VID 0x%04X / PID 0x%04X · Port %d",
208
+ driverName, device.getVendorId(), device.getProductId(), i)
209
+ : String.format("%s · VID 0x%04X / PID 0x%04X",
210
+ driverName, device.getVendorId(), device.getProductId());
211
+ labels.add(label);
212
+ flatDrivers.add(driver);
213
+ flatPortNumbers.add(i);
214
+ }
215
+ }
216
+
217
+ return new AlertDialog.Builder(ctx)
218
+ .setTitle(titleSelectPort)
219
+ .setItems(labels.toArray(new String[0]), (d, which) -> {
220
+ if (host != null) {
221
+ host.onPortSelected(
222
+ flatDrivers.get(which).getDevice(),
223
+ flatPortNumbers.get(which));
224
+ }
225
+ })
226
+ .setNegativeButton(android.R.string.cancel, (d, w) -> cancelAndFinish())
227
+ .setOnCancelListener(d -> cancelAndFinish())
228
+ .create();
229
+ }
230
+
231
+ private void cancelAndFinish() {
232
+ if (host != null) host.onPickerCancelled();
233
+ }
234
+ }
235
+ }
@@ -0,0 +1,37 @@
1
+ package dev.webserialapi;
2
+
3
+ import android.content.BroadcastReceiver;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+ import android.hardware.usb.UsbDevice;
7
+ import android.hardware.usb.UsbManager;
8
+
9
+ import com.facebook.react.ReactApplication;
10
+ import com.facebook.react.bridge.ReactContext;
11
+ import com.facebook.react.bridge.Arguments;
12
+ import com.facebook.react.bridge.WritableMap;
13
+ import com.facebook.react.modules.core.DeviceEventManagerModule;
14
+
15
+ public class UsbDetachReceiver extends BroadcastReceiver {
16
+
17
+ @Override
18
+ public void onReceive(Context context, Intent intent) {
19
+ if (!UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) return;
20
+
21
+ UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
22
+ if (device == null) return;
23
+
24
+ ReactApplication app = (ReactApplication) context.getApplicationContext();
25
+ ReactContext reactContext = app.getReactHost().getCurrentReactContext();
26
+ if (reactContext == null) return;
27
+
28
+ WritableMap event = Arguments.createMap();
29
+ event.putInt("deviceId", device.getDeviceId());
30
+ event.putInt("usbVendorId", device.getVendorId());
31
+ event.putInt("usbProductId", device.getProductId());
32
+
33
+ reactContext
34
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
35
+ .emit("disconnect", event);
36
+ }
37
+ }
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <resources>
3
+ <!-- CDC ACM (Arduino, etc.) -->
4
+ <usb-device class="2" subclass="2" protocol="1" />
5
+ <!-- FTDI -->
6
+ <usb-device vendor-id="0x0403" />
7
+ <!-- CP210x -->
8
+ <usb-device vendor-id="0x10C4" />
9
+ <!-- CH340/CH341 -->
10
+ <usb-device vendor-id="0x1A86" />
11
+ <!-- Prolific PL2303 -->
12
+ <usb-device vendor-id="0x067B" />
13
+ </resources>
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ presets: ['module:@react-native/babel-preset'],
3
+ };
package/biome.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "includes": ["src/**/*.{ts,tsx}"]
10
+ },
11
+ "formatter": {
12
+ "enabled": true,
13
+ "indentStyle": "space",
14
+ "indentWidth": 2,
15
+ "lineWidth": 80
16
+ },
17
+ "javascript": {
18
+ "formatter": {
19
+ "quoteStyle": "single",
20
+ "trailingCommas": "all",
21
+ "bracketSpacing": false,
22
+ "bracketSameLine": true,
23
+ "arrowParentheses": "asNeeded"
24
+ }
25
+ },
26
+ "linter": {
27
+ "enabled": true,
28
+ "rules": {
29
+ "recommended": true,
30
+ "style": {
31
+ "noNonNullAssertion": "off"
32
+ }
33
+ }
34
+ }
35
+ }
@@ -0,0 +1 @@
1
+ {}
@@ -0,0 +1,71 @@
1
+ import React from 'react';
2
+ import {StatusBar, StyleSheet, View} from 'react-native';
3
+ import type {SerialPort} from 'react-native-web-serial-api';
4
+ import {ConnectScreen} from './src/screens/ConnectScreen';
5
+ import {DevicesScreen} from './src/screens/DevicesScreen';
6
+ import {TerminalScreen} from './src/screens/TerminalScreen';
7
+ import {type ConnectionSettings, DEFAULT_SETTINGS} from './src/settings';
8
+ import {colors} from './src/theme';
9
+
10
+ type Screen = 'devices' | 'connect' | 'terminal';
11
+
12
+ /**
13
+ * A React Native clone of Kai Morich's SimpleUsbTerminal, built on the
14
+ * react-native-web-serial-api Web Serial API. Runs on Android and (Chromium) web.
15
+ */
16
+ function App(): React.JSX.Element {
17
+ const [screen, setScreen] = React.useState<Screen>('devices');
18
+ const [port, setPort] = React.useState<SerialPort | null>(null);
19
+ const [settings, setSettings] =
20
+ React.useState<ConnectionSettings>(DEFAULT_SETTINGS);
21
+
22
+ // Devices -> Connect form
23
+ const selectPort = (p: SerialPort) => {
24
+ setPort(p);
25
+ setScreen('connect');
26
+ };
27
+
28
+ // Connect form -> Terminal
29
+ const startTerminal = (s: ConnectionSettings) => {
30
+ setSettings(s);
31
+ setScreen('terminal');
32
+ };
33
+
34
+ const backToDevices = () => {
35
+ setScreen('devices');
36
+ setPort(null);
37
+ };
38
+
39
+ const backToConnect = () => setScreen('connect');
40
+
41
+ return (
42
+ <View style={styles.root}>
43
+ <StatusBar
44
+ barStyle="light-content"
45
+ backgroundColor={colors.primaryDark}
46
+ />
47
+ {screen === 'terminal' && port ? (
48
+ <TerminalScreen
49
+ port={port}
50
+ settings={settings}
51
+ onBack={backToConnect}
52
+ />
53
+ ) : screen === 'connect' && port ? (
54
+ <ConnectScreen
55
+ port={port}
56
+ initial={settings}
57
+ onBack={backToDevices}
58
+ onConnect={startTerminal}
59
+ />
60
+ ) : (
61
+ <DevicesScreen onSelect={selectPort} />
62
+ )}
63
+ </View>
64
+ );
65
+ }
66
+
67
+ const styles = StyleSheet.create({
68
+ root: {flex: 1, backgroundColor: colors.background},
69
+ });
70
+
71
+ export default App;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @format
3
+ */
4
+
5
+ // Note: import explicitly to use the types shipped with jest.
6
+ import {expect, it} from '@jest/globals';
7
+ import {render, screen, waitFor} from '@testing-library/react-native';
8
+ import App from '../App';
9
+
10
+ it('renders the devices screen', async () => {
11
+ render(<App />);
12
+ expect(screen.getByText('USB Devices')).toBeTruthy();
13
+ // DevicesScreen kicks off an async serial.getPorts() refresh on mount; let it
14
+ // settle so the state update is wrapped in act() (avoids a console warning).
15
+ await waitFor(() => expect(screen.queryByText('USB Devices')).toBeTruthy());
16
+ });
@@ -0,0 +1,120 @@
1
+ apply plugin: "com.android.application"
2
+ apply plugin: "org.jetbrains.kotlin.android"
3
+ apply plugin: "com.facebook.react"
4
+
5
+ /**
6
+ * This is the configuration block to customize your React Native Android app.
7
+ * By default you don't need to apply any configuration, just uncomment the lines you need.
8
+ */
9
+ react {
10
+ /* Folders */
11
+ // The root of your project, i.e. where "package.json" lives. Default is '../..'
12
+ // root = file("../../")
13
+ // The folder where the react-native NPM package is. Default is ../../node_modules/react-native
14
+ // reactNativeDir = file("../../node_modules/react-native")
15
+ // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
16
+ // codegenDir = file("../../node_modules/@react-native/codegen")
17
+ // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
18
+ // cliFile = file("../../node_modules/react-native/cli.js")
19
+
20
+ /* Variants */
21
+ // The list of variants to that are debuggable. For those we're going to
22
+ // skip the bundling of the JS bundle and the assets. By default is just 'debug'.
23
+ // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
24
+ // debuggableVariants = ["liteDebug", "prodDebug"]
25
+
26
+ /* Bundling */
27
+ // A list containing the node command and its flags. Default is just 'node'.
28
+ // nodeExecutableAndArgs = ["node"]
29
+ //
30
+ // The command to run when bundling. By default is 'bundle'
31
+ // bundleCommand = "ram-bundle"
32
+ //
33
+ // The path to the CLI configuration file. Default is empty.
34
+ // bundleConfig = file(../rn-cli.config.js)
35
+ //
36
+ // The name of the generated asset file containing your JS bundle
37
+ // bundleAssetName = "MyApplication.android.bundle"
38
+ //
39
+ // The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
40
+ // entryFile = file("../js/MyApplication.android.js")
41
+ //
42
+ // A list of extra flags to pass to the 'bundle' commands.
43
+ // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
44
+ // extraPackagerArgs = []
45
+
46
+ /* Hermes Commands */
47
+ // The hermes compiler command to run. By default it is 'hermesc'
48
+ // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
49
+ //
50
+ // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
51
+ // hermesFlags = ["-O", "-output-source-map"]
52
+
53
+ /* Autolinking */
54
+ autolinkLibrariesWithApp()
55
+ }
56
+
57
+ /**
58
+ * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
59
+ */
60
+ def enableProguardInReleaseBuilds = false
61
+
62
+ /**
63
+ * The preferred build flavor of JavaScriptCore (JSC)
64
+ *
65
+ * For example, to use the international variant, you can use:
66
+ * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
67
+ *
68
+ * The international variant includes ICU i18n library and necessary data
69
+ * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
70
+ * give correct results when using with locales other than en-US. Note that
71
+ * this variant is about 6MiB larger per architecture than default.
72
+ */
73
+ def jscFlavor = 'org.webkit:android-jsc:+'
74
+
75
+ android {
76
+ ndkVersion rootProject.ext.ndkVersion
77
+ buildToolsVersion rootProject.ext.buildToolsVersion
78
+ compileSdk rootProject.ext.compileSdkVersion
79
+
80
+ namespace "dev.react_native_web_serial_api.example"
81
+ defaultConfig {
82
+ applicationId "dev.react_native_web_serial_api.example"
83
+ minSdkVersion rootProject.ext.minSdkVersion
84
+ targetSdkVersion rootProject.ext.targetSdkVersion
85
+ versionCode 1
86
+ versionName "1.0"
87
+ }
88
+ signingConfigs {
89
+ debug {
90
+ storeFile file('debug.keystore')
91
+ storePassword 'android'
92
+ keyAlias 'androiddebugkey'
93
+ keyPassword 'android'
94
+ }
95
+ }
96
+ buildTypes {
97
+ debug {
98
+ signingConfig signingConfigs.debug
99
+ }
100
+ release {
101
+ // Caution! In production, you need to generate your own keystore file.
102
+ // see https://reactnative.dev/docs/signed-apk-android.
103
+ signingConfig signingConfigs.debug
104
+ minifyEnabled enableProguardInReleaseBuilds
105
+ proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
106
+ }
107
+ }
108
+ }
109
+
110
+ dependencies {
111
+ // usb-serial-for-android is provided transitively by react-native-web-serial-api
112
+ // The version of react-native is set by the React Native Gradle Plugin
113
+ implementation("com.facebook.react:react-android")
114
+
115
+ if (hermesEnabled.toBoolean()) {
116
+ implementation("com.facebook.react:hermes-android")
117
+ } else {
118
+ implementation jscFlavor
119
+ }
120
+ }
@@ -0,0 +1,10 @@
1
+ # Add project specific ProGuard rules here.
2
+ # By default, the flags in this file are appended to flags specified
3
+ # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4
+ # You can edit the include path and order by changing the proguardFiles
5
+ # directive in build.gradle.
6
+ #
7
+ # For more details, see
8
+ # http://developer.android.com/guide/developing/tools/proguard.html
9
+
10
+ # Add any project specific keep options here:
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+ xmlns:tools="http://schemas.android.com/tools">
4
+
5
+ <application
6
+ android:usesCleartextTraffic="true"
7
+ tools:targetApi="28"
8
+ tools:ignore="GoogleAppIndexingWarning"/>
9
+ </manifest>
@@ -0,0 +1,38 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <uses-permission android:name="android.permission.INTERNET" />
4
+ <uses-feature android:name="android.hardware.usb.host" />
5
+
6
+ <application
7
+ android:name=".MainApplication"
8
+ android:label="@string/app_name"
9
+ android:icon="@mipmap/ic_launcher"
10
+ android:roundIcon="@mipmap/ic_launcher_round"
11
+ android:allowBackup="false"
12
+ android:theme="@style/AppTheme"
13
+ android:supportsRtl="true">
14
+ <!-- PortPickerActivity and UsbDetachReceiver are provided by
15
+ react-native-web-serial-api and merged in automatically. -->
16
+ <activity
17
+ android:name=".MainActivity"
18
+ android:label="@string/app_name"
19
+ android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
20
+ android:launchMode="singleTask"
21
+ android:windowSoftInputMode="adjustResize"
22
+ android:exported="true">
23
+ <intent-filter>
24
+ <action android:name="android.intent.action.MAIN" />
25
+ <category android:name="android.intent.category.LAUNCHER" />
26
+ </intent-filter>
27
+ <intent-filter>
28
+ <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
29
+ </intent-filter>
30
+ <intent-filter>
31
+ <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
32
+ </intent-filter>
33
+ <meta-data
34
+ android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
35
+ android:resource="@xml/device_filter" />
36
+ </activity>
37
+ </application>
38
+ </manifest>
@@ -0,0 +1,22 @@
1
+ package dev.react_native_web_serial_api.example
2
+
3
+ import com.facebook.react.ReactActivity
4
+ import com.facebook.react.ReactActivityDelegate
5
+ import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
6
+ import com.facebook.react.defaults.DefaultReactActivityDelegate
7
+
8
+ class MainActivity : ReactActivity() {
9
+
10
+ /**
11
+ * Returns the name of the main component registered from JavaScript. This is used to schedule
12
+ * rendering of the component.
13
+ */
14
+ override fun getMainComponentName(): String = "SimpleUsbTerminal"
15
+
16
+ /**
17
+ * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
18
+ * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
19
+ */
20
+ override fun createReactActivityDelegate(): ReactActivityDelegate =
21
+ DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
22
+ }