I got myself some Kit-Starter code from google uploaded by someone else.
I hooked on my USB-Serial Cable and set my COM port to COM1.
When i build and ran it , it gave me error on this line, im not sure what's happening.
private int parseLGResponseHexa(string resp) {
var splitter = new string[1];
splitter[0] = "OK";
String[] partes = resp.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
String naco = partes[1];
String num = naco.Substring(0, 2);
int decAgain = int.Parse(num, NumberStyles.HexNumber);
return decAgain;
}
Error At "String Naco = partes[1];"
Related
I am trying to do a tx(pc)-rx(arduino), tx(arduino)-rx(pc) connection, sending a string "Hello World!:)" from the client in xamarin.forms, in order to receive the same string decoded from serial port with BLE. At the moment I send the string, it works well, due to the fact that I see perfectly the string on Serial Monitor of arduino, but when decoded, the string is not the same as the sended.
Codes:
Arduino:
void loop(){
if (BT.available() > 0 ){
c = BT.readString();
str_len = c.length() +1;
char char_array[str_len];
c.toCharArray(char_array, str_len);
int i = 0;
while(i<str_len){
char_array_aux[i] = char_array[i];
i++;
}
char_array_aux[str_len] = "\n";
}
int i = 0;
while(i<str_len){
if(char_array_aux[i] == "\n")
BT.end();
BT.print(char_array_aux[i]);
i++;
}
}
Xamarin.forms app send/receive message function:
public async Task sendAndReceiveString()
{
//Guid characteristics = Id {0000ffe1-0000-1000-8000-00805f9b34fb} System.Guid
//Guid services = Id {0000ffe0-0000-1000-8000-00805f9b34fb} System.Guid
var stringToSend = "Hello World! :)";
var services = await deviceConn.GetServicesAsync();
IService service = services[0];
var characteristics = await service.GetCharacteristicsAsync();
var characteristic = characteristics[0];
try
{
//Write message
byte[] bytes = Encoding.ASCII.GetBytes(stringToSend);
await characteristic.WriteAsync(bytes);
//Read Message
byte[] answ = await characteristic.ReadAsync();
string answ_str = Encoding.ASCII.GetString(answ);
msgSended = "Message sended:" + stringToSend;
msgReceived = "Message received: " + answ_str;
}
Debug log:
Sended string: Hello world! :)
Received string: Hello world! :)
Hello world! :)
He
I do not know how to work properly with bluetooth buffer. If anybody knows, let me know it please.
Thank you in advance.
Regards,
Raúl.
I just fixed it! I just used BT.readStringUntil("\n"); instead of readString()
and buffer does not overflow.
I have a problem with my code, it works really slow
My Code:
private static void PortRangeScan()
{
Console.Clear();
var From = FROM.Split('.'); // example (103.218.27.85)
string From1 = From[0];
string From2 = From[1];
string From3 = From[2];
string From4 = From[3];
var To = TO.Split('.'); // example (123.218.27.85)
string To1 = To[0];
string To2 = To[1];
string To3 = To[2];
string To4 = To[3];
for (int CurrentProxy = int.Parse(From1); CurrentProxy <= int.Parse(To1); CurrentProxy++)
{
foreach (int s in Ports)
{
TcpClient Scan = new TcpClient();
try
{
// If there is no exception then the Port is open
Scan.Connect($"{CurrentProxy}.{From2}.{From3}.{From4}", s);
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | OPEN", Color.Green);
}
catch
{
// If there is an excpetion then it means the Port is closed
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | CLOSED", Color.Red);
}
}
}
}
this code works really slow, if the port is closed, it can take up to 10 seconds until it checks the next port.
I wanted to add a Parallel.For loop or multi-threading but I am not sure how I can do it with this code.
so what do I need:
how can I make this code much faster or how can I add multi-threading
You could use the System.Net.Network Information namespace. Specifically the IPGlobal properties class. It can be used to return a full list of the currently used ports.
Sorry for the formatting. I am on mobile, but here is an example.
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (var tcpi in tcpConnInfoArray)
{
Console.Write($"Port {tcpi.LocalEndPoint.Port} is in use.");
}
I found this C# code for simple IP net scanner which scans the connected hosts in the network and displays its physical address and IP address.It works well but only when connected with the network via WIFI. It doesn't work when connected through the network via wires.
[DllImport("iphlpapi.dll", ExactSpelling = true)]
At first, iphlpapi.dll has been imported. So, can you explain it? the rest of the code is given below.
// Use Your work Group WinNT://&&&&(Work Group Name)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + this.TxtWorkGroup.Text.Trim());
DomainEntry.Children.SchemaFilter.Add("computer");
// To Get all the System names And Display with the Ip Address
foreach (DirectoryEntry machine in DomainEntry.Children)
{
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;
System.Net.IPHostEntry Tempaddr = null;
try
{
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(machine.Name);
}
catch (Exception)
{
MessageBox.Show("Unable to connect with the system :" + machine.Name);
continue;
}
IPAddress[] TempAd = Tempaddr.AddressList;
foreach (IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();
byte[] ab = new byte[6];
int len = ab.Length;
// This Function Used to Get The Physical Address
int r = SendARP((int)TempA.Address, 0, ab, ref len);
string mac = BitConverter.ToString(ab, 0, 6);
Ipaddr[2] = mac;
}
ListViewItem TempItem = new ListViewItem(Ipaddr);
this.ListHostIP.Items.Add(TempItem);
}
}
Turn off the WIFI adapter and try it again.
We have a solution running on WM 6.5 that connects to our servers but one of our customers has frequent problems where our software loses its gprs connection and is unable to get a new one until the phone is rebooted.
We know that the phone is in a gprs area as we are able to remote desktop into the phone and browse using internet explorer. Our logs show that although we have specified a 2 minute time out, ConnMgrEstablishConnectionSync returns with a waitingForConnection status. Does anybody have any ideas what could be going wrong? eg Is it possible that some 3rd party software is stealing our connection?
Many Thanks.
private void Connect()
{
if (_connectionHandle != IntPtr.Zero)
{
EventLog.AddLogEntry(LogSeverity.Trace, "connmgr - current handle was:" + _connectionHandle);
CloseConnection();
}
const int connectionTimeout = 120000;
const int CONNMGR_PARAM_GUIDDESTNET = 1;
const int CONNMGR_PRIORITY_USERINTERACTIVE = 0x8000;
const int CONNMGR_FLAG_SUSPEND_AWARE = 0x10; // suspended connections supported
const int CONNMGR_FLAG_NO_ERROR_MSGS = 0x40; // don't show any error messages for failed connections
const int CONNMGR_proxies = 0x3;
const string testUrl = "http://www.bbc.co.uk";
ConnectionInfo info = new ConnectionInfo();
info.cbSize = (uint)Marshal.SizeOf(info);
info.bExclusive = 0;
info.dwFlags = CONNMGR_proxies | CONNMGR_FLAG_NO_ERROR_MSGS | CONNMGR_FLAG_SUSPEND_AWARE;
info.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
Guid networkGuid = Guid.Empty;
int hResult = MobileNativeMethods.ConnMgrMapURL(testUrl, ref networkGuid, IntPtr.Zero);
if (hResult != 0)
{
EventLog.AddLogEntry(LogSeverity.Trace, "<<Dllimport - ConnMgrMapURL (error) " + hResult.ToString());
throw new ConnectionUnavailableException("Unable to open connection");
}
info.guidDestNet = networkGuid;
info.dwParams = CONNMGR_PARAM_GUIDDESTNET;
uint status = 0;
hResult = MobileNativeMethods.ConnMgrEstablishConnectionSync(ref info, out _connectionHandle, (uint)connectionTimeout, out status);
if (hResult != 0)
{
EventLog.AddLogEntry(LogSeverity.Trace, "<<Dllimport - ConnMgrEstablishConnectionSync (error) " + networkGuid.ToString());
throw new ConnectionUnavailableException("Unable to open connection: " + (ConnectionStatus) status);
}
EventLog.AddLogEntry(LogSeverity.Trace, "<<Dllimport - ConnMgrMapURL Connection OK");
}
In the end I found out that setting the AlwaysOn setting in the registry to false fixed the issue. I suspect that there is a deeper problem with Honeywell devices and this setting as Motorola devices seemed to work fine regardless of its value.
I've been trying to find a way to figure out which installed printers are 'connected'. After some Googling I figured I had to dive into WMI.
So I've built this test:
// Struct to store printer data in.
public struct MyPrinter
{
public string Availability;
public string ExtendedPrinterStatus;
public string Name;
public string PrinterStatus;
public string Status;
public string StatusInfo;
public MyPrinter(string a, string eps, string n, string ps, string s, string si)
{
Availability = a;
ExtendedPrinterStatus = eps;
Name = n;
PrinterStatus = ps;
Status = s;
StatusInfo = si;
}
}
var installedPrinters = new string[numPrinters];
PrinterSettings.InstalledPrinters.CopyTo(installedPrinters, 0);
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
var data = new List<MyPrinter>();
foreach (var printer in searcher.Get())
{
if (installedPrinters.Contains(printer["Name"].ToString()))
{
var availability = (printer["Availability"] ?? "").ToString();
var extendedPrinterStatus = (printer["ExtendedPrinterStatus"] ?? "").ToString();
var name = (printer["Name"] ?? "").ToString();
var printerStatus = (printer["PrinterStatus"] ?? "").ToString();
var status = (printer["Status"] ?? "").ToString();
var statusInfo = (printer["StatusInfo"] ?? "").ToString();
data.Add(new MyPrinter(availability, extendedPrinterStatus, name, printerStatus, status, statusInfo));
}
}
I have 6 printers from which 2 are network printers. I've run this with all printers connected and all results looked like this:
Availability = "" // printer["Availability"] = null
ExtendedPrinterStatus = "2" // 2 = Unknown
Name = "{printer name here}"
PrinterStatus = "3" // 3 = Idle
Status = "Unknown"
StatusInfo = "" // Null
So the only difference between the printers is the name.
I ran the script again but this time I disconnected my laptop from the network. So 2 of the printers were not connected anymore in this case.
The strange thing (for me) is, the results were exactly the same.
The reason I ran this test is, to figure out which field I'd need to use for my case.
So at the end, I have not been able to figure out how to figure out if a printer is connected or not.
So what I'd like, is a way to figure out the installed + connected printers in C#. If there is a way to do it without the use of WMI classes, that's also fine by me, as long as it works.
Me and a colleague have tried lots of stuff to find a solution for this and we figured this worked:
private string[] GetAvailablePrinters()
{
var installedPrinters = new string[PrinterSettings.InstalledPrinters.Count];
PrinterSettings.InstalledPrinters.CopyTo(installedPrinters, 0);
var printers = new List<string>();
var printServers = new List<string>();
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
foreach (var printer in searcher.Get())
{
var serverName = #"\\" + printer["SystemName"].ToString().TrimStart('\\');
if (!printServers.Contains(serverName))
printServers.Add(serverName);
}
foreach (var printServer in printServers)
{
var server = new PrintServer(printServer);
try
{
var queues = server.GetPrintQueues();
printers.AddRange(queues.Select(q => q.Name));
}
catch (Exception)
{
// Handle exception correctly
}
}
return printers.ToArray();
}
The trick is that when a printserver is not available, GetPrintQueues will throw some specific exception. By only adding the printers that don't throw such an exception, we get a list of all the connected printers. This doesn't check if a printer is turned on/off because that actually doesn't matter. If it is turned off, the document will just be placed in the print queue and it can be printed later on.
I hope this helps others who bump into this problem.
Sidenote:
The reason I decided not to catch that specific exception, is because I would have to reference a dll just for that exception.