Cognex creating own application from scratch - c#

what do they mean about
port.DtrEnable = true,
https://support.cognex.com/docs/dmst_616SR1/web/EN/Comms_Prog_Manual/Content/Topics/PDF/DMCAP/DMCCApplicationDevelopment.htm
Where do I put this code on the sample code?

You are probably working with COM ports.
you need import
using System.IO.Ports;
And when you create a SerialPort you should set the property
var serialPort = new SerialPort();
serialPort.DtrEnable = true;

Related

safe handle has been closed - numerous options to fix

I have a private function that creates a new serial port and opens it. From time to time, I get the "Safe handle has been closed" exception, that terminates the application. Now, I've been reading a few optional fixes and would like to know from your experience, what may be the real problem in my code.
1) Need to define the _serialPort variable outside of the scope of this private function.
2) The serial port's readTimeout property should not be infinite.
3) The using statement above disposes my portName variable.
SerialPort _serialPort;
string[] devices =
ConfigurationManager.AppSettings["GasAnalyzerDeviceName"].Split(',');
string portName;
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"))
{
portName = (from p in searcher.Get().Cast<ManagementBaseObject>()
let c = "" + p["Caption"]
where c != null
where devices.Any(d => c.Contains(d.Trim()))
from pn in SerialPort.GetPortNames()
where c.Contains(pn)
select pn).FirstOrDefault();
}
if (portName == null)
portName = ConfigurationManager.AppSettings["GasAnalyzerPortName"];
if (portName == null)
throw new Exception("Gas port not found");
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Set Serial port properties
_serialPort.PortName = portName;
_serialPort.BaudRate = 115200;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = Timeout.Infinite;//1200;
_serialPort.WriteTimeout = 1200;
Thanks!
I think you can discard options 2) and 3).
Number one is a possible candidate, but there is not enough code to be sure: If there are no other references to your SerialPort it becomes a candidate for garbage collection. Once it is garbage collected, any attempt to access it will result in an exception, tough I would expect a NullReferenceException.
There can be another cause: if your serial port is emulated over e.g. a USB device, and that device gets removed while your application is running, the underlying connection will be disposed.
When you try to use the SerialPort in your application after that has happened, you will get the 'safe handle has been closed' exception.

getting wrong data from USB Communication in C#

I am using microcontroller to send data to computer. This is the code that I am using to get data:
serialPort1.PortName = "COM13";
serialPort1.BaudRate = 57600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.Odd;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
output += sp.ReadByte() + " ";
}
But the problem is that I am getting wrong data, even sometimes I am missing one bytes. I am using "terminal" and it seems that I am sending data correctly with microcontroller but with c# I am getting wrong data.
Also is there any way to get the parameter of serial port automatically so that I dont need to set the parameters my self.

Can we create our own process in C#?

I need to create 3 processes in 1 program to simulate deadlock. How can I define my own process? I don't want to simply open an existing process.
For example for a thread:
Thread X = new Thread(){ //insert whatever code here// };
How can we do this for a process, like:
Process P = new Process(){//insert different threads here//};
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Process process = new Process();
process.StartInfo.FileName = "notepad";
//process.StartInfo.Arguments = "filename.txt"
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
}
}
}
Processes come from executable files.
You can write Process.Start(#"C:\Something.exe").
You probably looking for Process.Start (either static or instance method) - which will create new process by launching executable of your choice.
If you looking for implementation of fork from Unix you can't really do that in .Net to my knowledge.
Code in one process cannot be executed in another process. You need some form of inter-process communication, or remote procedure call.

Trouble Accessing com port in c#

I'm trying to read and write to a usb modem that is using the com port 3 with this code.
SerialPort sp = new SerialPort();
sp.PortName = "COM3";
//sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.Open();
sp.Write("AT<CR>");
byte[] bytes = new byte[sp.BytesToRead];
sp.Read(bytes, 0, sp.BytesToRead);
textBox1.Text = Encoding.UTF8.GetString(bytes);
But I get this error :
Access to the port 'COM3' is denied.
Someone have an idea ...
Thanks
You can only open the port once. Maybe you're accidentally opening it more than once within your code or another program is using it?

Redirecting standard input/output/error streams with .NET's Process class

I'm trying to write a wrapper for an interactive console-based application. For this I use C# and the Process class. I'm trying to redirect stdin/out/err, but it doesn't work.
Example code:
ProcessStartInfo startInfo = new ProcessStartInfo("admin.exe");
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
Process process = Process.Start(startInfo);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
while (true)
{
process.StandardInput.Write("uptime" + Environment.NewLine);
process.StandardInput.Flush();
Thread.Sleep(1000);
}
Console.ReadKey();
Nothing happens. But if I start admin.exe and write uptime, output is printed.
All solutions in the internet use ReadToEnd, but I can't use this because i have a dynamic communication on which I have to read stdout/err and write to stdin.
Has anyone an idea?
Update
I played with the posted zip on the linked thread. And then i tried to create a small 'proof-of-concept'-code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace ConsoleApplication3
{
class Program
{
private static void Read(StreamReader reader)
{
new Thread(() =>
{
while (true)
{
int current;
while ((current = reader.Read()) >= 0)
Console.Write((char)current);
}
}).Start();
}
static void Main(string[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo(#"cmd.exe");
startInfo.CreateNoWindow = true;
startInfo.ErrorDialog = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
Read(process.StandardOutput);
Read(process.StandardError);
while (true)
process.StandardInput.WriteLine(Console.ReadLine());
}
}
}
It works perfectly:-)
But with the admin.exe it doesn't work? The admin.exe doesn't use any tricky input-method and it doesn't need an inputed password.
I know the admin.exe is written in c and compiled with mingw on linux. So i created a small dummy-tool:
#include <stdio.h>
int main() {
int readed;
while ((readed = fgetc(stdin)) >= 0)
fputc((char)readed, stdout);
}
This tool does only echo the inputed text/line. I compiled it with i586-mingw32msvc-gcc and copied it to my windows machine. There i used the program on the top of this post to communicate with the dummy.exe. It doesn't work. No echo is shown. But why?
I compiled the dummy-code also with the Microsoft C++ Compiler, same effect.
Update2
(btw: Thanks to Tim Post)
I'm trying and trying. I tried to create a c-Tool, which does the same as my c# tool. I used _popen, but the effect was, that the output were shown at the end of the process. Hm, not good.
I found this alternative command shell for windows:
https://stackoverflow.com/questions/440269/whats-a-good-alternative-windows-console
http://sourceforge.net/projects/console/
It seems to work. It gets the stdout/err in realtime, can redirect the stdin and admin.exe works. And it is opensource. May be i'll find the solution inside the C++-Code.
I'm not well in C++, so it's hard, but i'll try it. May be i have to write a "clear" redirect-wrapper in C/C++ and use it in C#.
If someone has an idea please say it, because the other way can be very hard (for me^^):-)
Thanks.
best regards
Update 3
Hm, i think this happens because the child-process (admin.exe) uses a few threads...
But how to solve it?
The problem could be because of you are using Readline, where the data are output from admin.exe application are sequentially and not in new lines.., try to use Read instead, and build the desirable string from it..
Also you don't have to use Environment.NewLine to write string followed by new line, use WriteLine instead, so:
process.StandardInput.WriteLine("uptime");

Categories

Resources