How to use USB to RS232 communication with Android Things - serial-port

I am using MAX232 device for UART(Raspberry Pi) to RS232 communication(Other Board).
But I want to use USB to Serial cable for this. I have attached the image of a cable. How can I use this in Android Things?
Can anyone tell this.

You can use libraries like this or that. And in case of FTDI-based USB<->UART converters you can use FTDI's solution for Android like d2xx driver with Java wrapper. And you can find many examples (like this) of it's use:
...
private static D2xxManager ftD2xx = null;
private FT_Device ftDev;
...
try {
ftD2xx = D2xxManager.getInstance(this);
int devCount = 0;
devCount = ftD2xx.createDeviceInfoList(this);
Log.d(TAG, "Device number : "+ Integer.toString(devCount));
D2xxManager.FtDeviceInfoListNode[] deviceList = new D2xxManager.FtDeviceInfoListNode[devCount];
ftD2xx.getDeviceInfoList(devCount, deviceList);
if(devCount <= 0) {
return;
}
if(ftDev == null) {
ftDev = ftD2xx.openByIndex(this, 0);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(this, 0);
}
}
...
} catch (D2xxManager.D2xxException ex) {
Log.e(TAG,ex.toString());
}

Related

How to get rssi value of a connected Bluetooth device

I am trying to get the rssi value of a connected bluetooth device in my android program.
Below is the code:
gatt = mDevice.connectGatt(getApplicationContext(), false, new BluetoothGattCallback() {
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
Log.d(TAG, "rssi is : " + rssi);
((TextView) findViewById(R.id.rssiValue)).setText(rssi);
}
});
gatt.readRemoteRssi();
But the method onReadRemoteRssi doesnot return any value.
Please help me with the issue.
if(ContextCompat.checkSelfPermission(RSSI.this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
RSSI.this,
new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_FINE_LOCATION
},
1
);
}
Make sure that the mDevice variable retrieved from BlueetoothAdapter is not null
Lastly make sure the permissions are set, the above code will give you required privileges to get Bluetooth bonded device(s).

Toggle audio in speaker to ear-speaker and vice versa in iphone but microphone is muted

We are using third party Audio/Video SDK in our Xamarin.Forms.iOSproject. Now problem is that by default audio comes in speaker mode, instead of ear-speaker. I found below code and using that audio is toggling in ear-speaker and speaker. but when I am on speaker then microphone is muted and when I am in ear-speaker then both are working. so my question is how to enable microphone in both case?
bool blIsOnEarSpeaker=false;
public void SetAudioSettingsForIOS()
{
var session=AVFoundation.AVAudioSession.SharedInstance();
AVFoundation.AVAudioSessionCategory objCategory= AVFoundation.AVAudioSessionCategory.Playback;
Foundation.NSError error = null;
if (blIsOnEarSpeaker==false)
{
objCategory=AVFoundation.AVAudioSessionCategory.PlayAndRecord;
blIsOnEarSpeaker=true;
error = session.SetCategory(objCategory);
}
else
{
objCategory=AVFoundation.AVAudioSessionCategory.Playback;
blIsOnEarSpeaker=false;
error = session.SetCategory(
objCategory
,AVFoundation.AVAudioSessionCategoryOptions.DefaultToSpeaker
);
}
error = session.SetActive(true);
}
In the else condition:
Change
**objCategory=AVFoundation.AVAudioSessionCategory.Playback;**
to
**objCategory=AVFoundation.AVAudioSessionCategory.PlayAndRecord;**
OR better approach would be, using this line before if/else condition :
bool blIsOnEarSpeaker=false;
public void SetAudioSettingsForIOS()
{
var session=AVFoundation.AVAudioSession.SharedInstance();
AVFoundation.AVAudioSessionCategory objCategory= AVFoundation.AVAudioSessionCategory.Playback;
Foundation.NSError error = null;
objCategory=AVFoundation.AVAudioSessionCategory.PlayAndRecord;
if (blIsOnEarSpeaker==false)
{
blIsOnEarSpeaker=true;
error = session.SetCategory(objCategory);
}
else
{
blIsOnEarSpeaker=false;
error = session.SetCategory(
objCategory
,AVFoundation.AVAudioSessionCategoryOptions.DefaultToSpeaker
);
}
error = session.SetActive(true);
}

How to check Ethernet port connection status in Qt?

I am new to Qt .Actually, i want to check Whether the Ethernet is connected or not through qt application.
For Example: when the Data is transfer from source to Destination through Ethernet. if i suddenly, remove the Ethernet cable my Qt application has to give some pop-up message like "the connection is unavailable". Is there any way to find this one? Finally,Sorry for my English.
You might want to consider the Qt "Bearer Management" API:
http://doc.qt.io/qt-5/bearer-management.html
For example:
/ Set Internet Access Point
QNetworkConfigurationManager manager;
const bool canStartIAP = (manager.capabilities()
& QNetworkConfigurationManager::CanStartAndStopInterfaces);
// Is there default access point, use it
QNetworkConfiguration cfg = manager.defaultConfiguration();
if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
QMessageBox::information(this, tr("Network"), tr(
"No Access Point found."));
return;
}
If you are on Linux, I found a nice idea somewhere to check with QT and QProcess if the Ethernet Cable is physically connected.
QProcess process;
QString sNetCableStatus = "";
process.start("sh", QStringList()<<"-c"<<"grep \"\" /sys/class/net/eth0/carrier");
process.waitForFinished();
sNetCableStatus = process.readAllStandardOutput();
if (sNetCableStatus.length() != 0)
{
if (sNetCableStatus.left(1) == "1")
{
//connected
}
else if(sNetCableStatus.left(1) == "0")
{
//disconnected
}
else
{
//that should not happen
}
}

localhost request packet not recognized by sharppcap?

I did asp.net program using mvc 4. I deployed in iis server as localhost; I want track HTTP Packet so I used SharpPcap.
Here is full code...
namespace CaseStudy
{
class Program
{
static void Main(string[] args)
{
var parmenter = SharpPcap.CaptureDeviceList.Instance;
/*If no device exists, print error */
if (parmenter.Count < 1)
{
Console.WriteLine("No device found on this machine");
return;
}
int i = 0;
Console.WriteLine("Choose Your Devices :");
Console.WriteLine("----------------------");
foreach (PcapDevice dev in parmenter)
{
/* Device Description */
Console.WriteLine("{0}] {1} [MAC:{2}]", i, dev.Interface.FriendlyName, dev.Interface.MacAddress);
i++;
}
Console.WriteLine("----------------------");
//Extract a device from the list
int deviceIndex = -1;
do
{
Console.WriteLine("Enter Your Choice :");
deviceIndex = int.Parse(Console.ReadLine());
} while (!(deviceIndex < parmenter.Count && deviceIndex >= -1));
ICaptureDevice device = parmenter[deviceIndex];
//Register our handler function to the 'packet arrival' event
//device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEventHandler();
device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
//Open the device for capturing
//true -- means promiscuous mode
//1000 -- means a read wait of 1000ms
device.Open(DeviceMode.Promiscuous, 1000);
device.Filter = "ip and tcp";
Console.WriteLine("-- Listenning on {0}, hit 'Enter' to stop...", device.MacAddress);
//Start the capturing process
device.StartCapture();
//Wait for 'Enter' from the user.
Console.ReadLine();
//Stop the capturing process
device.StopCapture();
//Close the capturing device
device.Close();
}
private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
DateTime time = e.Packet.Timeval.Date;
int len = e.Packet.Data.Length;
byte[] data = e.Packet.Data;
//var packet = TcpPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
//Console.WriteLine(e.Packet.LinkLayerType.ToString());
Packet pack = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
if (pack is PacketDotNet.EthernetPacket)
{
var eth = pack.Extract(typeof(EthernetPacket)) as EthernetPacket;
if (len > 100)
{
Console.WriteLine("ETHERNET/INTERNET/HTTP PACKET");
//Console.WriteLine(HttpServerUtility.UrlTokenEncode(eth.Bytes));
Console.WriteLine("{0}-{1}" , eth.DestinationHwAddress, eth.SourceHwAddress);
//Console.WriteLine(eth.PayloadPacket.PayloadPacket.PrintHex());
Console.WriteLine(System.Text.Encoding.UTF8.GetString(eth.Bytes));
}
}
if (pack is PacketDotNet.TcpPacket) {
var tcp = pack.Extract (typeof(TcpPacket)) as TcpPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("TCP PACKET");
Console.WriteLine(tcp.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
if (pack is PacketDotNet.InternetPacket)
{
var inet = pack.Extract(typeof(InternetPacket)) as InternetPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("INTERNET PACKET");
Console.WriteLine(inet.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
if (pack is PacketDotNet.IpPacket)
{
var ip = pack.Extract(typeof(IpPacket)) as IpPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("IP PACKET");
Console.WriteLine(ip.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
}
}
}
this code caputuring remote server http packet like google, stackoverflow, facebook communicate with my system.
However i want track packet with my system only as a localhost.
using
any one can help? please...
It's impossible.
Why?
SharpPcap uses WinPcap and WinPcap extends the system driver to capture packets. According to WinPcap faq Question 13, it's not possible to capture the loopbackdevice aka localhost. It's a limitation of Windows not WinPcap.

LwIP Netconn API + FreeRTOS TCP Client Buffer Issue

I've been trying to modify the tcp server example with LwIP in STM32F4DISCOVERY board. I have to write a sender which does not necessarily have to reply server responses. It can send data with 100 ms frequency, for example.
Firstly, the example of TCP server is like this:
static void tcpecho_thread(void *arg)
{
struct netconn *conn, *newconn;
err_t err;
LWIP_UNUSED_ARG(arg);
/* Create a new connection identifier. */
conn = netconn_new(NETCONN_TCP);
if (conn!=NULL) {
/* Bind connection to well known port number 7. */
err = netconn_bind(conn, NULL, DEST_PORT);
if (err == ERR_OK) {
/* Tell connection to go into listening mode. */
netconn_listen(conn);
while (1) {
/* Grab new connection. */
newconn = netconn_accept(conn);
/* Process the new connection. */
if (newconn) {
struct netbuf *buf;
void *data;
u16_t len;
while ((buf = netconn_recv(newconn)) != NULL) {
do {
netbuf_data(buf, &data, &len);
//Incoming package
.....
//Check for data
if (DATA IS CORRECT)
{
//Reply
data = "OK";
len = 2;
netconn_write(newconn, data, len, NETCONN_COPY);
}
} while (netbuf_next(buf) >= 0);
netbuf_delete(buf);
}
/* Close connection and discard connection identifier. */
netconn_close(newconn);
netconn_delete(newconn);
}
}
} else {
printf(" can not bind TCP netconn");
}
} else {
printf("can not create TCP netconn");
}
}
I modified this code to obtain a client version, this is what I've got so far:
static void tcpecho_thread(void *arg)
{
struct netconn *xNetConn = NULL;
struct ip_addr local_ip;
struct ip_addr remote_ip;
int rc1, rc2;
struct netbuf *Gonderilen_Buf = NULL;
struct netbuf *gonderilen_buf = NULL;
void *b_data;
u16_t b_len;
IP4_ADDR( &local_ip, IP_ADDR0, IP_ADDR1, IP_ADDR2, IP_ADDR3 );
IP4_ADDR( &remote_ip, DEST_IP_ADDR0, DEST_IP_ADDR1, DEST_IP_ADDR2, DEST_IP_ADDR3 );
xNetConn = netconn_new ( NETCONN_TCP );
rc1 = netconn_bind ( xNetConn, &local_ip, DEST_PORT );
rc2 = netconn_connect ( xNetConn, &remote_ip, DEST_PORT );
b_data = "+24C"; // Data to be send
b_len = sizeof ( b_data );
while(1)
{
if ( rc1 == ERR_OK )
{
// If button pressed, send data "+24C" to server
if (GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_0) == Bit_SET)
{
Buf = netbuf_new();
netbuf_alloc(Buf, 4); // 4 bytes of buffer
Buf->p->payload = "+24C";
Buf->p->len = 4;
netconn_write(xNetConn, Buf->p->payload, b_len, NETCONN_COPY);
vTaskDelay(100); // To see the result easily in Comm Operator
netbuf_delete(Buf);
}
}
if ( rc1 != ERR_OK || rc2 != ERR_OK )
{
netconn_delete ( xNetConn );
}
}
}
While the writing operation works, netconn_write sends what's on its buffer. It doesnt care whether b_data is NULL or not. I've tested it by adding the line b_data = NULL;
So the resulting output in Comm Operator is like this:
Rec:(02:47:27)+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C+24C
However, I want it to work like this:
Rec:(02:47:22)+24C
Rec:(02:47:27)+24C
Rec:(02:57:12)+24C
Rec:(02:58:41)+24C
The desired write operation happens when I wait for around 8 seconds before I push the button again.
Since netconn_write function does not allow writing to a buffer, I'm not able to clear it. And netconn_send is only allowed for UDP connections.
I need some guidance to understand the problem and to generate a solution for it.
Any help will be greately appreciated.
It's just a matter of printing the result in the correct way.
You can try to add this part of code before writing in the netbuf data structure:
char buffer[20];
sprintf(buffer,"24+ \n");
Buf->p->payload = "+24C";
I see one or two problems in your code, depending on what you want it exactly to do. First of all, you're not sending b_data at all, but a constant string:
b_data = "+24C"; // Data to be send
and then
Buf->p->payload = "+24C";
Buf->p->len = 4;
netconn_write(xNetConn, Buf->p->payload, b_len, NETCONN_COPY);
b_data is not anywhere mentioned there. What is sent is the payload. Try Buf->p->payload = b_data; if it's what you want to achieve.
Second, if you want the +24C text to be sent only once when you push the button, you'll have to have a loop to wait for the button to open again before continuing the loop, or it will send +24C continuously until you stop pushing the button. Something in this direction:
while (GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_0) == Bit_SET) {
vTaskDelay(1);
}

Resources