Can't accept connection using raw tcp (lwIp) - tcp

I'm trying to create simple app using raw tcp api from lwip package.
So, here is part of my code:
err_t net_dg_accept(void *arg, struct tcp_pcb *con, err_t e)
{
stm_debug("netdebug: accepting connection");
const char *msg_t = "This is test debug message";
tcp_write(con, msg_t, sizeof(msg_t),TCP_WRITE_FLAG_COPY);
tcp_close(con);
}
void net_dg_thread ()
{
stm_debug("netdebug: thread is starting");
thrd_pcb = tcp_new();
if (thrd_pcb != NULL)
{
stm_debug("netdebug: thread_pcb was created");
err_t e;
e = tcp_bind(thrd_pcb, IP_ADDR_ANY, 22);
if (e == ERR_OK)
{
stm_debug("netdebug: thread_pcb was binded!");
lpcb = tcp_listen(thrd_pcb);
stm_debug("netdebug: thread_pcb was put into listenning mode!");
tcp_accept(lpcb,net_dg_accept);
stm_debug("netdebug: ?");
}
else
{
stm_debug("netdebug: error while binding thread_pcb!");
}
}
else
{
stm_debug("netdebug: error while creating thread_pcb!");
}
}
I try to connect to 22 port, but I get nothing. From the serial debug I get that thrd_pcb was successfully put into listening mode. Why can it be so?

Related

Xamarin Forms iOS will not fully connect to Wifi Access Point that has no internet access

I have a Xamarin forms application. The application programmatically connects to a an access to point to communicate via sockets with a host machine connected to that same access point. The access point is not required to have internet access. When testing my code in iOS - I get a socket error stating that the 'Destination is unreachable'. However, if I go to settings and click on the wifi connection I want to use - I am taken to the login page for the access point. If I click cancel I get the option to 'Use without Internet'. If I select that option, then go back to my application, I am able to connect to the host. Is there a way to programmatically tell iOS to use the connecting even though it does not have internet? I looked at the Zone property but that is read only. Here is the code I am using. Any assistance would be appreciated.
public async Task<WifiConfiguredEventArgs> ConnectToWifi()
{
try
{
var tobj_WifiManager = new NEHotspotConfigurationManager();
var tobj_SSIDs = await tobj_WifiManager.GetConfiguredSsidsAsync();
if (tobj_SSIDs != null && tobj_SSIDs.Contains(App.gvm_AppSettings.WifiSSID))
{
// We are already connected -- just return
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eAlreadyConnected;
}
else
{
var tobj_WifiConfig = new NEHotspotConfiguration(App.gvm_AppSettings.WifiSSID, App.gvm_AppSettings.WifiPassword, false);
tobj_WifiManager.ApplyConfiguration(tobj_WifiConfig, async (error) =>
{
if (error != null)
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eErrorEstablishingConnection;
lobj_WifiConfiguredEventArgs.ErrorMessage = error.ToString();
}
else
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eConnectionEstablished;
}
});
}
}
catch(Exception ex)
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eErrorEstablishingConnection;
lobj_WifiConfiguredEventArgs.ErrorMessage = ex.Message;
lobj_WifiConfiguredEventArgs.ErrorException = ex;
App.ProcessException(ex);
}
return lobj_WifiConfiguredEventArgs;
}
}
Someone asked for the socket code so here it is. To be clear, the socket code connects and communicates fine in iOS when the access point has an internet connection. It also works fine in all the android calls.
using FCISelfCheckIn;
using FCISelfCheckIn.Resources;
using FCISharedAll.FCICommObjects;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static FCISharedAll.FCIEnums.FlexEnums;
namespace FCISelfCheckIn
{
// This template use base socket syntax to change Pattern. (like Send, Receive, and so on)
// Convert to Task-based Asynchronous Pattern. (TAP)
public static class AsynchronousClientSocket
{
private static bool ib_IsConnected = false;
private static Socket iobj_Client = null;
public static async Task<MasterDataObject> SendMessage(string ps_IPAddress, int pi_Port, ge_CommunicationType pe_CommicationType,
string JSONData)
{
MasterDataObject lobj_response = new MasterDataObject();
try
{
//We should already be connected by the time we get here so just continue
//However if we are not - try to connect again
if (!ib_IsConnected)
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
iobj_Client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
ib_IsConnected = await iobj_Client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
}
if (ib_IsConnected)
{
var bytesSent = await iobj_Client.SendAsync(JSONData).ConfigureAwait(false);
// Receive the response from the remote device.
var ls_MasterDataObject = await iobj_Client.ReceiveAsync(60).ConfigureAwait(false);
if (ls_MasterDataObject == null)
{
lobj_response = new MasterDataObject();
lobj_response.CommunicationType = ge_CommunicationType.e_Error;
}
else
{
//deserialize the master data object in order to return it to the client
lobj_response = App.gvm_CommunicationHelper.DeserializeMasterDataObject(ls_MasterDataObject);
iobj_Client.Shutdown(SocketShutdown.Both);
}
}
else
{
lobj_response.CommunicationType = ge_CommunicationType.e_Error;
lobj_response.JSONDataObject = JsonConvert.SerializeObject(AppResources.ServerConnectionError);
}
// Release the socket.
iobj_Client.Close();
}
catch (Exception ex)
{
App.ProcessException(ex);
}
return lobj_response;
}
private static Task<bool> ConnectAsync(this Socket client, IPEndPoint remoteEndPoint)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint));
return Task.Run(() => Connect(client, remoteEndPoint));
}
private static bool Connect(this Socket client, EndPoint remoteEndPoint)
{
bool lb_ReturnValue = true;
try
{
if (client == null || remoteEndPoint == null)
{
lb_ReturnValue = false;
}
else
{
client.Connect(remoteEndPoint);
}
}
catch (System.Net.Sockets.SocketException Socketex)
{
lb_ReturnValue = false;
if (Socketex.ErrorCode != 10061 && Socketex.ErrorCode != 10065)
{
//Dont log if the host is not running.
App.ProcessException(Socketex);
}
}
catch (Exception ex)
{
App.ProcessException(ex);
lb_ReturnValue = false;
}
return lb_ReturnValue;
}
private static async Task<string> ReceiveAsync(this Socket client, int waitForFirstDelaySeconds = 10)
{
if (client == null) throw new ArgumentNullException(nameof(client));
Debug.WriteLine("Receive Message 1");
// Timeout for wait to receive and prepare data.
for (var i = 0; i < waitForFirstDelaySeconds; i++)
{
if (client.Available > 0)
break;
await Task.Delay(3000).ConfigureAwait(false);
}
// return null If data is not available.
if (client.Available < 1)
return null;
Debug.WriteLine("Receive Message 2");
// Size of receive buffer.
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
// Get data
var response = new StringBuilder(bufferSize);
do
{
var size = Math.Min(bufferSize, client.Available);
await Task.Run(() => client.Receive(buffer)).ConfigureAwait(false);
var ts_CurrentSegment = Encoding.ASCII.GetString(buffer, 0, size);
if (ts_CurrentSegment.Length > 0)
{
response.Append(Encoding.ASCII.GetString(buffer, 0, size));
}
} while (!response.ToString().EndsWith(FCIEndOfFile));
// Return result.
return response.ToString().Replace(FCIEndOfFile, "");
}
private static async Task<int> SendAsync(this Socket client, string data)
{
var byteData = Encoding.ASCII.GetBytes(data);
return await SendAsync(client, byteData, 0, byteData.Length, 0).ConfigureAwait(false);
}
private static Task<int> SendAsync(this Socket client, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (client == null) throw new ArgumentNullException(nameof(client));
return Task.Run(() => client.Send(buffer, offset, size, socketFlags));
}
public async static Task<bool> ForcePermissions(string ps_IPAddress, int pi_Port)
{
bool lb_ReturnValue = false;
try
{
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
//This is only done to force the local network permissions access in iOS 14.
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
iobj_Client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
ib_IsConnected = await iobj_Client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
if (ib_IsConnected)
{
Debug.WriteLine("GEORGE Permissions Connected");
//client.Shutdown(SocketShutdown.Both);
//client.Close();
lb_ReturnValue = true;
}
else
{
Debug.WriteLine("George Permissions not Connected");
}
}
catch (Exception ex)
{
//Just skip if there is an exception
App.ProcessException(ex);
}
return lb_ReturnValue;
}
}
}

Soup.Websocket on Vala

I wrote a client and server for tests. Client:
static Soup.WebsocketConnection websocket;
int main (string[] args)
{
var ws_session = new Soup.Session();
var ws_message = new Soup.Message("GET", "http://127.0.0.1:8088/");
string[] protocols = {"chat"};
var ws_loop = new MainLoop();
ws_session.websocket_connect_async.begin(ws_message, "localhost", protocols, null, (obj, res) => {
websocket = ws_session.websocket_connect_async.end(res);
websocket.message.connect(rec_message);
});
ws_loop.run();
stdout.printf("Program end. Press ENTER"); // the program does not reach this point
stdin.read_line();
websocket.close(0, null);
return 0;
}
void rec_message(int type, Bytes message){
stdout.printf("WebSock receive:\n");
stdout.printf("%s\n".printf((string)message.get_data()));
websocket.send_text("test_message2"); // client does not send message
}
And server:
public class WSServer : Soup.Server {
private int access_counter = 0;
public WSServer(){
assert (this != null);
string[] protocols = {"chat"};
this.add_websocket_handler(null,"localhost", protocols, get_ws);
}
void get_ws(Soup.Server server, Soup.WebsocketConnection connection, string path, Soup.ClientContext client){
connection.message.connect(ws_message);
string host = client.get_host();
info (#"Client connected! Host: $host");
string msg = """test_message1""";
info (#"Sending to client message: $msg");
connection.send_text(msg);
}
void ws_message(int id, Bytes msg){
string message = (string)msg.get_data();
info(#"Message received! ID: $id Message:\n$message\n");
}
}
int main (string[] args)
{
try {
int port = 8088;
MainLoop loop = new MainLoop ();
WSServer server = new WSServer ();
server.listen_local (port, 0);
loop.run ();
} catch (Error e) {
error ("Error: %s\n", e.message);
}
stdout.printf("Programm end. Press ENTER");
stdin.read_line ();
return 0;
}
After starting the server and client, the connection and exchange of the first message occurs test_message1 after which the server closes the connection and no longer receives messages. The client attempts to send a message test_message2 and then closes the connection with the code and the error message: WS Error 44: Error receiving data: Connection reset by peer
In general, the solutions to my questions are as follows:
The first problem was solved by removing ws_loop.quit();:
var ws_loop = new MainLoop();
ws_session.websocket_connect_async.begin(ws_message, "localhost", protocols, null, (obj, res) => {
websocket = ws_session.websocket_connect_async.end(res);
websocket.message.connect(rec_message);
//ws_loop.quit(); // this error
});
ws_loop.run();
The connection is closed by the server since the instance WebsocketConnection is destroyed when exiting the function void get_ws(Soup.Server server, Soup.WebsocketConnection connection, string path, Soup.ClientContext client)

Connecting to Bluetooth DUAL-SPP using RFcommsocket

I am trying to use BluetoothConnectionService written by Mitch Tabian to connect to a Microchip BM77 dual mode module. I am trying to connect with transparent BT.
From the logcat it seems that it can not connect to the UUID and then closes socket.
Is this BM77 device not able to connect using RFcommsocket? Does it require a different UUID?
package com.example.user.bluetooth_communication;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;
/**
* Created by User on 12/21/2016.
*/
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
private ConnectedThread mConnectedThread;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
/**
AcceptThread starts and sits waiting for a connection.
Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
**/
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
/**
Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
receiving incoming data through input/output streams respectively.
**/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
D/ViewRootImpl#21bc2e2[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl#21bc2e2[MainActivity]: ViewPostIme pointer 1
D/AbsListView: onTouchUp() mTouchMode : 0
D/BluetoothAdapter: cancelDiscovery
D/BluetoothAdapter: cancelDiscovery = true
D/MainActivity: onItemClick: You Clicked on a device.
D/MainActivity: onItemClick: deviceName = Dual-SPP
onItemClick: deviceAddress = 34:81:F4:40:0F:2A
Trying to pair with Dual-SPP
I/BluetoothDevice: createBond() for device 40:0 called by pid: 27565 tid: 27565
D/BluetoothConnectionServ: start
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
D/BluetoothConnectionServ: AcceptThread: Setting up Server using: 8ce255c0-200a-11e0-ac64-0800200c9a66
D/BluetoothConnectionServ: run: AcceptThread Running.
run: RFCOM server socket start.....
D/ViewRootImpl#21bc2e2[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl#21bc2e2[MainActivity]: ViewPostIme pointer 1
D/MainActivity: startBTConnection: Initializing RFCOM Bluetooth Connection.
D/BluetoothConnectionServ: startClient: Started.
D/ScrollView: initGoToTop
D/ScrollView: initGoToTop
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: setView = DecorView#be25176[Connecting Bluetooth] TM=true MM=false
D/BluetoothConnectionServ: ConnectThread: started.
I/BluetoothConnectionServ: RUN mConnectThread
D/BluetoothConnectionServ: ConnectThread: Trying to create InsecureRfcommSocket using UUID: 8ce255c0-200a-11e0-ac64-0800200c9a66
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: dispatchAttachedToWindow
D/BluetoothAdapter: cancelDiscovery
D/BluetoothAdapter: cancelDiscovery = true
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: Relayout returned: old=[0,0][0,0] new=[23,790][1057,1349] result=0x7 surface={valid=true 524643803136} changed=true
D/OpenGLRenderer: eglCreateWindowSurface = 0x7a27b171e0
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: MSG_RESIZED_REPORT: frame=Rect(23, 790 - 1057, 1349) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl#21bc2e2[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#3daba6f, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#9c9637c, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#4f75405mSocket: android.net.LocalSocket#9c67c5a impl:android.net.LocalSocketImpl#b028e8b fd:java.io.FileDescriptor#2073b68, mSocketState: INIT
D/BluetoothConnectionServ: run: Closed Socket.
D/BluetoothConnectionServ: run: ConnectThread: Could not connect to UUID: 8ce255c0-200a-11e0-ac64-0800200c9a66
connected: Starting.
ConnectedThread: Starting.
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/OpenGLRenderer: eglDestroySurface = 0x7a27b171e0
D/ViewRootImpl#fcf1c11[Connecting Bluetooth]: dispatchDetachedFromWindow
D/InputEventReceiver: channel '48033aa Connecting Bluetooth (client)' ~ Disposing input event receiver.
D/InputEventReceiver: channel '48033aa Connecting Bluetooth (client)' ~NativeInputEventReceiver.
D/ViewRootImpl#21bc2e2[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
E/ViewRootImpl: sendUserActionEvent() returned.
E/BluetoothConnectionServ: write: Error reading Input Stream. socket closed

How can I monitor the ~/.local directory using Vala?

I am trying to monitor the ~/.local directory according to the Vala documentation I can monitor the home correctly. but I can't monitor the the ~/.local.
initFileMonitor V1:
public void initFileMonitor(){
try {
string homePath = Environment.get_home_dir();
string filePath = homePath + "/.local";
File file = File.new_for_path(filePath);
FileMonitor monitor = file.monitor_directory(FileMonitorFlags.NONE, null);
print ("\nMonitoring: %s\n", file.get_path ());
monitor.changed.connect ((src, dest, event) => {
if (dest != null) {
print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
} else {
print ("%s: %s\n", event.to_string (), src.get_path ());
}
});
} catch (Error err) {
print ("Error: %s\n", err.message);
}
}
terminal output(no error, no monitoring):
Monitoring: /home/srdr/.local
Because the file monitor is stored in a local variable it is like other variables destroyed (or in GObject terms finalised/destructed) at the end of the function call
To ensure it lives long enough you should make it a field on a class, then the FileMonitor instance is 'owned' by an instance of that class rather than each call to a specific method
Runnable demo (valac demo.vala --pkg gio-2.0)
class FileMonitorDemo {
private FileMonitor monitor;
public void initFileMonitor() {
var path = Path.build_filename(Environment.get_home_dir(), ".local");
var file = File.new_for_path(path);
try {
monitor = file.monitor_directory(NONE);
message ("Monitoring: %s", file.get_path ());
monitor.changed.connect ((src, dest, event) => {
if (dest != null) {
print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
} else {
print ("%s: %s\n", event.to_string (), src.get_path ());
}
});
} catch (Error err) {
critical ("Error: %s\n", err.message);
}
}
}
void main () {
var filemon = new FileMonitorDemo();
filemon.initFileMonitor();
new MainLoop ().run ();
}
You need to actually run the monitor by creating a main loop and having it wait for events:
new MainLoop ().run ();

Counting the number of transmissions in TinyOS 2.x

I'm trying to implement an application in NesC able to count the number of transmissions performed along the simulation, however I'm facing many difficulties. No approach that I tryed works. Could anyone help me? this is my application:
module FloodingC {
uses {
interface Boot;
interface SplitControl as AMControl;
interface Timer<TMilli> as MilliTimer;
interface Receive;
interface AMSend;
interface Packet;
interface AMPacket;
interface RootControl;
interface PacketAcknowledgements as PackAck;
}
}
implementation {
message_t packet;
bool locked = FALSE;
uint16_t flag;
event void Boot.booted() {
flag = 0;
call AMControl.start();
}
event void AMControl.startDone(error_t err) {
if(err == SUCCESS) {
if(TOS_NODE_ID == 1)
call RootControl.setRoot();
call MilliTimer.startOneShot(1024);
}
else {
call AMControl.start();
}
}
event void AMControl.stopDone(error_t err) {
}
void sendMsg(){
floodingMsg_t* msg = (floodingMsg_t* ) call Packet.getPayload(&packet, sizeof(floodingMsg_t));
if(msg == NULL) {
return;
}
flag = 1;
msg->nodeid = TOS_NODE_ID;
msg->counter = 1;
call PackAck.requestAck(&packet);
if(call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(floodingMsg_t)) == SUCCESS) {
locked = TRUE;
}
}
event void MilliTimer.fired() {
if(locked) {
return;
}
else {
if (call RootControl.isRoot()){
sendMsg();
}
}
}
event void AMSend.sendDone(message_t *msg, error_t error){
if (call PackAck.wasAcked(msg) == SUCCESS){
locked = FALSE;
}
else{
sendMsg();
}
}
event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len) {
floodingMsg_t* newMsg = (floodingMsg_t* )payload;
if (locked == TRUE) return msg;
if(flag == 0) {
flag = 1;
newMsg->nodeid = TOS_NODE_ID;
newMsg->counter++;
call AMSend.send(AM_BROADCAST_ADDR, msg, call Packet.maxPayloadLength());
}
return msg;
}
}
Thanks
You can count them using a BaseStation sniffer (included in tinyos), or adding a sequence number on your transmitted packet.

Resources