I'm attempting to write a program which would enable texts to be sent out to customers, I'm using AT Commands with a GSM modem to accomplish this, I have looked at various bits of Documentation but have been unable to find a solution for the following problem.
I am attempting to make the GSM modem return all of the text messages contained within its memory, I have tried many combinations of AT Commands and Parsing techniques to throw this into a text box, but to no avail.
Any help on this would be most appreciated, my code is below
private SerialPort _serialPort2 = new SerialPort("COM3", 115200);
private void MailBox_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
_serialPort2.Open();
//_serialPort2.Write("AT+CMGF=1 \r");
_serialPort2.Write("AT+CMGL=\"ALL\"");
string SerialData = _serialPort2.ReadExisting();
var getnumbers = new string((from s in SerialData where char.IsDigit(s) select s).ToArray());
var getText = SerialData;
SendTxt.Text = getnumbers;
SendMsgBox.Text = getText;
//for (int i = 0; i < SerialData.Length; i++ )
//{
// if (char.IsDigit(SerialData))
//}
//.Text = _serialPort2.ReadExisting();
//string[] text = { textBox1.Text };
//IEnumerable<string> formattext = from words in text where words.("+447") select words;
// foreach (var word in formattext)
//{
//SenderBox.Items.Add(word.ToString());
// }
_serialPort2.Close();
//_serialPort2.DataReceived += new SerialDataReceivedEventHandler(_serialPort2_DataReceived);
}
Related
I am trying to get information reading a card using the RFID Gigatek UR110/115U.
This card just has a code, and I want to read it and store it in a variable.
My reader is in COM4 and is connected by USB.
I am trying something like this:
Designer:
private void InitializeComponent()
{
//...
this.serialPort1 = new System.IO.Ports.SerialPort(this.components);
//...
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
//...
private System.IO.Ports.SerialPort serialPort1;
//...
}
Method:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (this.serialPort1.IsOpen == true)
{
String aux = this.serialPort1.ReadLine();
if (Encoding.ASCII.GetBytes(aux)[0] == 2)
aux = aux.Substring(1);
if (aux.Length > 10)
aux = aux.Substring(0, 10);
this.Lectura = aux;
if (this.serialPort1.IsOpen)
this.serialPort1.Close();
this.tiempo_esperado = 0;
}
}
But this is not working. What could am I doing wrong? Thanks in advance!
I implemented a function in a windows form application to capture and read needed tabular data from a file (sourcedata.data) and save it in another file (result.data ).
How i and by using the application can capture a real time stream data like such available here :https://data.sparkfun.com/streams in csv or .data file to use it.
Or are there any direct waya to read the stream data directly from the website source periodically ?
private void button5_Click(object sender, EventArgs e)
{
List<string[]> rows = new List<string[]>();
int[] indexes = { 0, 1, 3, 5, 6, 7, 8, 9 };
using (var reader = new StreamReader(#"sourcedata.data"))
{
using (StreamWriter writetext = new StreamWriter("result.data"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.IndexOf(',') == -1)
continue;
string[] values = line.Split(',');
string[] row = new string[indexes.Length];
int insertIndex = 0;
for (int i = 0; i < values.Length; i++)
{
string val = values[i];
if (val.Trim() == "?")
goto BREAK;
if (indexes.Contains(i))
row[insertIndex++] = val;
}
rows.Add(row);
writetext.WriteLine(String.Join(",", row));
BREAK:;
}
}
}
}
You have two split your problem into two separated sub problems:
Write a method public static string DownloadData(...) which will download the data from the source. This can be done by any HTTP client or library you can find like System.Net.Http.HttpClient or System.Net.WebClient.
See How to download a file from a URL in C#?
Add/start a timer which calls this method periodically. You can use classes like System.Windows.Forms.Timer or System.Timers.Timer.
See What is the best way to implement a "timer"?
#Progman
It is the code
public partial class Download : Form
{
public Download()
{
InitializeComponent();
}
WebClient client;
private void btnDownload_Click(object sender, EventArgs e)
{
string url = txtUrl.Text;
if (!string.IsNullOrEmpty(url))
{
Thread thread = new Thread(() =>
{
Uri uri = new Uri(url);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
client.DownloadFileAsync(uri, Application.StartupPath + "/" + filename);
});
thread.Start();
}
}
private void Download_Load(object sender, EventArgs e)
{
client = new WebClient();
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
}
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
progressBar.Minimum = 0;
double recieve = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recieve / total * 100;
lblStatus.Text = $"Download {string.Format("{0:0.##}", percentage)}%";
progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}
}
I am developing an application to read data through Serial Port. What I am trying to read is a string that could be empty or with something in it.
My first attempt was creating an array where inside of it I would be able to insert what could come from Serial Port.
string[] pass = new string[4];
pass[0] = "";
pass[1] = "Something";
pass[2] = "To";
pass[3] = "Read";
for (int i = 0; i < pass.Length; i++)
{
string element = pass[i];
}
But this isn't work for me because I wanna read any thing from the Serial port.
In the next option, in the data.ToString() == "Any string I want".
string data = serPort.ReadExisting();
if (data.ToString() == "Any string I want")
{
Environment.Exit(0);
}
Basically, instead of the "Any string I want" I would like to every time I send something through the Arduino it will be recognized by the application.
Do you guys have any suggestions about this? In other words, if the incoming data is equal to the string written by the Arduino it will do something.
You need to decide on a termination char and add it to your arduino code that is sending the serial string and look for that char in the incoming data. I'm using carriage Return line feed.
private string receivedDate = string.Empty;
private System.IO.Ports.SerialPort mport;
private void Form1_Load(object sender, EventArgs e)
{
mport = new SerialPort("COM1", 9600, Parity.None,8, StopBits.One);
mport.DataReceived += new SerialDataReceivedEventHandler(mport_DataReceived);
}
private void mport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
receivedDate += mport.ReadExisting();
if (receivedDate.Contains("\r\n"))
{
//show data
//Clear receivedDate
}
}
I am trying to pull 3 values from a .csv file into an array of class called PizzaOrder. The .csv file was created using the same program. I am having problems figuring out how to insert the values from the .csv into the array of PizzaOrder.
Here is the code of the form so far:
public partial class Form1 : Form
{
PizzaOrder[] pizzaArray = new PizzaOrder[4];
PizzaOrder[] ReadPizzaArray = new PizzaOrder[4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//this is just creating the values and inserting into the array
PizzaOrder p1 = new PizzaOrder(12, "Pepperoni", 14.88m);
PizzaOrder p2 = new PizzaOrder(15, "Mushrooms", 15.69m);
PizzaOrder p3 = new PizzaOrder(13, "Bacon", 15.33m);
PizzaOrder p4 = new PizzaOrder(16, "Olives", 17.47m);
pizzaArray[0] = p1;
pizzaArray[1] = p2;
pizzaArray[2] = p3;
pizzaArray[3] = p4;
}
private void btnDisplay_Click(object sender, EventArgs e)
{
//this is just displaying the contents of the array in a listbox
lstOrders.Items.Clear();
for(int loop = 0; loop < pizzaArray.Length; loop++)
{
lstOrders.Items.Add(pizzaArray[loop].ShowOrder());
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//this is where the .csv file is being created and saved to
StreamWriter SavePizza = new StreamWriter("PizzaFile.csv", true);
try
{
for (int loop = 0; loop < pizzaArray.Length; loop++)
{
SavePizza.Write(pizzaArray[loop].ShowOrder()+ Environment.NewLine);
}
}
catch(System.Exception)
{
MessageBox.Show("A file write error has occured...", "File Error");
}
finally
{
SavePizza.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
//this is where I am attempting to read from the .csv
StreamReader ReadPizza = new StreamReader(File.OpenRead("PizzaFile.csv"));
try
{
string input = ReadPizza.ReadToEnd();
string[] PizzaRead = input.Split(',');
for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
{
//this is where I'm trying to insert from the .csv into the array again, where the problem is
ReadPizzaArray[loop2] = (PizzaRead[0], PizzaRead[1], PizzaRead[2]);
}
}
catch(System.Exception)
{
MessageBox.Show("An error occured during the file read...","File Read Error");
}
finally
{
ReadPizza.Close();
}
}
}
The PizzaOrder class accepts an int, sting, and decimal in that order.
The information from the .csv needs to be added as such.
Any information and/guidance would be most appreciated! Thanks!
You will want to create a new PizzaOrder object to do this. Along with that, you will need to convert to the proper data types. Here is example code:
for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
{
ReadPizzaArray[loop2] = new PizzaOrder(Convert.ToInt32(PizzaRead[0]), PizzaRead[1].ToString(), Convert.ToDecimal(PizzaRead[3]));
}
Along with this, you should take a look at some coding standards. local variables are usually not capitalized. A List would likely work better than an array, as you don't know how many entries there will be for different CSV files.
In addition to oppassum's answer, it seems like you didn't split your csv by lines before splitting each line by commas.
string input = ReadPizza.ReadToEnd();
string[] lines = input.Split(new[] { Environment.NewLine}, StringSplitOptions.RemoveEmptryEntries);
foreach (string line in lines)
{
string[] PizzaRead = line.Split(',');
//Insert oppassum's answer here...
}
Read the file with File.ReadAllLines(), and use String.Split() and String.Trim():
var lines = File.ReadAllLines("PizzaFile.csv")
List<PizzaOrder> orders = new List<PizzaOrder>();
foreach (var line in lines)
{
var fields = line.Split(',');
PizzaOrder order = new PizzaOrder()
{
Id = Convert.ToInt32(fields[0].Trim());
Type = fields[1].Trim();
// etc.
}
}
var result = orders.ToArray();
I want to make a call from a GSM modem using C#. I have written the following code. but I am unable to make the call. Please tell what the mistake is. Also let me know how to handle the response in the code from the modem so that I can display a message like "call connecting" or "cannot connect".
private void button1_Click(object sender, EventArgs e)
{
SerialPort po = new SerialPort();
po.PortName = "COM3";
po.BaudRate = int.Parse( "9600");
po.DataBits = Convert.ToInt32("8");
po.Parity = Parity.None;
po.StopBits = StopBits.One;
po.ReadTimeout = int.Parse("300");
po.WriteTimeout = int.Parse("300");
po.Encoding = Encoding.GetEncoding("iso-8859-1");
po.Open();
po.DtrEnable = true;
po.RtsEnable = true;
po.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
po.Write("ATD9030665834;");
}
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
{
//what to write here to display the response??
}
}
Use port.WriteLine("ATD"+phno+";");
This will definitely solve your problem..
And to handle the response use port.ReadExisting() and compare with your requirement. As easy as that :)
Good luck..
Make Sure whether you are configuring po same as Hyper-terminal as it is working with Hyperterminal.
Hyper Terminal settings are usually like:
If it has Flow Control as NONE then You don't need:
po.DtrEnable = true;
po.RtsEnable = true;
I don't find use of Setting encoding.
Most important thing You are forgetting is Add "\r" at the end of Any AT Command! Seems you haven't read AT Command list!
private void button1_Click(object sender, EventArgs e)
{
SerialPort po = new SerialPort();
po.PortName = "COM10";
po.BaudRate = int.Parse("9600");
po.DataBits = Convert.ToInt32("8");
po.Parity = Parity.None;
po.StopBits = StopBits.One;
po.ReadTimeout = int.Parse("300");
po.WriteTimeout = int.Parse("300");
po.Encoding = Encoding.GetEncoding("iso-8859-1");
po.Open();
po.DtrEnable = true;
po.RtsEnable = true;
//po.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// po.Write("ATD01814201013;");
po.WriteLine("ATD01"+textBoxPhoneNumber.Text+";"+Environment.NewLine);
}