vl53l0x with android things - raspberry-pi

I hope using VL53L0X with android Things in raspberry pi 3 b+
private static final String I2C_DEVICE_NAME = "I2C1";
private static final int I2C_ADDRESS = 0x52;
PeripheralManager manager = PeripheralManager.getInstance();
List<String> deviceList = manager.getI2cBusList();
if (deviceList.isEmpty()) {
Log.i(TAG, "No I2C bus available on this device.");
} else {
Log.i(TAG, "List of available devices: " + deviceList);
}
byte b=0;
//i2c연결
try {
mDevice = manager.openI2cDevice(I2C_DEVICE_NAME, I2C_ADDRESS);
String name= mDevice.getName();
Log.w(TAG, "connected"+name);
This code connect i2c connected android things VL53L0X
But I can't understand read distance data

Related

Xamarin Forms Artnet and UDP transmission

I'm creating a cross platform application that uses Artnet and UDP protocol to communicate with a device on the network. I know Artnet is also UDP.
Where it works:
Windows OS:
Ethernet. Direct Link and Router controlled.
Wifi. Direct Link and Router Controlled.
Android OS:
Ethernet. N/A
Wifi. Direct Link only.
iOS:
Ethernet. N/A
Wifi. Direct Link only.
Don't understand why there's 0 communication when there's a router involved on Android and iOS. I tried all the suggested codes I could find online and ticked all the capabilities that I could find for Android and iOS.
Wireshark shows there is transmission going on, but my App doesn't capture the packets.
Snipets:
var artnet = new ArtNetSocket(); // using System.Net.Sockets;
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
artnet.Bind(new IPEndPoint(LocalIP, 6454));
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
EndPoint localPort = new IPEndPoint(IPAddress.Any, Port);
ArtNetData data= new ArtNetData();
artnet.BeginReceiveFrom(recieveState.buffer, 0, recieveState.bufferSize, SocketFlags.None, ref localPort, new AsyncCallback(WhenRecieved), data);
private void WhenRecieved(IAsyncResult state)
{
//1.Do something when received
//2.Begin receive again
}
How I look for IPs:
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
if (Interface.NetworkInterfaceType != NetworkInterfaceType.Loopback )
{
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (var info in UnicastIPInfoCol)
{
if (info.Address.AddressFamily == AddressFamily.InterNetwork)
{
IPsets.Add(new IPCouples(info.Address, info.IPv4Mask));
}
}
}
}
It's so weird it's probably something simple...
Ok, because I was creating sockets for each IP group, packets weren't captured on public networks, unless the APP was on a Microsoft OS device. If I create a UDPClient and bind it to a port, instead of the localIP address, it will capture everything coming on that port, regardless of the sender's IP Address. If you check the IP address of the socket, it will be 0.0.0.0:PortNumber.
public class Something: UdpClient
{
public int LocalPort;
public Something(int LocalPort) : base(LocalPort)
{
EnableBroadcast = true;
this.LocalPort = LocalPort;
StartListening();
}
private void StartListening()
{
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
StateObject state = new StateObject();
state.workSocket = Client;
BeginReceive(received, state);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
private void received(IAsyncResult ar)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
StateObject state = (StateObject)ar.AsyncState;
var message = EndReceive(ar, ref remoteEndPoint);
if (message.Length > 0)
{
var messageString = (Encoding.UTF8.GetString(message));
//Do Something
}
StartListening();
}
public SendToAll(string message)
{
var callMessage = Encoding.ASCII.GetBytes(message);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
EnableBroadcast = true;
Send(callMessage, callMessage.Length, new IPEndPoint(GetBroadcast(UnicatIPInfo.Address,UnicatIPInfo.IPv4Mask) , LocalPort));
}
}
}
private IPAddress GetBroadcast(IPAddress someAddress, IPAddress someMask)
{
//Do something to get broadscat
return Broadcast;
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
It works on all platform. Carefull which port you use.

Programatically get list of devices connected to WiFi Hotspot hosted on a Windows IoT Core machine, RPI

I would like to interface with Programmatically Interface with the WiFi Hotspot hosted on my RPI running Windows IoT Core. I figured out host the WiFi Hotspot part, windows 10 iot raspberry pi 3 wifi hotspot but now I would like to get the list of devices connected to this network. Is this Possible?
You can use WiFiDirectConnectionListener to achieve this goal. When other devices connect to host device over the Wifi SoftAP, WiFiDirectConnectionListener will capture a connect request.
private Dictionary<string,DeviceInformation> connectionDeviceList = new Dictionary<string, DeviceInformation>();
WiFiDirectConnectionListener wifiAPListener = new WiFiDirectConnectionListener();
wifiAPListener.ConnectionRequested += WifiAPListener_ConnectionRequested;
private void WifiAPListener_ConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var request = args.GetConnectionRequest();
var devInfo = request.DeviceInformation;
var wfdDevice = await WiFiDirectDevice.FromIdAsync(devInfo.Id);
wfdDevice.ConnectionStatusChanged += WfdDevice_ConnectionStatusChanged;
if (!connectionDeviceList.ContainsKey(devInfo.Id))
{
connectionDeviceList.Add(devInfo.Id, devInfo);
}
}
catch(Exception ex)
{
Debug.Write(ex.StackTrace);
}
}
private void WfdDevice_ConnectionStatusChanged(WiFiDirectDevice sender, object args)
{
try
{
if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
{
if (connectionDeviceList.ContainsKey(sender.DeviceId))
{
connectionDeviceList.Remove(sender.DeviceId);
}
}
}
catch(Exception ex)
{
Debug.Write(ex.StackTrace);
}
}
The name of DeviceInformation is the MAC of you device which you to connect the wifi hotspot, you can get more information by setting a breakpoint. When you drop the connection, the WiFiDirectDevice will invoke ConnectionStatusChanged event.

Get the Bluetooth headphone MAC address as it is connected in A2DP

Goal: open a bluetooth socket to a currently connected A2DP device, when I know it is connected.
In order to connect the socket, I need the MAC address of this device.
As i currently understand, there is 2 kinds of listener to get the bluetooth state:
1- BluetoothAdapter.getProfileProxy() as described here How to get bluetooth connected devices using BluetoothHeadset API
triggers when bluetooth card is ON / OFF.
allow to get a specific bluetoothProfile (A2DP for example), then the list of the connected devices to this profile, then the mac address of this connected devices.
the device list is ever empty when "onServiceConnected" is called (devices need more time to connected after the bluetooth card startup). So I need to call it after the device connection.
2- A broadcast receiver on BluetoothDevice.ACTION_ACL_CONNECTED as described here How to programmatically tell if a Bluetooth device is connected? (Android 2.2)
triggers when bluetooth device is connected / disconnected.
do not allow to get any information of this device
So I need to use both of them to trigger when A2DP device is connected... and so get the MAC address of this device (then open the btSocket):
Start the btAdapter.getProfileProxy inside the BroadcastReceiver "BluetoothDevice.ACTION_ACL_CONNECTED", but with a 3 seconds delay to allow it to connect.
It is the only (complicated) way to do that?
onCreate{
context.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "Action received\n");
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
Log.d(TAG, "ACTION_ACL_CONNECTED received\n");
timerHandler.postDelayed(timerRunnableBtConnection, 3000);
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
{
Log.d(TAG, "ACTION_ACL_DISCONNECTED received\n");
btAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
}
}
private Runnable timerRunnableBtConnection = new Runnable() {
#Override
public void run() {
btAdapter.getProfileProxy(intelloApplication.getAppContext(), mProfileListener, BluetoothProfile.A2DP);
}
};
};
// Define Service Listener of BluetoothProfile
// then create the btSocket on it
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
Log.d(TAG, "Bluetooth connected\n");
btA2dp = (BluetoothA2dp) proxy;
List<BluetoothDevice> devices = btA2dp.getConnectedDevices();
Log.d(TAG, "List of " + devices.size() + " device\n");
for ( final BluetoothDevice dev : devices ) {
String address = dev.getAddress();
Log.d(TAG, "Name: " + dev.getName() + " and address: " + address + "\n");
btDevice = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(btDevice);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
useBluetooth = true;
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
useBluetooth = false;
Log.d(TAG, "....Close connection.");
} catch (IOException e2) {
Log.d(TAG, "Unable to close socket during connection failure");
Log.d(TAG, e2.getMessage());
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
}
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.A2DP) {
Log.d(TAG, "Bluetooth disconnected\n");
}
}
};

sockets seems to not work on two computers

i've faceing a weird problem i wrote a c# simple chat app and it works perfect when i launch the 2 clients on 1 machine but when i try one on my laptop(other computer but same ip) or send it to my friend it's just not working... we both turned off the firewall
thats the server code(part of it which i think can be the problem)
private void StartListening()
{
listener = new TcpListener(IPAddress.Any, listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
and that's the client code
private void EstablishConnection()
{
statusBar1.Text = "Connecting to Server";
try
{
clientsocket = new TcpClient("10.0.0.3",serverport);
ns = clientsocket.GetStream();
sr = new StreamReader(ns);
connected = true;
}
catch (Exception e)
{
MessageBox.Show("Could not connect to Server","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
statusBar1.Text = "Disconnected";
}
}
private void RegisterWithServer()
{
try
{
string command = "CONN|" + ChatOut.Text;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
string serverresponse = sr.ReadLine();
serverresponse.Trim();
string[] tokens = serverresponse.Split(new Char[]{'|'});
if(tokens[0] == "LIST")
{
statusBar1.Text = "Connected";
btnDisconnect.Enabled = true;
}
for(int n=1; n<tokens.Length-1; n++)
lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));
this.Text = clientname + ": Connected to Chat Server";
}
catch (Exception e)
{
MessageBox.Show("Error Registering","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ReceiveChat()
{
bool keepalive = true;
while (keepalive)
{
try
{
Byte[] buffer = new Byte[2048];
ns.Read(buffer,0,buffer.Length);
string chatter = System.Text.Encoding.ASCII.GetString(buffer);
string[] tokens = chatter.Split(new Char[]{'|'});
if (tokens[0] == "CHAT")
{
rtbChatIn.AppendText(tokens[1]);
if(logging)
logwriter.WriteLine(tokens[1]);
}
if (tokens[0] == "PRIV") {
rtbChatIn.AppendText("Private from ");
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(tokens[2] + "\r\n");
if(logging){
logwriter.Write("Private from ");
logwriter.Write(tokens[1].Trim() );
logwriter.WriteLine(tokens[2] + "\r\n");
}
}
if (tokens[0] == "JOIN")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has joined the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has joined the Chat");
}
string newguy = tokens[1].Trim(new char[]{'\r','\n'});
lbChatters.Items.Add(newguy);
}
if (tokens[0] == "GONE")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has left the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has left the Chat");
}
lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));
}
if (tokens[0] == "QUIT")
{
ns.Close();
clientsocket.Close();
keepalive = false;
statusBar1.Text = "Server has stopped";
connected= false;
btnSend.Enabled = false;
btnDisconnect.Enabled = false;
}
}
catch(Exception e){}
}
}
private void QuitChat()
{
if(connected) {
try{
string command = "GONE|" + clientname;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
clientsocket.Close();
}
catch(Exception ex){
}
}
if(logging)
logwriter.Close();
if(receive != null && receive.IsAlive)
receive.Abort();
this.Text = "ChatClient";
}
private void StartStopLogging()
{
if(!logging){
if(!Directory.Exists("logs"))
Directory.CreateDirectory("logs");
string fname = "logs\\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
FileAccess.Write));
logging = true;
btnLog.Text = "Stop Logging";
statusBar1.Text = "Connected - Log on";
}
else{
logwriter.Close();
logging = false;
btnLog.Text = "Start Logging";
statusBar1.Text = "Connected - Log off";
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(String[] args)
{
ChatClientForm cf = new ChatClientForm();
if(args.Length == 0)
cf.serveraddress = "localhost";
else
cf.serveraddress = args[0];
Application.Run(cf);
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
if(ChatOut.Text == ""){
MessageBox.Show("Enter a name in the box before connecting","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else
clientname = ChatOut.Text;
EstablishConnection();
if(connected)
{
RegisterWithServer();
receive = new Thread(new ThreadStart(ReceiveChat));
receive.Start();
btnSend.Enabled = true;
btnConnect.Enabled = false;
ChatOut.Text = "";
}
im breaking my head over 2 weeks with that... please someone help... :(
basically you have a device on your network (It is probably 10.0.01 or 10.0.0.254, but it could be something else). This is probably either your router / cablemodem / dsl modem. This allows you to do Network Address Translation / Port Address Translation (NAT/PAT). Which allows you to share 1 Public /WAN IP address (79.181.175.247) with all of the computers on your LAN (10.0.0.*). It does this by remapping all of your connections outbound to share the one address, and it keeps track of all of these connections. So when your computer goes out to connect to the internet (say browse a website). It connects from from 10.0.0.3 port 45356 to say google.com port 80. The firewall then maps the request to come from 79.181.175.247 port 5634 and sends the packet to google, and keeps track that return traffic to port 5634 maps to 10.0.0.3 port 45356, so it sends it back to the requesting host.
A side effect is that inbound connections don't know where to go. So for example if your serverport is 1234 on your chat program,and it is listening on 0.0.0.0 of your laptop (10.0.0.3). Your Firewall/Router (10.0.0.1?) doesn't know about this port (there are mechanisms, such as UPNP to communicate this up to compatible routers, but that is outside the scope of this). So you need to manually tell your router/firewall that any connections on the public IP address on port 1234 should be forwarded to port 1234 on your laptop. Depending upon the firewall/router this can have different names. Could be Port Forward, or could be called a mapping, etc... This is required so that the inbound traffic makes it directly to your program.
If you where to try this on your local lan (With firewalls disabled on your computer), you would need to use your internal IP addresses (10.0.0.x) to connect between laptop and other computer (you said same IP, but internally they need to have different addresses, or else they won't work).

Android UDID like IPhone?

Does Android have a UDID like IPhone? If yes, is there a way I can get it programatically?
Thanks
Chris
From the docs:
getDeviceId()
Returns the unique device ID, for
example, the IMEI for GSM and the MEID
for CDMA phones. Return null if device
ID is not available.
It's very easy to get the Android UDID - check out the following code:
public class DemoActivityActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
Log.d(">>>>", "Android ID: " + Secure.getString(getContentResolver(), Secure.ANDROID_ID));
Log.d(">>>>", "Device ID : " + tm.getDeviceId());
}
For getting the Device ID you have to set following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
For getting the Android ID you don't need to set any permission.
The Device ID used to only be available if you had signed up for Market by associating your phone with your Google account when you start, i.e. not available on the emulator. This seems to have changed with Android 2.2, where one is generated for the emulator as well. I don't believe it is associated with IMEI, ICC or any other phone-related token, but is rather a pseudo-unique token generated by Google web services to identify your phone.
I implemented a class to get IMEI / Wifi MAC address / deviceID, hope it useful for you ^^
public class DeviceInfo {
protected static String imeiNumber;
protected static String wifiMacAddress;
protected static String deviceID;
// This method must be called before other method
public static void init(Context context) throws Exception {
imeiNumber = getImei(context);
wifiMacAddress = getWifiMacAddress(context);
deviceID = getDeviceId(context);
}
public static String getDeviceInfo() {
return deviceID;
}
public static String getImei() {
return imeiNumber;
}
public static String getWifiMacAddress() {
return wifiMacAddress;
}
public static String getModel() {
return Build.MODEL;
}
public static String getOsVersion() {
return Build.VERSION.RELEASE;
}
protected static String getDeviceId(Context context) throws Exception {
String imei = getImei(context);
if (imei != null) return imei;
String tid = getWifiMacAddress(context);
return tid;
}
protected static String getWifiMacAddress(Context context) throws Exception {
WifiManager manager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo == null || wifiInfo.getMacAddress() == null)
return md5(UUID.randomUUID().toString());
else return wifiInfo.getMacAddress().replace(":", "").replace(".", "");
}
protected static String getImei(Context context) {
TelephonyManager m = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String imei = m != null ? m.getDeviceId() : null;
return imei;
}
protected static String md5(String s) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(s.getBytes());
byte digest[] = md.digest();
StringBuffer result = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
result.append(Integer.toHexString(0xFF & digest[i]));
}
return (result.toString());
}
}