Pole display problem in c# - c#

I used pole display(E POS) in my POS c# application.I have two major problem in that,
1. I can't clear the display perfectly.
2. I can't set the cursor position.
I used some dirty tricks to do these.But I am not satisfied with that code.The following code i used.
Code :-
class PoleDisplay : SerialPort
{
private SerialPort srPort = null;
public PoleDisplay()
{
try
{
srPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
if (!srPort.IsOpen) srPort.Open();
}
catch { }
}
~PoleDisplay()
{
srPort.Close();
}
//To clear Display.....
public void ClearDisplay()
{
srPort.Write(" ");
srPort.WriteLine(" ");
}
//Display Function
//'line' 1 for First line and 0 For second line
public void Display(string textToDisplay, int line)
{
if (line == 0)
srPort.Write(textToDisplay);
else
srPort.WriteLine(textToDisplay);
}
}

Your problem is that you are calling Write to clear line 1, and WriteLine to clear line 2.
This doesn't make any sense. The only difference between the methods is that WriteLine adds a linebreak to the end. All you are really doing is this outputting this string:
" "\r\n
Without knowing the brand of the pole display you are using, I can't tell you the proper way to do it, but the way you are trying to do it will never work. Most terminals accept special character codes to move the cursor, or clear the display. Have you found a reference for the terminal you are working with? Most displays will clear if you send them CHR(12).
All that aside, there is a major problem with your class design. You should never rely on destructors to free resources in C#.
In C#, the destructor will be called when the garbage collector collects the object, so there is no deterministic way to know when the resource (in this case a Com port), will be collected and closed.
Instead, implement the interface IDisposable on your class.
This requires you to add a Dispose method to your class. This would serve the same purpose as your current destructor.
By doing that, you can utilize a built in language feature in C# to release your resources when the object goes out of scope.
using (PoleDisplay p = new PoleDisplay())
{
// Do Stuff with p
}
// When the focus has left the using block, Dispose() will be called on p.

Send hex code 0C to clear the screen, it works for most displays
here is a code sample:
byte[] bytesToSend = new byte[1] { 0x0C }; // send hex code 0C to clear screen
srPort.Write(bytesToSend, 0, 1);

Related

MessageBox and while loop C#

I'm modifying existing C# code in order to pilote a piston. Every 30ms, I have a direct feedback of the position of this piston, through an event. The value is stored in a global variable I use to get the current position of the piston.
What I'm trying to achieve: for a given distance input (A->C), I want the piston to travel at full speed for 95% of the distance (A->B), and then slower for the remaining 5% (B->C).
I have access to a command that defines the speed and the destination of the piston : pos(velocity, destination).
However, if I write that code:
pos(fullSpeed,B);
pos(reducedSpeed, C);
the piston directly goes from fullSpeed to reducedSpeed
I tried to use a while loop to compare the current position of the piston with the goal destination, however, upon entering the while loop, the variable storing the piston position does not update anymore.
However, I noticed that by throwing a MessageBox in between, the position value keeps on getting updated, and I can simply click "ok" to launch the second command.
pos(fullSpeed,B);
MessageBox.show("Wait");
pos(reducedSpeed, C);
I would like to know why the "while" loop stops the update of the position variable but the MessageBox does not. I mean, as long as I don't click the "ok" button, the box is here preventing me from doing anything, which for me ressembles a while loop behaviour. Is there another way for me to do this instead of the MessageBox ?
I have little to no knowledge when it comes to C# and no support. I have tried to look in the documentation, but I did not find an answer (I have probably missed it). Any lead is more than welcome.
EDIT: I have no documentation for that code, and it is barely commented. Here is what I gathered (really hope it helps):
To move the piston, taht function is called:
MyEdc.Move.Pos(control, speed, destination, ref MyTan);
control simply define what we pilote (a distance or a load, it is an enum), and I have no idea what MyTan does. Only thing I know is that the MyEdc.Move.Pos returns an error code.
If I look at the definition of "pos", I am redirected to class
public DoPEmove Move;
containing among other things:
public DoPE.ERR Pos(DoPE.CTRL MoveCtrl, double Speed, double Destination, ref short Tan);
DoPE.ERR is also an type enum. However, I cannot reach the definition of a function named "Pos". Coud it be within the .dll included ?
The following is the code that allows me to access the position of the piston (without the global variables):
private int OnData(ref DoPE.OnData Data, object Parameter)
{
if (Data.DoPError == DoPE.ERR.NOERROR)
{
DoPE.Data Sample = Data.Data;
Int32 Time = Environment.TickCount;
if ((Time - LastTime) >= 300 /*ms*/)
{
LastTime = Time;
string text;
text = String.Format("{0}", Sample.Time.ToString("0.000"));
guiTime.Text = text;
text = String.Format("{0}", Sample.Sensor[(int)DoPE.SENSOR.SENSOR_S].ToString("0.000"));
guiPosition.Text = text;
text = String.Format("{0}", Sample.Sensor[(int)DoPE.SENSOR.SENSOR_F].ToString("0.000"));
guiLoad.Text = text;
text = String.Format("{0}", Sample.Sensor[(int)DoPE.SENSOR.SENSOR_E].ToString("0.000"));
guiExtension.Text = text;
}
}
return 0;
}
Which is called using
MyEdc.Eh.OnDataHdlr += new DoPE.OnDataHdlr(OnData);
I realise how little I know on how the soft operates, and how frustrating this is for you. If you think this is a lost cause, no problem, I'll try Timothy Jannace solution, and if it does not help me, I'll stick with the MessageBox solution. I just wanted to know why the MessageBox allowed me to sort of achieve my objectif, but the while loop did not, and how to use it in my advantage here.
I tried to use a while loop to compare the current position of the
piston with the goal destination, however, upon entering the while
loop, the variable storing the piston position does not update
anymore.
While you are in the while loop, your app can no longer receive and process the feedback event.
One possible solution would be to use async/await like this:
private const int fullSpeed = 1;
private const int reducedSpeed = 2;
private int currentPistonPositon = 0; // global var updated by event as you described
private async void button1_Click(object sender, EventArgs e)
{
int B = 50;
int C = 75;
pos(fullSpeed, B);
await Task.Run(() =>
{ // pick one below?
// assumes that "B" and "currentPistonPosition" can actually be EXACTLY the same value
while (currentPistonPositon != B)
{
System.Threading.Thread.Sleep(25);
}
// if this isn't the case, then perhaps when it reaches a certain threshold distance?
while (Math.Abs(currentPistonPositon - B) > 0.10)
{
System.Threading.Thread.Sleep(25);
}
});
pos(reducedSpeed, C);
}
Note the button1_Click method signature has been marked with async. The code will wait for the while loop inside the task to complete while still processing event messages because of the await. Only then will it move on to the second pos() call.
Thank you for your answer ! It works like a charm ! (good catch on the
EXACT value). I learnt a lot, and I am sure the async/await combo is
going to be very usefull in the future ! – MaximeS
If that worked well, then you might want to consider refactoring the code and making your own "goto position" method like this:
private void button1_Click(object sender, EventArgs e)
{
int B = 50;
int C = 75;
GotoPosition(fullSpeed, B);
GotoPosition(reducedSpeed, C);
}
private async void GotoPosition(int speed, int position)
{
pos(speed, position);
await Task.Run(() =>
{
while (Math.Abs(currentPistonPositon - position) > 0.10)
{
System.Threading.Thread.Sleep(25);
}
});
}
Readability would be greatly improved.
You could even get fancier and introduce a timeout concept into the while loop. Now your code could do something like below:
private void button1_Click(object sender, EventArgs e)
{
int B = 50;
int C = 75;
if (GotoPosition(fullSpeed, B, TimeSpan.FromMilliseconds(750)).Result)
{
if (GotoPosition(reducedSpeed, C, TimeSpan.FromMilliseconds(1500)).Result)
{
// ... we successfully went to B at fullSpeed, then to C at reducedSpeed ...
}
else
{
MessageBox.Show("Piston Timed Out");
}
}
else
{
MessageBox.Show("Piston Timed Out");
}
}
private async Task<bool> GotoPosition(int speed, int position, TimeSpan timeOut)
{
pos(speed, position); // call the async API
// wait for the position to be reached, or the timeout to occur
bool success = true; // assume we have succeeded until proven otherwise
DateTime dt = DateTime.Now.Add(timeOut); // set our timeout DateTime in the future
await Task.Run(() =>
{
System.Threading.Thread.Sleep(50); // give the piston a chance to update maybe once before checking?
while (Math.Abs(currentPistonPositon - position) > 0.10) // see if the piston has reached our target position
{
if (DateTime.Now > dt) // did we move past our timeout DateTime?
{
success = false;
break;
}
System.Threading.Thread.Sleep(25); // very small sleep to reduce CPU usage
}
});
return success;
}
If you're using events you are probably having concurrency issues. Especially with events being raised every 30ms!
A very simple way to handle concurrency is to use a lock object to prevent different threads from using contested resources simultaneously:
class MyEventHandler
{
private object _lockObject;
MyEventHandler()
{
_lockObject = new object();
}
public int MyContestedResource { get; }
public void HandleEvent( object sender, MyEvent event )
{
lock ( _lockObject )
{
// do stuff with event here
MyContestedResource++;
}
}
}
Keep in mind that is very simple and by no means perfect in every scenario. If you provide more information about how the events are raised and what you're doing with them people will be able to provide more help.
EDIT:
Using that signature you posted for the Pos method I was able to find documentation on the library you are using: https://www.academia.edu/24938060/Do_PE
The reason you only see the method signature when you goto definition is because the library has been compiled into a dll. Actually, it probably wouldn't be that useful to see the code anyway because it looks like the library is a C# wrapper around native (c or c++) code.
Anyways, I hope the documentation is helpful to you. If you look at page 20 there are some pointers on doing movement. This is going to be a challenge for a new programmer but you can do it. I would suggest you avoid using the event handler to drive your logic and instead stick with using the synchronous versions of commands. Using the synchronous commands your code should operate the same way it reads.
I believe what you'll want to do is add a call to:
Application.DoEvents();
This will allow your application to process posted messages (events), which will allow that global variable to be updated.
I just wanted to know why the MessageBox allowed me to sort of achieve my objectif, but the while loop did not, and how to use it in my advantage here.
The reason that works is because you're giving the WndProc a chance to process events which have been sent to the application. It's not an intended feature of that call to MessageBox.Show();, but it is a consequence. You can do the same thing with a call to Application.DoEvents(); without the interruption of the message box.

C# Continuously / uninterrupted reading data (from third party SDK)

Intro:
I am developing software that uses motion trackers to analyse human motor systems. Currently I am implementing hardware from xsens and using their SDK to receive data from their wireless sensors.
The SDK offers a COM interface with a "getData" method which you call to receive the currently available xyz axis data (simplified). If you do not call getData, you skip that "beat" so you will be missing data, there is no caching in their hardware/SDK.
Problem:
My problem is that I need to get data at a rate of at least 75Hz, preferably a bit more, but 75 would be acceptable, but I am currently quickly dropping to just 20 signals per second...
If I remove the processing bit (see the sample below) I get perfect sample rates, so I think either the dequeue is causing the enqueue to pause. Or the "heavy" CPU load is causing all threads to wait. I have no idea how to figure out what is actually causing it, the profiler (EQATEC) just shows my "GetData" method is taking longer after a while.
Question:
What is the best technique to use to accomplish this? Why would my "reading" thread be interrupted/blocked? There must be more cases where people need to read from something without being interrupted, but I have been Googleing for 2 weeks now and apparently I can't find the correct words.
Please advise.
Thanks
Simplified code sample, version 4, using a MultiMedia timer (http://www.codeproject.com/Articles/5501/The-Multimedia-Timer-for-the-NET-Framework) and a BackgroundWorker
public class Sample
{
private MultiMediaTimer _backgroundGetData;
private bool _backgroundGettingData;
private BackgroundWorker _backgroundProcessData;
private ConcurrentQueue<double> _acceleration = new ConcurrentQueue<double>();
private void StartProcess()
{
if (_backgroundGetData == null)
{
_backgroundGetData = new MultiMediaTimer {Period = 10, Resolution = 1, Mode = TimerMode.Periodic, SynchronizingObject = this};
_backgroundGetData.Tick += BackgroundGetDataOnTick;
}
_backgroundProcessData = new BackgroundWorker {WorkerReportsProgress = false, WorkerSupportsCancellation = true};
_backgroundProcessData.DoWork += BackgroundProcessDataOnDoWork;
_backgroundGetData.Start();
}
private void BackgroundProcessDataOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
double value;
if (!_acceleration.TryDequeue(out value)) value = 0;
//Do a lot of work with the values collected so far,
//this will take some time and I suspect it's the cause of the delays?
}
private void BackgroundGetDataOnTick(object sender, EventArgs eventArgs)
{
if (_backgroundGettingData) return;
_backgroundGettingData = true;
//123 represents a value I am reading from the sensors using the SDK
double value = 123;
if (value == -1)
{
Thread.Sleep(5);
continue;
}
_acceleration.Enqueue(value);
if (_acceleration.Count < 5) continue;
if (!_backgroundProcessData.IsBusy)
{
_backgroundProcessData.RunWorkerAsync();
}
_backgroundGettingData = false;
}
}
I am seeing the problem here
_backgroundProcessDataThread.Start();
while (!_backgroundProcessDataThread.IsAlive){}
_backgroundGetDataThread.Start();
while (!_backgroundGetDataThread.IsAlive) {}
Well, you can see here that you are having infinite loop here and the second thread starts only after first has finished its work. i.e. first thread is done. This is in no way an ideal model.
Sorry, I recognized the issue later.
The problem is, _backgroundGetDataThread will start only after _backgroundProcessDataThread has done its work.

C# Initialize local variable once

I assume my question will be totally stupid but I have to know the answer.
Is it possible to initialize a variable just once in this situation?
static void Main()
{
while (true)
{
MethodA();
MethodB();
}
}
private static void MethodA()
{
string dots = string.Empty; // This should be done only once
if (dots != "...")
dots += ".";
else
dots = string.Empty;
Console.WriteLine(dots + "\t" + "Method A");
System.Threading.Thread.Sleep(500);
}
private static void MethodB()
{
string dots = string.Empty; // This should be done only once
if (dots != ".....")
dots += ". ";
else
dots = string.Empty;
Console.WriteLine(dots + "\t" + "Method B");
System.Threading.Thread.Sleep(500);
}
Of course I can initialize string dots out of method but I don't want to do mess in the code, and this can't be done in any other loop too (like for). Any ideas how solve this or am I so stupid to think normally?
Thanks in advance.
EDIT: I've changed the sample code to be more practical. Desired output should be:
. Method A
. Method B
.. Method A
.. Method B
... Method A
... Method B
Method A
.... Method B
. Method A
.....Method B
Etc. etc.
You said you don't want to keep the dots out side of Method (in the Method's class), then you must return the value from Method so that you can at least pass it in later on, thus persisting its state.
string Method(string dot = string.Empty)
{
if(dot == "...") return string.Empty;
else return dot + ".";
}
var result = Method(Method(Method(Method(Method(Method()))))) // etc...
EDIT:
Your edited question does not make your initial problem more practical. It still suffers from the same problem: You want X but C# does not have X. Use C++ or VB.NET instead.
The answer to your question
"Is it possible to initialize a variable just once in this situation?"
is Sorry, NO!
You could keep dots in your class, and initialize it when the class is created, i.e.
string dots = string.Empty;
private void Method()
{
if (dots != "...")
dots += ".";
else
dots = string.Empty;
}
In other languages (C++) you can declare static variables at any scope. This would solve your issue neatly but C# doesn't permit declaration of static variables within functions. This is actually a C# FAQ: Why doesn't C# support static method variables?.
This design feature means that you cannot do what you want in a conventional method. You might be able to do something particularly cunning with currying, but if you don't want to mess with the existing program structure, that's out. I'm sure that there's a way to write native code that would get you to what you want, but it feels like a bad idea.
Putting it simply, you're asking for data that persists outside of its scope. In C#, your chief (sole?) remedy is to increase that data's scope.
You are looking for persistent data between calls to the method, so you need a data element outside of your call. You don't have static local variables in C#.
Consider reading this Stackoverflow post.
Are you thinking of a static local variable as in C++? They are not supported in C#, as discussed here.

How does this code work? [HARD]

LINK:
http://www.codeproject.com/KB/dotnet/twaindotnet.aspx
I'm trying to create a wrapper class for this open source .NET implementation of TWAIN and I'm having trouble understand how it actually gets the image.
I've downloaded the source code and in the GUI there is a button called Acquire. When I click this button to go to it's event handler I find this code which I assume gets the image:
private void menuItemScan_Click(object sender, System.EventArgs e)
{
if (!msgfilter)
{
this.Enabled = false;
msgfilter = true;
Application.AddMessageFilter(this);
}
tw.Acquire();
}
If I follow the Acquire() method to see it's contents, I see this:
public void Acquire()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, srcds);
if (rc != TwRC.Success)
return;
TwCapability cap = new TwCapability(TwCap.XferCount, 1);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, cap);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
TwUserInterface guif = new TwUserInterface();
guif.ShowUI = 1;
guif.ModalUI = 1;
guif.ParentHand = hwnd;
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, guif);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
}
What I don't understand is how a method with a 'void' return type can actually have a return statement. Also, where is it acquiring and returning an image?
Can anyone help out?
I'm trying to create a useful wrapper and open source it, because as it stands there is no easy drag and drop solution for scanning images in C#.
Thanks for the help!
Edit: Thanks for the help regarding early returns. TIL! Now I'm curious about how the application gets the images to display on the form.
Any guidance?
"Void" means it returns nothing, not that it doesn't return. So the return statement just terminates the function and returns to the caller
For your other question, there are a few other relevant stack overflow questions
Twain question: is it possible to scan just one document from feeder?
WIA Twain support C#
The DSCap line is seeing if there are multiple images. The capture happens as part of the call to DSuserif
Infact, you set a message filter on your form by calling Application.AddMessageFilter(this) method. So, you have to listen to scanner events and when you get a TwainCommand.TransferReady event, you will call TransferPictures() to get the image collection.
The method simply returns void to avoid other code segments being executed. That is completely legal. The method is not acquiring an image it only prepares the hardware and UI that is acquiring the image, i'd say.
return; causes the control flow to exit the function.
Had a look at the library. It seems that Acquire() just causes the driver to perform an acquire, and TransferPictures() is called to retrieve the pictures (that one returns an ArrayList, so yes it is returning something).

showing the address of reference in C# (debugging WCF)

I am debugging a WCF project with two-way communication. I have a callback with data that I store in an array the client, a WinForm, and use that for painting a control. As you can guess, the data disappears from writing in the array (really a list) to when I read the data.
For debugging I would like to see if I am writing and reading the same object so that the callback function isn't making some kind of copy and throw it away. For example I want to see the address of the this - pointer. How do I do that in VS2010 Exp?
Edit
Some code:
Field declaration:
// the cards that the player have
private List<Card> cards = new List<Card>();
callback handler:
private void btnDraw_Click(object sender, EventArgs e)
{
Tuple<Card, string> update = PressedDraw(this);
cards.Add(update.Item1);
PaintCards();
}
paint event:
private void cardPanel_Paint(object sender, PaintEventArgs e)
{
int counter = 0;
Point fromCorner = new Point(20,12);
int distance = 50;
foreach (Card card in cards)
{
Point pos = fromCorner;
pos.Offset(counter++ * distance, 0);
Bitmap cardBitmap =
cardFaces[Convert.ToInt32(card.suit),
Convert.ToInt32(card.rank)];
Rectangle square = new Rectangle(pos, cardBitmap.Size);
e.Graphics.DrawImage(cardBitmap, square);
}
When I debug I enter first in the callback handler and adds a Card in cards
PaintCards() calls Invalidate and the paint event is run. When in cardPanel_Paint, cards.Count is zero again.
Best regards.
Görgen
In the Watch/Locals/Autos windows, you can right-click on an object and select "Make Object ID" to give the object an identification number. This number is effectively the same as a native object's address; it serves to identify.
The identity of an object is tracked across garbage collections and compactions, so across the lifetime of your application, you can tell if a certain object is the one you originally tagged. This feature might help in your situation.
This blog post has a quick run-through of the feature.
The address of an object in c# can be changed by the garbage collector so you can not use that (and there is no straight forward method to do so).
But you can use Object.ReferenceEquals to compare to objects to see if they are really the same.
Edit:
But it looks like you have messed things up something like this.
var a = new List<string> { "String1" };
var b = a;
a = new List<string> { "String 2" }; // really GetListFromWcf();
Console.WriteLine(b[0]);
this prints String1, not String2.
If you can not figure it out you need to post some code to show where thing get wrong.

Categories