c# and serial port - c#

I'm trying to do an application in c #, which sends a text file through a serial port to a machine.
all good and beautiful if the machine is put in download mode.
if the operator forgets to put the machine on download mode .... here comes the problem, I have a writetimout exception.
I would like to use this exception or anything else to resume the process and my program will try to reload the file into the machine.
below is my code
private void incarca_button_Click(object sender, EventArgs e)
{
string open_folder = cale_txt.Text.Replace(Environment.NewLine, "");
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = open_folder;
if (theDialog.ShowDialog() == DialogResult.OK)
{
var onlyFileName = System.IO.Path.GetFileName(theDialog.FileName);
piesa_lbl.Hide();
piesa_txt.Hide();
SerialPort cnc_com = new SerialPort(com);
cnc_com.BaudRate = Int32.Parse(bit);
parity = parity.ToString();
cnc_com.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
cnc_com.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stop_bit);
cnc_com.DataBits = Int32.Parse(data_bit);
cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
cnc_com.Encoding = Encoding.ASCII;
cnc_com.ReadTimeout = 500;
cnc_com.WriteTimeout = 500;
cnc_com.ReadBufferSize = 1000000;
cnc_com.WriteBufferSize = 1000000;
//cnc_com.DtrEnable = true;
//cnc_com.RtsEnable = true;
try
{
cnc_com.Open();
}
catch (UnauthorizedAccessException) { }
catch (System.IO.IOException) { }
catch (ArgumentException) { }
using (StreamReader sr = new StreamReader(open_folder + #"\" + onlyFileName))
{
while (sr.Peek() >= 0)
{
try
{
cnc_com.WriteLine(sr.ReadLine());
//cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
}
catch(TimeoutException wtout)
{
MessageBox.Show("Masina nu este pregatita\nReincarcati programul");
cnc_com.Close();
cnc_com = null;
}
}
}
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
}
}
I would like this piece of code to be executed only if the file was passed successfully to the machine
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
thank you

Related

Tesseract Init() method C3

I am using Tesseract 2 with c# .net 4.5
Whenever code reaches to OCR.InIt() method, it comes out of code and program stops execution.
Even Catch block does not hold the code.
Please let me know how to check the problem.
Bitmap image = new Bitmap(ofd_OpenPhoto.FileName);
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
ocr.Init("C:\\tessnet2\\tesseract-ocr\\tessdata", "eng", false);
Please let me know, how to use Init() method, Should I remove null?
private void btn_Browse_Click(object sender, EventArgs e)
{
ofd_OpenPhoto.Multiselect = false;
ofd_OpenPhoto.RestoreDirectory = true;
ofd_OpenPhoto.SupportMultiDottedExtensions = false;
ofd_OpenPhoto.FileName = "";
ofd_OpenPhoto.Title = "Select Photo";
ofd_OpenPhoto.Filter = "Photo Files (*.jpg)|*.jpg";
DialogResult result = ofd_OpenPhoto.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string file_name;
if (ofd_OpenPhoto.FileName != null)
{
try
{
file_name = ofd_OpenPhoto.FileName.Substring(ofd_OpenPhoto.FileName.LastIndexOf("\\") + 1);
txt_PhotoPath.Text = file_name.Substring(0, file_name.LastIndexOf("."));
Emgu.CV.Image<Bgr, Byte> img_o = new Emgu.CV.Image<Bgr, byte>(ofd_OpenPhoto.FileName);
pb_PhotoViewer_O.Image = img_o.ToBitmap();
if (pb_PhotoViewer_O.Image != null)
{
try
{
Bitmap image = new Bitmap(ofd_OpenPhoto.FileName);
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
ocr.Init(#"C:\\Program Files (x86)\\Tesseract-OCR", "eng", false);
List<tessnet2.Word> result1 = ocr.DoOCR(image, Rectangle.Empty);
txt_ExtractedNumber.Text = result1.ToString();
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
//e.Message();
}
}
}
}
This is my code.
Thanks.
If you write ocr.Init("C:\\tessnet2\\tesseract-ocr\\tessdata", "eng", false);
then at C:\tessnet2\tesseract-ocr\tessdata directory you must have next files:
eng.DangAmbigs
eng.freq-dawg
eng.inttemp
eng.normproto
eng.pffmtable
eng.unicharset
eng.user-words
eng.word-dawg
Also you must check that an Windows system environment variable ( TESSDATA_PREFIX ) is deleted

Make Wpf more Smooth

I load a lage data fra a text File and display it in a Datatgrid,
the problem is that the windows is slow and not smootth,
how can i implemented the code below better?
the button Code:
private async void MILoadLogFile_Click(object sender, RoutedEventArgs e) {
// Configure open file dialog box
OpenFileDialog oFD = new OpenFileDialog();
// Did they click on the OK button?
if (oFD.ShowDialog() == true) {
await myLogSession.LoadfromFileAsync(oFD.FileName);
}
}
the locad method:(sorry for long Code)
public async Task LoadfromFileAsync(String fileName) {
compassLogCollection.Clear();
StreamReader streamReader = new StreamReader(fileName);
if (fileName.Contains("Compass")) {
String temp = "";
String line;
DateTime dateTime = new DateTime();
LoggingLvl loggingLvl = new LoggingLvl();
LoggingLvl.ELoggingLvl eLoggingLvl = new LoggingLvl.ELoggingLvl();
char[] delimiters = new[] {' '};
string threadId = "";
string loggingMessage;
string dateAndTimestamp = "";
int ff = 0;
try {
using (streamReader) {
while ((line = await streamReader.ReadLineAsync()) != null) {
//while ((line = streamReader.ReadLine()) != null) {
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " + t.Replace(",", ".");
dateTime = DateTime.Parse(dateAndTimestamp);
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl = loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
loggingLvl = new LoggingLvl(eLoggingLvl);
CompassLogData cLD = new CompassLogData(dateTime, loggingLvl, threadId, loggingMessage);
compassLogCollection.Add(cLD);
}
Console.Out.WriteLine("DOOOOOOOOOOOOONE");
}
} catch (Exception e) {
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
I don't see anywhere in your code where UI is updated, so I'm assuming what's causing the slowness is reading of the data from the disk. You can try setting the priority of the thread reading the data from the disk to something lower than Normal so that the UI thread has a better chance at CPU cycles. See the thread priority property.
Also, if the length of the lines in your file are not large and given that the code reading the file is already running in a background thread, I would just use ReadLine instead of using ReadLineAsync and passing the work to yet another thread.

text-to-speech error

I am writing a text-to-speech program and my program throws an exception (simpleTTS speak error).
How do I solve this problem?
private void Voiced(String textToSpeech)
{
try
{
SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
Voice = new SpVoice();
Voice.Volume = 100;
if (chkSaveToWavFile.Checked)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "All files (*.*)|*.*|wav files (*.wav)|*.wav";
sfd.Title = "Save to a wave file";
sfd.FilterIndex = 2;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
SpFileStream SpFileStream = new SpFileStream();
SpFileStream.Open(sfd.FileName, SpFileMode, false);
Voice.AudioOutputStream = SpFileStream;
Voice.Speak(textToSpeech, SpFlags);
SpFileStream.Close();
}
}
else
{
Voice.Speak(textToSpeech, SpFlags);
}
}
catch (Exception error)
{
MessageBox.Show("Speak error", "SimpleTTS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Mono for Android Save into Gallery's Directory

Im trying to save into SD card and if is not available into save it into Internal memory on the Gallery, but always showing on the Galley directory. But this code is not saving it or how can i do to show it into Gallerys Directory.
string nameFile = file + ".png";
//Check wether the sd card is available or not
string state = Android.OS.Environment.ExternalStorageState;
bool isExternalStorageAvailable = false;
bool isExternalStorageWritable = false;
string path = null;
if(Android.OS.Environment.MediaMounted.Equals(state))
{
isExternalStorageAvailable = isExternalStorageWritable = true;
//var path = Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
path = Android.OS.Environment.ExternalStorageDirectory.ToString();
Toast.MakeText(this, "Saved in SDCard", ToastLength.Short).Show();
}
else if(Android.OS.Environment.MediaMountedReadOnly.Equals(state))
{
isExternalStorageAvailable = true;
isExternalStorageWritable = false;
}
else
{
//path = Android.OS.Environment.DataDirectory;
path = Android.OS.Environment.DirectoryPictures;
Toast.MakeText(this, "Saved in Internal Memory ", ToastLength.Short).Show();
}
//Create a Bitmap screen capture
Android.Graphics.Bitmap bitmap;
View view = v.RootView;
view.DrawingCacheEnabled = true;
bitmap = Android.Graphics.Bitmap.CreateBitmap(view.DrawingCache);
view.DrawingCacheEnabled = false;
System.IO.FileStream fs = null;
try
{
fs = new System.IO.FileStream(path + "/" + nameFile, System.IO.FileMode.OpenOrCreate);
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
if(isExternalStorageAvailable == true && isExternalStorageWritable == true)
{
//SendBroadcast(new Intent(Intent.ActionMediaMounted, Android.Net.Uri.Parse(path + "/" + nameFile)));
MyMediaConnectorClient client = new MyMediaConnectorClient(path + "/" + nameFile);
MediaScannerConnection scanner = new MediaScannerConnection(this, client);
client.SetScanner(scanner);
scanner.Connect();
}
else
{
Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver, bitmap, nameFile, v.Id.ToString());
}
fs.Flush();
}
catch(FileNotFoundException e)
{
Log.Error("File Not Found Exception", e.ToString());
}
catch(IOException e)
{
Log.Error("IOException", e.ToString());
}
finally
{
if (fs != null)
fs.Close();
dialog.Dismiss();
}

A generic error occurred in GDI+ ExternalException Was caught cant figure out why

The error is on the line:
for (int x = 0; x < myList.Count(); x++)
The x++is painted with green.
Im using backgroundoworker and I used this code same code in another form before without a backgroundworker and it worked good. Now in the other form im using a click button event to show() this form and I want to use a progressBar1 to show the progress of the backgroundowrker work.
I used now try and catch inside this for loop and it went to the catch point and showed me the error. The full exception message is:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Animation_Radar_Preview.cs:line 163
gifImages isnt null.
This is the full code of this form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DannyGeneral;
using unfreez_wrapper;
namespace mws
{
public partial class Animation_Radar_Preview : Form
{
int mtpStart;
int mtpEnd;
Picturebox1_Fullscreen pb1;
string radar_images_download_directory;
string tempRadarPngToGifDirectory;
int numberOfFiles;
UnFreezWrapper unfreez;
string path_exe;
List<string> myList;
string previewDirectory;
int animatedGifSpeed;
bool loop;
string nameOfStartFile;
string nameOfEndFile;
string previewFileName;
BackgroundWorker backGroundWorker1;
Image img;
private MemoryStream _memSt = null;
public Animation_Radar_Preview()
{
InitializeComponent();
mtpStart = Picturebox1_Fullscreen.mtp1Start;
mtpEnd = Picturebox1_Fullscreen.mtp1End;
animatedGifSpeed = Picturebox1_Fullscreen.animatedSpeed;
loop = Picturebox1_Fullscreen.looping;
pb1 = new Picturebox1_Fullscreen();
radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
previewDirectory = path_exe + "\\" + "previewDirectory";
if (Directory.Exists(previewDirectory))
{
}
else
{
Directory.CreateDirectory(previewDirectory);
}
previewFileName = previewDirectory + "\\" + "preview.gif";
loop = false;
animatedGifSpeed = 0;
unfreez = new UnFreezWrapper();
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.WorkerSupportsCancellation = true;
this.backGroundWorker1.WorkerReportsProgress = true;
backGroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backGroundWorker1_ProgressChanged);
backGroundWorker1.DoWork += new DoWorkEventHandler(backGroundWorker1_DoWork);
backGroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backGroundWorker1_RunWorkerCompleted);
backGroundWorker1.RunWorkerAsync();
progressBar1.Value = 0;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result1;
result1 = new DialogResult();
SaveFileDialog sd = new SaveFileDialog();
sd.Title = "Select a folder to save the animated gif to";
sd.InitialDirectory = "c:\\";
sd.FileName = null;
sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
sd.FilterIndex = 1;
sd.RestoreDirectory = true;
result1 = sd.ShowDialog();
string file1 = sd.FileName;
if (result1 == DialogResult.OK)
{
File.Move(previewFileName, file1);
}
}
public void pictureBoxImage(string pbImage)
{
Image img2 = null;
try
{
using (img = Image.FromFile(pbImage))
{
//get the old image thats loaded from the _memSt memorystream
//and dispose it
Image i = this.pictureBox1.Image;
this.pictureBox1.Image = null;
if (i != null)
i.Dispose();
//grab the old stream
MemoryStream m = _memSt;
//save the new image to this stream
_memSt = new MemoryStream();
img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);
if (m != null)
m.Dispose();
//create our image to display
img2 = Image.FromStream(_memSt);
}
if (img2 != null)
pictureBox1.Image = img2;
label2.Text = numberOfFiles.ToString();
label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
//File.Delete(pbImage);
}
catch(Exception err)
{
Logger.Write("Animation Error >>> " + err);
}
}
private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> myGifList;
Image gifImages = null;
//button1.Enabled = false;
Animation_Radar_Preview ap = new Animation_Radar_Preview();
//ap.FormClosing += new FormClosingEventHandler(ap_FormClosing);
FileInfo[] fi;
DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory);
fi = dir1.GetFiles("*.png");
myList = new List<string>();
myGifList = new List<string>();
for (int i = mtpStart; i < mtpEnd; i++)
{
myList.Add(fi[i].FullName);
}
for (int x = 0; x < myList.Count(); x++)
{
try
{
gifImages = Image.FromFile(myList[x]);
gifImages.Save(tempRadarPngToGifDirectory + "\\" + x.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception ex)
{
MessageBox.Show(x.ToString() + "\r\n" + (gifImages == null).ToString() + "\r\n" + ex.Message);
}
}
myGifList = new List<string>();
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
fi = dir1.GetFiles("*.gif");
nameOfStartFile = fi[0].Name;
for (int i = 0; i < fi.Length; i++)
{
myGifList.Add(fi[i].FullName);
//backGroundWorker1.ReportProgress(i);
nameOfEndFile = fi[i].Name.Length.ToString();
}
numberOfFiles = myGifList.Count();
unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);
/*this.Invoke((MethodInvoker)delegate
{
pictureBoxImage(previewFileName);
});*/
}
private void backGroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pictureBoxImage(previewFileName);
}
}
}
I'm not entirely sure what is going wrong, especially as you say this same code worked previously — but it is not clear whether it worked with the same set of images.
Anyhow, the documentation for the Save method says that an ExternalException will be thrown in one of two situations:
Image was saved with the wrong format.
Image is saved to the file it was created from.
It cannot be that you are saving over the file because you are changing its extension, so it must be the wrong format. What this actually means is not clear. Perhaps one of the source images is using capabilities of the PNG format that cannot be converted to GIF, e.g. alpha channel transparency.
If I may take a moment to make some other suggestions too:
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
The empty 'success' case is not required if you invert the logic:
if (!Directory.Exists(tempRadarPngToGifDirectory)
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
Code that manipulates file paths such as the following:
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
You should consider using the Path class as this will handle the edge cases better and make more portable code:
tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");

Categories

Resources