I have developed a React Native app for Android device to connect with a HW board and one of the functionality is to communicate with HW board with Serial I/F Adapter from Mobile .
I have tried out multiple npm packages and none of them I could get to work.
Here is my sample code
import SerialPortAPI from 'react-native-serial-port-api';
const path = await SerialPortAPI.devicePaths(paths => {
console.log("List paths", paths)
})
const connectDevice = async (cfg) => {
const { baudRate, serialPortName, stopBits } = cfg
serialPort = await SerialPortAPI.open(serialPortName, { baudRate, stopBits});
const sub = serialPort.onReceived(buff => {
const str = buff.toString('hex').toUpperCase()
console.log(str);
})
await serialPort.send('A7B7');
}
It is NOT listing the device List connected and also not able to open/write/read.
Other packages I tried are:
react-native-usbserial
react-native-serialport
react-native-usb-serialport
react-native-serial-port-api
I any pointers and working sample will be of great help.
Regards
Raghu VT
Are you connecting the phone to your pc or it should work as host? I think that is key point to understand.
My phone is Host and I started with Android code.
Would recommend to use Android to test if possible.
You want to pay attention to the port type used.
If you use a USB AB connector you need to use an otg cable or adapter.
if case of type C , this will be detected automatically.
Hope could provide some hints
Related
How can I set my device name for bluetooth in Flutter?
In Java, there is one plugin BluetoothAdapter which could be used to set the bluetootg device name, but in Flutter, I did not find a way to do this.
thanks
Try FlutterBlue which is a bluetooth plugin for Flutter. You should able to do that via that plugin. Here is an example of reading/writing a characteristic from that page just in case if link goes poof:
// Reads all characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
}
// Writes to a characteristic
await c.write([0x12, 0x34])
I wanted to share something that i found interesting and hopefully get an explanation of this behavior. It goes like this. I created a page and all it does is upload a file to the server.
const input = document.getElementById("input");
const button = document.getElementById("button");
button.addEventListener("click", () => {
const file = input.files[0];
const xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:4000");
const formData = new FormData();
formData.append(input.id, file);
xhr.onload = () => {
console.log(xhr.response);
};
xhr.send(formData);
});
server
const http = require("http");
const express = require("express");
const app = express();
const upload = require("express-fileupload");
const cors = require("cors");
const fs = require("fs");
app.use(cors());
app.use(upload());
const server = http.createServer(app).listen(4000);
app.use("/", express.static(__dirname + "/client"));
app.post("/", (req, res) => {
fs.appendFile("./uploads/" + req.files.input.name, req.files.input.data,
() => {
res.send("file uploaded");
}
);
});
On pc it works just fine. Out of curiosity i wanted to test this on my android device. My pc is connected to mobile hotspot, and i go cmd>ipconfig to get ip adress. Now i enter the page on my phone and when i press upload nothing happens, file not added to folder on server. I think maybe onclick event listener doesn't work on android so i test it by removing http request and changing background color on press. It works. I decide to use USB debbuging so i can get to chrome dev tools on android. And then i try uploading again.
This time it works !
I think maybe it has something to do with phone now being connected to pc by usb. I exit android chrome dev tools and try uploading again, with usb connection. Again it does NOT work, file not added to folder on server.
Does anyone have an idea why ONLY when using android dev tools does this work?
I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager
I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).
Code snippet:
clickButton.Click += (sender, args) =>
{
ClickButtonEvent();
};
private static async void ClickButtonEvent()
{
await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}
I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:
Am I missing something ?
Or is the library broken ?
I ran into this using Android Emulator on Hyper-v. It turns out that the network is set to internal. So the http://www.montemagno.com/sample.mp3 could not be found. My workaround:
Hyper-v -> Virtual Switch Manager, add an external network.
Hyper-v -> Virtual Machines->Settings, add new hardware->Network adapter and set to external network.
"Visual Studio Emulator for Android" desktop app, launch phone vm,
in Visual Studio, deploy and run app.
Sound should work from external source now.
Permissions maybe? In the project site it states that for Android:
You must request AccessWifiState, Internet, MediaContentControl and
WakeLock permissions
By default example use ExoPlayerAudioService.
There are issue with url escape in ExoPlayerAudioService.GetSource method
private IMediaSource GetSource(string url)
{
string escapedUrl = Uri.EscapeDataString(url);
var uri = Android.Net.Uri.Parse(escapedUrl);
var factory = URLUtil.IsHttpUrl(escapedUrl) || URLUtil.IsHttpsUrl(escapedUrl) ? GetHttpFactory() : new FileDataSourceFactory();
var extractorFactory = new DefaultExtractorsFactory();
return new ExtractorMediaSource(uri
, factory
, extractorFactory, null, this);
}
string escapedUrl = Uri.EscapeDataString(url);
I.E. http://example.com/path_to_audio.mp3 will be escaped to "http%3A%2F%2Fexample.com%2Fpath_to_audio.mp3" as result HTTP error.
To fix just skip url escape.
We are looking to communicate with a bluetooth device connected to an Android tablet. We are using Termux and have NodeJS installed. Does anyone know if it is even possible to communicate with a bluetooth device? Would we have to attempt to communicate with the device directly through the /dev folder?
It is my understanding that Android is built on top of the Linux kernel, however, it has implemented specific things on top of it to interact for other things such as connectivity. Would the device even be accessible through the /dev folder via NodejS "serialport" or another tool?
As a last resort, if this is not possible, I guess we could try to build NodeJS in the Android OS through a rooted terminal. I've heard this isn't as easy as one would think though. Through Termux I am able to access the /dev folder and see all the devices. Not sure how the permission would work though. Thanks.
You can communicate through the serial port using this tool. I have never use this tool but providing this only as a reference, since android is built on a linux kernel this might work. Please note that the examples are same as documentation.
https://github.com/eelcocramer/node-bluetooth-serial-port
Basic client usage
var btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
btSerial.on('found', function(address, name) {
btSerial.findSerialPortChannel(address, function(channel) {
btSerial.connect(address, channel, function() {
console.log('connected');
btSerial.write(new Buffer('my data', 'utf-8'), function(err, bytesWritten) {
if (err) console.log(err);
});
btSerial.on('data', function(buffer) {
console.log(buffer.toString('utf-8'));
});
}, function () {
console.log('cannot connect');
});
// close the connection when you're ready
btSerial.close();
}, function() {
console.log('found nothing');
});
});
btSerial.inquire();
Basic server usage (only on Linux)
var server = new(require('bluetooth-serial-port')).BluetoothSerialPortServer();
var CHANNEL = 10; // My service channel. Defaults to 1 if omitted.
var UUID = '38e851bc-7144-44b4-9cd8-80549c6f2912'; // My own service UUID. Defaults to '1101' if omitted
server.listen(function (clientAddress) {
console.log('Client: ' + clientAddress + ' connected!');
server.on('data', function(buffer) {
console.log('Received data from client: ' + buffer);
// ...
console.log('Sending data to the client');
server.write(new Buffer('...'), function (err, bytesWritten) {
if (err) {
console.log('Error!');
} else {
console.log('Send ' + bytesWritten + ' to the client!');
}
});
});
}, function(error){
console.error("Something wrong happened!:" + error);
}, {uuid: UUID, channel: CHANNEL} );
I try to open a website in chrome and native android browser (emulated Android 5.0 and 6) to check several items.
every time i run the test, the choosen browser get started and in the url field stays 'data:,' btw the actual tab is also loaded two times.
I know there is a way to do this with selenium webdriver, but this is not the right way for me because i used the followed code for several emulated devices to test this website and on iOS/Mac osx its working.
So why not on android. My way to test this website is with capybara, appium and ruby.
on iOS there exists a
:safariInitialUrl =>'http://www.mypage.com'
cap.
but not for android.
So, my question is: how is it possible to start my website on an emulated android devices without using selenium webdriver.
code:
Capybara.register_driver :androidphone do |app|
capabilities = {
:deviceName => 'nex5_5',
:avd => 'nex5_5',
:browserName => 'Chrome',
:platformVersion => '5.0',
:platformName => 'Android',
:automationName => 'Appium',
}
url = "http://localhost:4723/wd/hub"
appium_lib_options = {
server_url: url
}
all_options = {
appium_lib: appium_lib_options,
caps: capabilities,
}
Appium::Capybara::Driver.new app, all_options
You have to add this line in your config file :
exports.config = {
directConnect:false,
}
I think you have also to add the Timeout in your configuration file, if you are using jasmine framework for example add this code :
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}