writeBytes returning -1025 using LibNoDave - c#

I have a weird problem with my Connection from C# to my Simatic S7-1200.
I am using LibNoDave to connect and i want to set bits of my SPS with the C#-program.
This is working just fine but it only works 9 times and then the writeBytes(..) function returns -1025 and not 0 as it should and it is not setting the byte anymore.
I then have to restart the application and it will work 9 times again.
This is my LibNoDave class.
static class LibNoDave
{
static libnodave.daveConnection dc;
static bool connection = false;
public static bool CreateConnection()
{
const string IP = "192.168.1.250";
const int Rack = 0;
const int Slot = 0;
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
try
{
fds.rfd = libnodave.openSocket(102, IP);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1",
0, libnodave.daveProtoISOTCP,
libnodave.daveSpeed187k);
di.setTimeout(1000000);
int res = di.initAdapter();
if (res == 0)
{
dc = new libnodave.daveConnection(di, 0,
Rack, Slot);
res = dc.connectPLC();
if (res == 0)
{
connection = true;
return true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
public static void DisconnectPLC()
{
if (connection)
{
dc.disconnectPLC();
libnodave.closeSocket(102);
connection = false;
}
}
public static void WritePLC(int anfangswert, byte wert)
{
if (connection)
{
byte[] buf = new Byte[1];
buf[0] = wert;
int res = dc.writeBytes(libnodave.daveFlags, 0, anfangswert, 1, buf);
MessageBox.Show(res.ToString());
}
}
}
Here I am calling the functions:
private void frmAuslagerung_Load(object sender, EventArgs e)
{
if (!LibNoDave.CreateConnection())
{
finished = true;
this.Close();
}
LibNoDave.WritePLC(1, Byte.Parse(auto.Position.Lade.ToString()));
}
private void frmAuslagerung_FormClosing(object sender, FormClosingEventArgs e)
{
if (!finished)
{
//e.Cancel = true; //Not in code for testing
LibNoDave.DisconnectPLC(); //Only for testing
}
else
LibNoDave.DisconnectPLC();
}

I don´t see any problem in code and I don´t know neither your device nor LibNoDave, but the problem may be related to:
1- Is some receiver an "One single digit" (like 0 to 9) address or container ?
2- The position is being truly reseted as I see in WritePLC function?
3- The "LibNoDave.WritePLC" is incrementing its pointer?
Good luck.

it can be problem closing the connection try with:
public static void DisconnectPLC()
{
if (connection)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closePort(fds.rfd);
connection = false;
}
}

It's old, but for others to find: in my case it was the declaration of fds and di: they had to be class members and not local to the connect method, or the timeout value was being lost later on.

Related

C# check multiple client connections

I am currently developing a one-to-many relationship between one server and many clients.
Everytime a client connects I append to the client list: clientList.Add(client);
I wrote the following code to check the "pulse" of the client connection as to see if the client is still connected and currently updating the toolStripStatusLabel1
This seems to work well when checking one connection and in addition, I added the exception cleanup() when trying to send data so that it should check at all scenarios(Feel free to give your opinion).
My question now is, how do I check the connection from multiple clients?
Please find below the reference code:
private void StartListen()
{
//Creating a TCP Connection and listening to the port
tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
tcpListener.Start();
toolStripStatusLabel1.Text = "Listening on port 6666 ...";
int counter = 0;
appStatus = 0;
while (true)
{
try
{
client = tcpListener.AcceptTcpClient();
counter++;
clientList.Add(client);
IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
//Updating status of connection
toolStripStatusLabel1.Text = "Connected from " + IPAddress.Parse(ipend.Address.ToString());
appStatus = 1;
th_outPutStream = new Thread(delegate () { outPutStream(client); });
th_outPutStream.Start();
th_inPutStream = new Thread(delegate () { inPutStream(client); });
th_inPutStream.Start();
th_checkConnection = new Thread(checkConnection);
th_checkConnection.Start();
}
catch (Exception err)
{
Cleanup();
}
}
}
private void checkConnection()
{
bool status = true;
while (status == true)
{
status = IsConnected();
if (status == true)
{
System.Threading.Thread.Sleep(3000); //Wait 3 seconds then try again
}
else
{
Cleanup();
}
}
}
private bool IsConnected()
{
try
{
return !(client.Client.Poll(1, SelectMode.SelectRead) && client.Client.Available == 0);
}
catch (SocketException) { Cleanup(); return false; }
}
I did this by simply creating a forloop for each client in my client list:
private void checkConnection()
{
bool status = true;
while (true)
{
for (int i = 0; i < clientList.Count; i++)
{
Debug.WriteLine(clientList.Count);
status = IsConnected(i);
if (status == true)
{
}
else
{
Cleanup(i);
}
}
System.Threading.Thread.Sleep(3000); //Wait 3 seconds then try again
}
}
private bool IsConnected(int i)
{
try
{
return !(clientList[i].Client.Poll(1, SelectMode.SelectRead) && clientList[i].Client.Available == 0);
}
catch (SocketException) { Cleanup_dep(); return false; }
}

async await in UWP windows 10 IOT core running in Raspberry Pi 3B and memory leak

First of all I am a complete begineer in C# and literally don't know how to use async/await/cancellation/Tasks, I come from a embedded systems background with basic-moderate C/C++ knowledge. So i just get the idea what those async functions do here. the async task codes are copied from samples from microsoft, they simply keep on reading the serial port for new bytes. I made some animations for the UI through Blend, and that's just it nothing more fancy.
This app runs on a raspberry with IOT core, and its sole job is to provide a UI for user to control a microcontroller with plain text instructions send through serial port. All these buttons simply send some strings to serial port which my microcontroller reads and acts accordingly.
Problem 1: I modified a line in the ReadAsync function uint ReadBufferLength = 1; the value was 128 in sample code, my microcontroller sends a complete instruction or data ending with "\r\n". This meant it will keep on reading bytes in serial that come from the microcontroller until the buffer is full and call the ReadAsync function again. since it was reading until the buffer (128) was full, multiple instructions come and fill the buffer. So i had no way to figure out what is the instruction in the buffer. So my work around here was to change the buffer to 1 and append a string with new bytes from serial port until it finds Environment.NewLine and then build logic based on the complete instruction in the string.
Question 1: How do I modify the code to not change the uint ReadBufferLength = 1; and make the ReadAsync function store my serial incoming data until it finds \r\n ?
MAJOR Problem 2: As soon as I enter Manual/Auto mode by clicking the front panel button, my microcontroller starts sending temperature sensor value through serial port as fast as possible without any delay between instructions. I know the raspberry pi (win10 iot core) is fast enough to not miss any instruction or the physical serial port buffer of the PI getting overfilled. It works fine, there is no problem at this point in the app, no crash or slowdowns. But overtime I can see that the app is consuming more and more RAM. the behavior is same in PC if I build it in x86 mode. after running it for 1 hour it will consume over 120 megabytes whereas it starts at 30-50 megabytes initially.
To recreate the problem, please change string qFilter = SerialDevice.GetDeviceSelector("UART0"); UART0 to appropriate com port in windows. otherwise the app will not run. Probably a Virtual COM port needs to be installed or a usb to ttl module might be required.
Problem 3: Cannot build the app in release mode using the option "Compile with .NET Native tool chain", without this it runs fine in the raspberry.
Internal compiler error: MCG0024:UnresolvableTypeReference Unresolvable type reference 'System.Runtime.InteropServices.WindowsRuntime.IRestrictedErrorInfo' in 'Assembly(Name=System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)' found. Please check the references in your build system. A reference is either missing or an assembly is missing an expected type. hvac_version_4
github project file
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.Devices.SerialCommunication;
using Windows.Storage.Streams;
using System.Threading;
using Windows.Devices.Enumeration;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;
using Microsoft.Toolkit.Uwp.UI.Animations.Behaviors;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace hvac_version_2
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
SolidColorBrush greenBrush = new SolidColorBrush(Colors.Green);
SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
SolidColorBrush greyBrush = new SolidColorBrush(Colors.DarkSlateGray);
//private bool updatingValues;
private CancellationTokenSource ReadCancellationTokenSource;
private SerialDevice serialPort = null;
DataWriter dataWriteObject = null;
DataReader dataReaderObject = null;
public string strFromPort;
private string final_string;
private int compressorAkey=0;
private int compressorBkey=0;
private int pump_entry = 0;
private int compAentry=0;
private int compBentry=0;
private int fan1entry = 0;
private int fan2entry = 0;
private double Blur_amount = 0;
public MainPage()
{
this.InitializeComponent();
stop_button.IsEnabled = false;
set_temperature.IsEnabled = false;
set_switching_time.IsEnabled = false;
auto_mode.IsEnabled = false;
manual_mode.IsEnabled = false;
compressorA_button.IsEnabled = false;
compressorB_button.IsEnabled = false;
fanA_button.IsEnabled = false;
fanB_button.IsEnabled = false;
init.IsEnabled = false;
init_timing.IsEnabled = false;
pump_button.IsEnabled = false;
load_animation.Begin();
}
private async void stop_button_Click(object sender, RoutedEventArgs e)
{
//do something
start_animation.Stop();
if (serialPort == null) return;
await sendToPort("end");
set_temperature.IsEnabled = false;
set_switching_time.IsEnabled = false;
manual_mode.IsEnabled = true;
auto_mode.IsEnabled = true;
stop_button.IsEnabled = false;
compressorA_button.IsEnabled = false;
compressorB_button.IsEnabled = false;
fanA_button.IsEnabled = false;
fanB_button.IsEnabled = false;
init.IsEnabled = false;
init_timing.IsEnabled = false;
pump_button.IsEnabled = false;
start_button.IsEnabled = true;
pump_entry = 0;
compAentry = 0;
compBentry = 0;
fan1entry = 0;
fan2entry = 0;
stop_animation.Begin();
start_button.Width = 162;
GC.Collect();
}
private async void set_temperature_changed(object sender, EventArgs e)
{
//System.Diagnostics.Debug.WriteLine("entered the async void set_temp.............");
}
private async void set_switching_time_value_changed(object sender, EventArgs e)
{
//System.Diagnostics.Debug.WriteLine("entered the async void switching time.............");
}
private async void manual_mode_Click(object sender, RoutedEventArgs e)
{
if (serialPort == null) return;
await sendToPort("manual");
auto_mode.IsEnabled = false;
manual_mode.IsEnabled = false;
stop_button.IsEnabled = true;
set_temperature.IsEnabled = true;
set_switching_time.IsEnabled = true;
pump_button.IsEnabled = true;
fanA_button.IsEnabled = true;
fanB_button.IsEnabled = true;
compressorA_button.IsEnabled = true;
compressorB_button.IsEnabled = true;
init.IsEnabled = true;
init_timing.IsEnabled = true;
}
private async void auto_mode_Click(object sender, RoutedEventArgs e)
{
set_switching_time.IsEnabled = true;
set_temperature.IsEnabled = true;
init.IsEnabled = true;
stop_button.IsEnabled = true;
init_timing.IsEnabled = true;
if (serialPort == null) return;
await sendToPort("auto");
}
private async void start_button_Click(object sender, RoutedEventArgs e)
{
stop_animation.Stop();
await sendToPort("ready");
auto_mode.IsEnabled = true;
manual_mode.IsEnabled = true;
start_button.IsEnabled = false;
start_animation.Begin();
System.Diagnostics.Debug.WriteLine("sending ready command");
}
private async void compressorA_button_Click(object sender, RoutedEventArgs e)
{
if (compAentry == 0)
{
if (serialPort == null) return;
await sendToPort("compressorAON"); //sending key
compAentry = 1;
}
else
{
if (serialPort == null) return;
await sendToPort("compressorAoff"); //sending key
compAentry = 0;
}
}
private async void compressorB_button_Click(object sender, RoutedEventArgs e)
{
if (compBentry == 0)
{
if (serialPort == null) return;
await sendToPort("compressorBON"); //sending key
compBentry = 1;
}
else
{
if (serialPort == null) return;
await sendToPort("compressorBoff"); //sending key
compBentry = 0;
}
}
private async void fanA_button_Click(object sender, RoutedEventArgs e)
{
if (fan1entry == 0)
{
if (serialPort == null) return;
await sendToPort("fan1on");
fan1entry = 1;
}
else
{
if (serialPort == null) return;
await sendToPort("fan1off");
fan1entry = 0;
}
}
private async void fanB_button_Click(object sender, RoutedEventArgs e)
{
if (fan2entry == 0)
{
if (serialPort == null) return;
await sendToPort("fan2on");
fan2entry = 1;
}
else
{
if (serialPort == null) return;
await sendToPort("fan2off");
fan2entry = 0;
}
}
private async void pump_button_Click(object sender, RoutedEventArgs e)
{
if (pump_entry == 0)
{
if (serialPort == null) return;
await sendToPort("pumpon");
pump_entry = 1;
}
else
{
if (serialPort == null) return;
await sendToPort("pumpoff");
pump_entry = 0;
}
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
string qFilter = SerialDevice.GetDeviceSelector("UART0");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);
if (devices.Any())
{
string deviceId = devices.First().Id;
await OpenPort(deviceId);
}
ReadCancellationTokenSource = new CancellationTokenSource();
while (true)
{
//System.Diagnostics.Debug.WriteLine("program came before await listen");
await Listen();
}
}
private async Task OpenPort(string deviceId)
{
serialPort = await SerialDevice.FromIdAsync(deviceId);
if (serialPort != null)
{
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(50);
serialPort.BaudRate = 115200;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
//Console.WriteLine("Serial port configured successfully");
//txtStatus.Text = "Serial port configured successfully";
}
}
private async Task Listen()
{
try
{
if (serialPort != null)
{
dataReaderObject = new DataReader(serialPort.InputStream);
await ReadAsync(ReadCancellationTokenSource.Token);
}
}
catch (Exception ex)
{
txtStatus.Text = ex.Message;
}
finally
{
if (dataReaderObject != null) // Cleanup once complete
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
}
}
private async Task ReadAsync(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1; // only when this buffer would be full next code would be executed
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken); // Create a task object
//string debug = dataReaderObject.ReadString(bytesRead2);
//System.Diagnostics.Debug.WriteLine("writing string debug"+ debug);
UInt32 bytesRead = await loadAsyncTask; // Launch the task and wait until buffer would be full
if (bytesRead > 0)
{
strFromPort = dataReaderObject.ReadString(bytesRead);
final_string = final_string + strFromPort;
//txtStatus2.Text = final_string;
if (final_string.Contains(Environment.NewLine))
{
string logicstring = final_string;
final_string = "";
//System.Diagnostics.Debug.WriteLine("writing logic string " + logicstring);
if (logicstring.StartsWith("A"))
{
if(logicstring.Contains("-"))
{
//it is a negative number
logicstring = Regex.Match(logicstring, #"\d+").Value;
int gauge1_pass = int.Parse(logicstring) * -1;
tempgauge1.Value = gauge1_pass;
}
else
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int gauge1_pass = int.Parse(logicstring);
tempgauge1.Value = gauge1_pass;
}
}
if (logicstring.StartsWith("B"))
{
if (logicstring.Contains("-"))
{
//it is a negative number
logicstring = Regex.Match(logicstring, #"\d+").Value;
int gauge2_pass = int.Parse(logicstring) * -1;
tempgauge1.Value = gauge2_pass;
}
else
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int gauge2_pass = int.Parse(logicstring);
tempgauge2.Value = gauge2_pass;
}
}
if (logicstring.StartsWith("setting"))
{
if (logicstring.Contains("-"))
{
//it is a negative number
logicstring = Regex.Match(logicstring, #"\d+").Value;
int previous_temp_setting = int.Parse(logicstring) * -1;
set_temperature.Value = previous_temp_setting;
}
else
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int previous_temp_setting = int.Parse(logicstring);
set_temperature.Value = previous_temp_setting;
}
}
if (logicstring.StartsWith("pumpon"))
{
pump_status_light.Fill = greenBrush;
Storyboard_Pump_Led.RepeatBehavior = RepeatBehavior.Forever;
Storyboard_Pump_Led.Begin();
}
if (logicstring.StartsWith("pumpoff"))
{
pump_status_light.Fill = redBrush;
Storyboard_Pump_Led.Stop();
}
if (logicstring.StartsWith("pumpfail"))
{
if (!FailPopup.IsOpen)
{
FailPopup.IsOpen = true;
}
}
if (logicstring.StartsWith("clear the popup"))
{
if (FailPopup.IsOpen)
{
FailPopup.IsOpen = false;
}
}
if (logicstring.StartsWith("switch_interval"))
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int previous_interval_setting = int.Parse(logicstring);
set_switching_time.Value = previous_interval_setting;
}
if (logicstring.StartsWith("timer"))
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int remaining_time = int.Parse(logicstring);
remaining_time = remaining_time / 1000;
timer_box.Text = remaining_time.ToString();
}
if (logicstring.StartsWith("Free RAM = "))
{
logicstring = Regex.Match(logicstring, #"\d+").Value;
int remaining_memory = int.Parse(logicstring);
free_memory.Text = remaining_memory.ToString();
}
if (logicstring.StartsWith("fan1on"))
{
fan1_status_light.Fill = greenBrush;
storyboard_fan1_led.RepeatBehavior = RepeatBehavior.Forever;
storyboard_fan1_led.Begin();
}
if (logicstring.StartsWith("fan1off"))
{
fan1_status_light.Fill = redBrush;
storyboard_fan1_led.Stop();
}
if (logicstring.StartsWith("fan2on"))
{
fan2_status_light.Fill = greenBrush;
storyboard_fan_2.RepeatBehavior = RepeatBehavior.Forever;
storyboard_fan_2.Begin();
}
if (logicstring.StartsWith("fan2off"))
{
fan2_status_light.Fill = redBrush;
storyboard_fan_2.Stop();
}
if (logicstring.StartsWith("compressorAON")) //key
{
compressorA_status_light.Fill = greyBrush;
compressorAkey = 1;
}
if (logicstring.StartsWith("compressorAoff")) //key
{
compressorA_status_light.Fill = redBrush;
compressorAkey = 0;
}
if (logicstring.StartsWith("compressorBON")) //key
{
compressorB_status_light.Fill = greyBrush;
compressorBkey = 1;
}
if (logicstring.StartsWith("compressorBoff")) //key
{
compressorB_status_light.Fill = redBrush;
compressorBkey = 0;
}
if (logicstring.StartsWith("compressorA on")) // actually compressor on
{
compressorA_status_light.Fill = greenBrush;
storyboard_compA_Led.RepeatBehavior = RepeatBehavior.Forever;
storyboard_compA_Led.Begin();
}
if (logicstring.StartsWith("compressorB on")) // actually compressor on
{
compressorB_status_light.Fill = greenBrush;
storyboard_compB_led.RepeatBehavior = RepeatBehavior.Forever;
storyboard_compB_led.Begin();
}
if (logicstring.StartsWith("compressor off")) // actually compressor off
{
if (compressorBkey == 1)
{
compressorB_status_light.Fill = greyBrush;
storyboard_compB_led.Stop();
}
if (compressorAkey == 1)
{
compressorA_status_light.Fill = greyBrush;
storyboard_compA_Led.Stop();
}
if (compressorBkey == 0)
{
compressorB_status_light.Fill = redBrush;
storyboard_compB_led.Stop();
}
if (compressorAkey == 0)
{
compressorA_status_light.Fill = redBrush;
storyboard_compA_Led.Stop();
}
}
if (logicstring.StartsWith("compressorA off")) // actually compressor off
{
compressorA_status_light.Fill = redBrush;
storyboard_compA_Led.Stop();
}
if (logicstring.StartsWith("compressorB off")) // actually compressor off
{
compressorB_status_light.Fill = redBrush;
storyboard_compB_led.Stop();
}
}
}
}
private async Task WriteAsync(string text2write)
{
Task<UInt32> storeAsyncTask;
if (text2write.Length != 0)
{
dataWriteObject.WriteString(text2write);
storeAsyncTask = dataWriteObject.StoreAsync().AsTask(); // Create a task object
UInt32 bytesWritten = await storeAsyncTask; // Launch the task and wait
if (bytesWritten > 0)
{
//txtStatus.Text = bytesWritten + " bytes written at " + DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern);
}
}
else { }
}
private async Task sendToPort(string sometext)
{
try
{
if (serialPort != null)
{
dataWriteObject = new DataWriter(serialPort.OutputStream);
await WriteAsync(sometext);
}
else { }
}
catch (Exception ex)
{
txtStatus.Text = ex.Message;
}
finally
{
if (dataWriteObject != null) // Cleanup once complete
{
dataWriteObject.DetachStream();
dataWriteObject = null;
}
}
}
private void CancelReadTask()
{
if (ReadCancellationTokenSource != null)
{
if (!ReadCancellationTokenSource.IsCancellationRequested)
{
ReadCancellationTokenSource.Cancel();
}
}
}
private void Page_Unloaded(object sender, RoutedEventArgs e)
{
CancelReadTask();
if (serialPort != null)
{
serialPort.Dispose();
}
serialPort = null;
}
private async void init_Click(object sender, RoutedEventArgs e)
{
double sendtempvalue = (double)set_temperature.Value;
if (serialPort == null) return;
await sendToPort("settemp," + sendtempvalue);
//System.Diagnostics.Debug.WriteLine("EEPROM " + sendtempvalue);
}
private async void init_timing_Click(object sender, RoutedEventArgs e)
{
double switching_time_minute = (double)set_switching_time.Value;
if (serialPort == null) return;
await sendToPort("switch_interval," + switching_time_minute);
//System.Diagnostics.Debug.WriteLine("EEPROM " + switching_time_minute);
}
/*
private void Page_Unloaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
}*/
}
}
Question 1: How do I modify the code to not change the uint
ReadBufferLength = 1; and make the ReadAsync function store my serial
incoming data until it finds \r\n ?
Please try to use following code. When using ReadBufferLength = 1, the transmission efficiency will be lower.
private async Task ReadAsync(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 128; // only when this buffer would be full next code would be executed
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken); // Create a task object
//string debug = dataReaderObject.ReadString(bytesRead2);
//System.Diagnostics.Debug.WriteLine("writing string debug"+ debug);
UInt32 bytesRead = await loadAsyncTask; // Launch the task and wait until buffer would be full
if (bytesRead > 0)
{
strFromPort = dataReaderObject.ReadString(bytesRead);
final_string = final_string + strFromPort;
//txtStatus2.Text = final_string;
if (final_string.Contains(Environment.NewLine))
{
string logicstring = final_string;
final_string = final_string.Substring(final_string.IndexOf(Environment.NewLine) + 1);
//System.Diagnostics.Debug.WriteLine("writing logic string " + logicstring);
}
}
}
Problem 2: after running it for 1 hour it will consume over 120
megabytes whereas it starts at 30-50 megabytes initially.
Please try to build the app in release but not using the .NET native toolchain.It's a known issue. Please see here.
Problem 3: Cannot build the app in release mode using the option
"Compile with .NET Native tool chain", without this it runs fine in
the raspberry.
Please remove the references runtime.win10-arm-aot.Microsoft.NETCore.UniversalWindowsPlatform and runtime.win10-arm.Microsoft.NETCore.UniversalWindowsPlatform in your project. The project will be compiled with .Net native tool chain successfully without the two libraries, since that these two libs depends on the native lib of System.Runtime.InteropServices.

My service doesn't change the wallpaper and I don't know why

I've created a service, which "locks" the desktop background, so you can't change it. In general, the service compares the current wallpaper with the one I want to be the new wallpaper. If it's not the same, it gets overwritten. This is my OnTimer()-Method, which gets executed every 2 seconds:
private void OnTimer(object sender, ElapsedEventArgs e)
{
if (!File.Exists("C:/Program Files/image.jpg"))
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream s = myAssembly.GetManifestResourceStream("MsService.Gandalf.jpg"); ;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
while (true)
{
try
{
File.WriteAllBytes("C:/Program Files/image.jpg", b);
break;
}
catch (Exception)
{
//stuff
}
}
}
//{path} is %Appdata%
if (!FileEquals($"{path}\\Microsoft\\Windows\\Themes\\TranscodedWallpaper", "C:/Program Files/image.jpg"))
{
byte[] file = File.ReadAllBytes("C:/Program Files/image.jpg");
while (true)
{
try
{
File.WriteAllBytes($"{path}\\Microsoft\\Windows\\Themes\\TranscodedWallpaper", file);
break;
}
catch (Exception)
{
//stuff
}
}
}
}
That's the FileEquals Method:
static bool FileEquals(string path1, string path2)
{
byte[] file1 = File.ReadAllBytes(path1);
byte[] file2 = File.ReadAllBytes(path2);
if (file1.Length == file2.Length)
{
for (int i = 0; i < file1.Length; i++)
{
if (file1[i] != file2[i])
{
return false;
}
}
return true;
}
return false;
}
When I start the service, It only changes the wallpaper if I change it actively, even if it already is another one that the one I want it to be, and only once. The service outputs no error when debugging, and the service doesn't crash. Also when I change the wallpaper, the breakpoints in the if(!File.Equals(...)) gets triggered. Virus scanner isn't alerting anything too. Why doesn't it work anyway?

application hangs when closing a listening port

I'm using com0com to create a part of virtual ports comA/comB, typing the input to comA from hyperterminal and listening on comB in a wpf application. When I run the following code (by triggering Connect), the application successfully connects and is able to get the data from comA, but hangs when I do Disconnect.
public void Connect()
{
readPort = new SerialPort("COMB");
readPort.WriteTimeout = 500;
readPort.Handshake = Handshake.None;
readPort.Open();
readThread = new Thread(Read);
readRunning = true;
readThread.Start();
System.Diagnostics.Debug.Print("connected");
}
public void Disconnect()
{
if (!readRunning)
{
readPort.Close();
}
else
{
readRunning = false;
readThread.Join();
readPort.Close();
}
System.Diagnostics.Debug.Print("disconnected");
}
public void Read()
{
while (readRunning)
{
try
{
int readData = 0;
readData = readPort.ReadByte();
System.Diagnostics.Debug.Print("message: " + readData.ToString());
}
catch (TimeoutException)
{
}
}
}
I tried changing the Read function to a write by using
byte[] writeData = { 1, 2, 3 };
readPort.Write(writeData, 0, 3);
instead of port.readbyte, and it starts working perfectly when disconnecting. Does anyone know if there is anything different about readbyte that could have caused the freeze? Or is it possibly related to com0com?
Just checking back, in case anyone runs into the same issue, I found an alternative way overriding SerialPort.DataReceived like this:
public override void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] buf = new byte[sp.BytesToRead];
sp.Read(buf, 0, buf.Length);
receivedDataDel(buf);
}

C# 32feet.Net: Handling two bluetooth connections in seperate threads, gives SocketException

I'm writing a C# console application using the 32feet.Net library that creates two threads to search for and connect to different Bluetooth devices and then open up TCP sockets so that data can be passed to the devices via a network connection. I know this situation sounds completely bizarre, but I've been asked to do this by a senior colleague.
My code seems to work OK with only one device connected, although the Bluetooth connection does sometimes drop out after a couple of messages have been passed backwards and forwards. However, sometimes as soon as the second device connects I get an error saying System.net.sockets.socketexception a connection attempt failed because the connected party did not properly respond, other times the code just exits without throwing any exceptions.
I was wondering what is causing this, I've seen that the 32feet.Net library can support multiple connections. I'm wondering if I've made some errors, as I'm new to C#, .Net, and even Windows, and have never written any Bluetooth based code before.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BluetoothManager
{
class Program
{
static void Main(string[] args)
{
BTManager rover_btm = new BTManager();
BTManager base_btm = new BTManager();
base_btm.Port = 0xba5e;
rover_btm.Port = 17825;
base_btm.Name = "Base";
rover_btm.Name = "Rover";
base_btm.match = (args.Length >= 1 && args[0] != "") ? args[0] : "dev1";
rover_btm.match = (args.Length >= 2 && args[1] != "") ? args[1] : "dev2";
Console.WriteLine("Base Station match: " + base_btm.match);
Console.WriteLine("Rover match: " + rover_btm.match);
Thread Base = new Thread(new ThreadStart(base_btm.HandleThread));
Thread Rover = new Thread(new ThreadStart(rover_btm.HandleThread));
Base.Start();
Rover.Start();
Base.Join();
Rover.Join();
Console.Read();
}
}
}
BTManager.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
using System.IO;
namespace BluetoothManager
{
class BTManager
{
private static BluetoothDeviceInfo[] peers;
private BluetoothClient client;
private bool _isConnected = false;
private string _match;
private const string defpin = "0000";
private TcpListener tcpListener;
private int _port;
private string _name = "Not Named";
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Port
{
get { return _port; }
set { _port = value; }
}
public bool IsConnected
{
get { return _isConnected; }
private set { _isConnected = value; }
}
public string match
{
get { return _match; }
set { _match = value; }
}
public BTManager()
{
client = new BluetoothClient();
}
public void HandleThread()
{
BluetoothDeviceInfo device;
while (!this.findDevice(out device)) ;
Console.WriteLine("About to pair");
int count = 0;
int max = 5;
while ((!(BluetoothSecurity.PairRequest(device.DeviceAddress, defpin))) && count < max)
{
Console.WriteLine("Pairing Failed, retrying");
count++;
Thread.Sleep(100);
}
if (count == max)
{
HandleThread();
}
else
{
Console.WriteLine("Paired..Beginning connect");
client.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, this.callback, client);
}
}
private void callback(IAsyncResult result)
{
client.EndConnect(result);
this.tcpListener = new TcpListener(IPAddress.Loopback, _port);
this.tcpListener.Start();
TcpClient TcpClient = this.tcpListener.AcceptTcpClient();
NetworkStream networkStream = TcpClient.GetStream();
Stream bluetoothStream = client.GetStream();
byte[] fromNetwork = new byte[1024];
byte[] fromBluetooth = new byte[1024];
while (client.Connected && TcpClient.Connected)
{
try
{
if (networkStream.CanRead)
{
Array.Clear(fromNetwork, 0, 1024);
networkStream.Read(fromNetwork, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
bluetoothStream.Write(fromNetwork, 0, 1024);
bluetoothStream.Flush();
while (bluetoothStream.CanRead)
{
Array.Clear(fromBluetooth, 0, 1024);
bluetoothStream.Read(fromBluetooth, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
networkStream.Write(fromBluetooth, 0, 1024);
networkStream.Flush();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
this.HandleThread();
}
private bool findDevice(out BluetoothDeviceInfo device)
{
peers = client.DiscoverDevicesInRange();
device = Array.Find(peers, element => element.DeviceName == match);
foreach (BluetoothDeviceInfo btdi in peers)
{
Console.WriteLine(btdi.DeviceName);
}
if (device == null)
{
Console.WriteLine(Name +": Not Found");
return false;
}
else
{
Console.WriteLine(Name +": Found");
return true;
}
}
}
}
I am using Sockets in order to communicate with the Bluetooth device.
Its very important to release any resources when disconnecting.
In order to find your COM port you can use this link
Your stream is located here:
System.Net.Sockets.NetworkStream stream = bthClient.GetStream();
Example to how to connect and find your device.
private InTheHand.Net.Sockets.BluetoothClient _BTClient = null;
private InTheHand.Net.Sockets.BluetoothDeviceInfo[] _clientDevices;
/// <summary>
/// Thread function to discover devices
/// </summary>
private void DiscoverBluetoothThread()
{
try
{
_BTClient = new InTheHand.Net.Sockets.BluetoothClient();
_clientDevices = _BTClient.DiscoverDevices(999, _authenticated, _remembered, _unknown);
_BTClient.Dispose();
_BTClient = null;
}
catch (Exception) { }
}
Private void Connect(InTheHand.Net.Sockets.BluetoothDeviceInfo info)
{
string addressN = info.DeviceAddress.ToString("N"); //Format Example: "00066606E014"
string addressC = info.DeviceAddress.ToString("C"); //Format Example: "00:06:66:06:E0:14"
string addressP = info.DeviceAddress.ToString("P"); //Format Example: "00.06.66.06.E0.14"
string addressD = info.DeviceAddress.ToString(); //Format Example: "00066606E014"
string serialPort = FindBluetoothPortName(addressN);
//https://stackoverflow.com/questions/26439091/how-to-get-bluetooth-device-com-serial-port-in-winform-c/27919129#27919129
if (string.IsNullOrEmpty(serialPort) == false && serialPort.Trim().Length > "COM".Length)
bool installed = InstallBluetoothDevice(addressC, passKey, autoConnect);
}
public bool InstallBluetoothDevice(string deviceMACAddress, string passKey, bool connect)
{
string strDevicePassKey = passKey;
string BTMac = deviceMACAddress;
InTheHand.Net.BluetoothAddress BTAddress;
InTheHand.Net.Sockets.BluetoothClient BTClient = new InTheHand.Net.Sockets.BluetoothClient();
InTheHand.Net.BluetoothEndPoint BTEndPoint;
InTheHand.Net.Bluetooth.BluetoothRadio BTRadio;
BTRadio = InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio;
BTRadio.Mode = RadioMode.Connectable;
Guid spguid = BluetoothService.SerialPort;
BTAddress = InTheHand.Net.BluetoothAddress.Parse(BTMac);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
try
{
BluetoothSecurity.PairRequest(BTAddress, strDevicePassKey);
//Application.DoEvents();
BTClient = new InTheHand.Net.Sockets.BluetoothClient();
if (connect)
{
BTClient.Connect(BTEndPoint);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
_connectedDevices.Add(BTAddress, BTClient);
return BTClient.Connected;
}
return true;
}
catch (Exception ex)
{
return false;
}
}

Categories