Issue with +CDS AT COMMAND - c#

I'm issue when I get +CDS in AT COMMAND throught c# using SerialPort, any times I get this +CDS truncated, example:
+CDS: 25
0002970C91555868047414212181414094882121814140948830
Why I've this problem, why any times work nice?
I'm starting SerialPort:
public PortCOM(string porta)
: base(porta, 115200, Parity.None, 8, StopBits.One)
{
this.StatusPort = StatusPorta.Ready;
this.DiscardNull = true;
this.ReadTimeout = 21000;
this.RtsEnable = true;
this.DtrEnable = true;
this.ReceivedBytesThreshold = 9;
this.NewLine = "\r\n";
this.ReadBufferSize = 1024;
}
public static void TestPort()
{
var p = new PortCom("COM12");
if (!p.IsOpen)
p.Open();
p.StatusPort = StatusPorta.Ready;
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceivedSample);
p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);
p.ErrorReceived += new SerialErrorReceivedEventHandler(p_ErrorReceived);
p.Disposed += new EventHandler((obj, porta) =>
{
Console.WriteLine(((PortaCOM)obj).ToString());
});
if (Console.ReadKey().Key == ConsoleKey.B)
{
p.Close();
p.Dispose();
}
}
static void p_DataReceivedSample(object sender, SerialDataReceivedEventArgs e)
{
var p = (PortaCOM)sender;
try
{
Console.WriteLine(p.ReadExisting());
var sb = new StringBuilder();
sb.Append(p.ReadExisting());
int y = sb.ToString().IndexOf("\r\n");
var stop = Stopwatch.StartNew();
stop.Start();
while (y == -1)
{
sb.Append(p.ReadExisting());
y = sb.ToString().IndexOf("\r\n");
if (stop.Elapsed.TotalSeconds > 10)
break;
}
stop.Stop();
var _retorno = sb.ToString();
var cmt = regCMT.Match(_retorno);
var succ = regSucess.Match(_retorno);
var report = regStatusReport.Match(_retorno);
var erro = regError.Match(_retorno);
#region Resposta
if (cmt.Success)
{
var smss = new SMS();
var source = cmt.Groups[3].Value;
SMS.Fetch(smss, ref source);
var resposta = new Resposta()
{
Mensagem = smss.Message,
Data = smss.ServiceCenterTimeStamp,
Sender = smss.PhoneNumber,
Operadora = p.OperadoraName.NomeOperadora.ToString()
};
GravaResposta().ToAsync(Scheduler.TaskPool).Invoke(p, cmt.Groups[3].Value);
p.IsError = false;
}
#endregion
#region StatusReport
if (report.Success)
{
RecebeReport(p, report.Groups[2].Value.Trim());
p.IsError = false;
}
#endregion
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
Please I really need help with it, I'm glad for any help!

+cds is alert for incoming message with message location on SIM memeory.
so here its seems in PDU mode data. and it is seems may be flash message content.
Convert the data PDU mode to Text mode to receive message.
review this ATSMS library

Related

Automatically send messages every 1 second

internal class Program2
{
public static async Task<int> Main(string[] args)
{
Console.WriteLine("String console app");
var senderObject = MessageActivator.GetSenderObject();
MessageOptions opts = null;
Parser.Default.ParseArguments<MessageOptions>(args).WithParsed(opts1 =>
{
opts = (MessageOptions)opts1;
}).WithNotParsed(optsx =>
{
Environment.Exit(0);
});
await Task.Delay(100);
senderObject.SendMessage(new SyslogMessageOptions()
{
SyslogServerHost = opts.SyslogServerHost,
SyslogServerPort = opts.SyslogServerPort,
ApplicationName = opts.ApplicationName,
ProcessorId = opts.ProcessorId,
MessageId = opts.MessageId,
Facility = opts.Facility,
Severity = opts.Severity,
NetworkProtocols = (SyslogTesterLib.NetworkProtocol)opts.NetworkProtocols,
MessageFormat = (SyslogTesterLib.SyslogMessageFormat)opts.MessageFormat,
Message = opts.Message,
ShouldPrintMessage = opts.ShouldPrintMessage,
LocalHostName = opts.LocalHostName,
StructuredData = opts.StructuredData,
Date = opts.Date,
}, new BulkMessageOptions()
{
TotalNMessageOptions = new TotalNMessageOptions() { TotalMessages=opts.TotalNMessageCount},
BulkMessageSendType = BulkMessageSendType.OncePerSecond,
});
Console.WriteLine("Press any key to close.");
Console.ReadKey();
return 0;
}
}
Here I am sending a syslog bulk message with various options.
What I wanted to know is, is it possible for it to automatically send every 1 second. If yes, how can I possibly do that?
There's the codes, in case if it brings of any help.
See the Interval property of Timer object.
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=net-6.0
Just set your interval and assign your callback to the elapsed event
//send a message every 1 second
var timer = new Timer(1000);
var senderObject = MessageActivator.GetSenderObject();
MessageOptions opts = null;
Parser.Default.ParseArguments<MessageOptions>(args).WithParsed(opts1 =>
{
opts = (MessageOptions)opts1;
});
timer.Elapsed += (sender, e) =>
{
senderObject.SendMessage(new SyslogMessageOptions()
{
SyslogServerHost = opts.SyslogServerHost,
SyslogServerPort = opts.SyslogServerPort,
ApplicationName = opts.ApplicationName,
ProcessorId = opts.ProcessorId,
MessageId = opts.MessageId,
Facility = opts.Facility,
Severity = opts.Severity,
NetworkProtocols = (SyslogTesterLib.NetworkProtocol)opts.NetworkProtocols,
MessageFormat = (SyslogTesterLib.SyslogMessageFormat)opts.MessageFormat,
Message = opts.Message,
ShouldPrintMessage = opts.ShouldPrintMessage,
LocalHostName = opts.LocalHostName,
StructuredData = opts.StructuredData,
Date = opts.Date,
});
};
timer.Start();
Console.ReadLine();

ReceiveDetections Method is Calling Multiple Times

I am scanning QR CODE but the problem is ReceiveDetections method is calling multiple times even after a successful scan.How can I prevent calling the api multiple times after a successful call.
here is the code snippet
public void ReceiveDetections(Detections detections)
{
SparseArray qrcodes = detections.DetectedItems;
if (qrcodes.Size() != 0)
{
txtscankanbancloseResult.Post(async () =>
{
Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
vibrator.Vibrate(1000);
txtscankanbancloseResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
try
{
var client = new HttpClient();
var uri = new Uri(string.Format(AppStatics.clsStatic.url + "//Kanban/SaveKanbanStatus"));
List<string> lstskanban = new List<string>();
String myDate = DateTime.Now.ToString("dd-MMM-yyyy");
string adateddate = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss");
JsonScankanbanclose objjscan = new JsonScankanbanclose();
lstskanban.Add(txtscankanbancloseResult.Text);
objjscan.UpdateBy = SingletonSession.Instance().getUsername();
objjscan.KANBANNOList = lstskanban;
objjscan.IsKANBANClosed = true;
string jsonData = JsonConvert.SerializeObject(objjscan);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
var result = await response.Content.ReadAsStringAsync();
if (response.ReasonPhrase == "OK")
{
JArray scanresult = JArray.Parse(result);
Scanlist objscan = new Scanlist();
if (ScanSucessfull.Count == 0)
{
objscan.KanbanID = "Kanban NO";
objscan.KanbanQty = "Kanban Qty";
ScanSucessfull.Add(objscan);
objscan = new Scanlist();
}
// Scanlist item = ScanSucessfull.Find(c => c.KanbanID == scanresult[0]["KANBANID"].ToString());
//int itemPosition = ScanSucessfull.BinarySearch(scanresult[0]["KANBANID"].ToString());
//if (itemPosition.cou=="")
//{
objscan.KanbanID = scanresult[0]["KANBANNumber"].ToString();
objscan.KanbanQty = scanresult[0]["Qty"].ToString();
ScanSucessfull.Add(objscan);
//}
var adapter = new CustomAdapterScan(this, ScanSucessfull);
lstviewscankanbanclose.SetAdapter(adapter);
lstviewscankanbanclose.Clickable = false;
//lstview.Enabled = false;
lstviewscankanbanclose.ItemSelected += null;
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.successful);
currentSong = Resource.Raw.successful;
mPlayer.SeekTo(1);
mPlayer.Start();
//Toast.MakeText(this, , ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkGreen, "Data Save Sucessfully..", ToastLength.Short);
_kanbancount++;
txtscankanbanclosekanbancount.Text = "Kanban Count:" + " " + _kanbancount;
txtscankanbanclosekanbancount.Visibility = ViewStates.Visible;
}
else
{
string[] result1 = result.Split(':');
string[] result2 = result1[1].Split('"');
string[] result3 = result2[1].Split('"');
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.fail);
// mPlayer.SeekTo(2);
currentSong = Resource.Raw.fail;
mPlayer.Start();
//Toast.MakeText(this, result3[0].ToString(), ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkRed, result3[0].ToString(), ToastLength.Short);
}
// dialog.Hide();
cameraSource.Start(surfaceView.Holder);
//txtResult.Text = "";
}
catch (System.Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
// txtResult.Text = "";
txtscankanbancloseResult.Visibility = ViewStates.Invisible;
//cameraSource.Start(surfaceView.Holder);
}
});
using (var h = new Handler(Looper.MainLooper))
h.Post(() =>
{
cameraSource.Stop();
// Toast.MakeText(this, "This Kanban Already Scanned....", ToastLength.Short).Show();
});
}
}
Here is the code where I crate and open the camera source to scan the QR code
private void btnkanbanscan_Click(object sender, EventArgs e)
{
try
{
#region validation
if (spnSiteID.SelectedItemPosition < 0)
{
throw new Exception("Please Select Site...");
}
if (spnLocation.SelectedItemPosition < 0)
{
throw new Exception("Please Select Location..");
}
if (spnInspactionType.SelectedItemPosition < 0)
{
throw new Exception("Please Select Inspection Type..");
}
#endregion
LayoutInflater layoutInflater = LayoutInflater.From(this);
View scanview = LayoutInflater.Inflate(Resource.Layout.scan_popup, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.SetView(scanview);
surfaceView = scanview.FindViewById<SurfaceView>(Resource.Id.spvscan);
dialog = alertDialogBuilder.Create();
dialog.SetCanceledOnTouchOutside(false);
dialog.Show();
barcodeDetector = new BarcodeDetector.Builder(this)
.SetBarcodeFormats(BarcodeFormat.Code128 | BarcodeFormat.QrCode)
.Build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.SetRequestedPreviewSize(480, 480)
.SetAutoFocusEnabled(true)
.Build();
surfaceView.Holder.AddCallback(this);
barcodeDetector.SetProcessor(this);
surfaceView.Visibility = ViewStates.Visible;
_definemethod = "KANBAN";
}
catch (Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
}
}
NCTB: I noticed that after opening the dialog to scan the QR CODE the ReceiveDetections method get called frequently and the scanned value comes in detections parameter .which is normal and it supposed to do so.But the problem is after a successful scan it should not call anymore.

EF inserting values in table failed after some time

I am working on EF. I am trying to insert into a table, the insert function is in a thread.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
Thread.Sleep(50);
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
new Thread(() => {
SaveData(finalData);
}).Start(); // starting the thread
port.DiscardOutBuffer();
port.DiscardInBuffer();
}
And this is my save data function
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;
mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
u.SaveChanges();
}
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
try
{
thread.Abort(); // aborting it after insertion
//Thread.Sleep(50);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
The above code runs for some time, but after that I encountered an error at u.SaveChanges();
System.Data.Entity.Core.EntityException: 'An error occurred while closing the provider connection. See the inner exception for details.'
MySqlException: Fatal error encountered during command execution.
MySqlException: Fatal error encountered attempting to read the resultset.
MySqlException: Reading from the stream has failed.
IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I have looked into each solution and tried them but still unable to resolve this issue. I must be missing something that I don't know.
Update 1 My whole code
Calling constructor
public CommunicationEngine()
{
port.ReadTimeout = 500;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Open();
Console.WriteLine("Port opened successfully");
Console.WriteLine("I am Recieving");
}
Calling handler
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
Thread.Sleep(50);
Console.WriteLine("Bytes are ok..." + port.BytesToRead + " Recieved ");
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
try
{
new Thread(() => {
SaveData(finalData);
}).Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
port.DiscardOutBuffer(); port.DiscardInBuffer();
}
Saving data into DB
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;
if (finalData.Length == 138)
{
comm = true;
var H = finalData.Substring(0, 2);
var FC = finalData.Substring(2, 9);
var len = finalData.Substring(10, 2);
var sr = finalData.Substring(12, 12);
var energy_tag = finalData.Substring(24, 4);
var e_val = hexToDec(finalData.Substring(28, 8)) / 10;
var a_curr_tag = finalData.Substring(36, 4);
var a_curr_val = hexToDec(finalData.Substring(40, 8)) / 1000;
var b_curr_tag = finalData.Substring(48, 4);
var b_curr_val = hexToDec(finalData.Substring(52, 8)) / 1000;
var c_curr_tag = finalData.Substring(60, 4);
var c_curr_val = hexToDec(finalData.Substring(64, 8)) / 1000;
var a_vol_tag = finalData.Substring(72, 4);
var a_vol_val = hexToDec(finalData.Substring(76, 8)) / 10;
var b_vol_tag = finalData.Substring(84, 4);
var b_vol_val = hexToDec(finalData.Substring(88, 8)) / 10;
var c_vol_tag = finalData.Substring(96, 4);
var c_vol_val = hexToDec(finalData.Substring(100, 8)) / 10;
var a_pf_tag = finalData.Substring(108, 4);
var a_pf_val = hexToDec(finalData.Substring(112, 4)) / 1000;
var b_pf_tag = finalData.Substring(116, 4);
var b_pf_val = hexToDec(finalData.Substring(120, 4)) / 1000;
var c_pf_tag = finalData.Substring(124, 4);
var c_pf_val = hexToDec(finalData.Substring(128, 4)) / 1000;
var crc = finalData.Substring(132, 4);
var ftr = finalData.Substring(136, 2);
var d_type = "600";
DateTime theDate = DateTime.Now;
string format = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(LineNumber() + "Data Ready to be inserted in DB");
using (mdc_dbEntities u = new mdc_dbEntities())
{
var msnList = u.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
foreach (var res in msnList)
{
var cust_id = u.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
try
{
u.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
else if(finalData.Length == 30)
{
var msn_no = finalData.Substring(12, 12);
mdc_dbEntities p = new mdc_dbEntities();
var update = p.meter_control.Where(c => (c.comm_executed == 0))
.Where(o => (o.m_hex == msn_no))
.SingleOrDefault();
if(update.comm_sent == "Disconnect")
{
update.comm_executed = 1;
update.comm = 0;
p.SaveChanges();
Console.WriteLine("Meter Disconnected....");
}
else if(update.comm_sent == "Connect")
{
update.comm_executed = 1;
update.comm = 1;
p.SaveChanges();
Console.WriteLine("Meter Connected....");
}
comm = true;
}
else
{
comm = true;
}
try
{
thread.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Any help would be highly appreciated.
Executing EF related changes in a manually initiated thread is not a good idea. Try to run the EF changes in the same thread. If you are bothered with processing incoming requests, use Async, and Await feature. I have modified your code to accommodate this feature. Please try this.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
Console.WriteLine("Thread Going to Start");
SaveDataAsync(finalData).Wait(); // this call will become sync and runs under main thread.
port.DiscardOutBuffer();
port.DiscardInBuffer();
}
public async Task<bool> SaveDataAsync(string finalData)
{
mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
var isSaveSuccess = false;
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
isSaveSuccess = (await u.SaveChangesAsync())>0; // if records inserted, the count will be more than 0
}
return isSaveSuccess;
}
}
this is easier to read and may help
saying all this please ensure that you can actually make a connection to the db
double check connectionString
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
using (mdc_dbEntities dbContext = new mdc_dbEntities())
{
var msnList = dbContext.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
//put debug point here and check that msnList is populated
foreach (var item in msnList)
{
//this is slow as it will be a db query for each loop
var cust_id = dbContext.mdc_meter_cust_rel.Where(m => m.msn == item.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
var data = new mdc_meters_data()
{
msn = item.msn,
cust_id = cust_id,
device_id = item.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = item.p_id,
};
dbContext.mdc_meters_data.Add(data);
}
//depending on how many you added this may take some time.
dbContext.SaveChanges();
}
}

stm32f4 discovery sample of using USB to communicate with pc or read/write pendrive using net micro framework

I cannot find any sample of using USB port of STM32F4 Discovery board in .NET Micro Framework. I'm trying to learn how to use USB port to send or write data. Where can I find such examples?
I've tried to make sample application based on https://guruce.com/blogpost/communicating-with-your-microframework-application-over-usb but it doesn't work.
This is part of my code sample:
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Hardware.UsbClient;
using System;
using System.Text;
using System.Threading;
namespace MFConsoleApplication1
{
public class Program
{
private const int WRITE_EP = 1;
private const int READ_EP = 2;
private static bool ConfigureUSBController(UsbController usbController)
{
bool bRet = false;
// Create the device descriptor
Configuration.DeviceDescriptor device = new Configuration.DeviceDescriptor(0xDEAD, 0x0001, 0x0100);
device.bcdUSB = 0x110;
device.bDeviceClass = 0xFF; // Vendor defined class
device.bDeviceSubClass = 0xFF; // Vendor defined subclass
device.bDeviceProtocol = 0;
device.bMaxPacketSize0 = 8; // Maximum packet size of EP0
device.iManufacturer = 1; // String #1 is manufacturer name (see string descriptors below)
device.iProduct = 2; // String #2 is product name
device.iSerialNumber = 3; // String #3 is the serial number
// Create the endpoints
Configuration.Endpoint writeEP = new Configuration.Endpoint(WRITE_EP, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Write);
writeEP.wMaxPacketSize = 64;
writeEP.bInterval = 0;
Configuration.Endpoint readEP = new Configuration.Endpoint(READ_EP, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Read);
readEP.wMaxPacketSize = 64;
readEP.bInterval = 0;
Configuration.Endpoint[] usbEndpoints = new Configuration.Endpoint[] { writeEP, readEP };
// Set up the USB interface
Configuration.UsbInterface usbInterface = new Configuration.UsbInterface(0, usbEndpoints);
usbInterface.bInterfaceClass = 0xFF; // Vendor defined class
usbInterface.bInterfaceSubClass = 0xFF; // Vendor defined subclass
usbInterface.bInterfaceProtocol = 0;
// Create array of USB interfaces
Configuration.UsbInterface[] usbInterfaces = new Configuration.UsbInterface[] { usbInterface };
// Create configuration descriptor
Configuration.ConfigurationDescriptor config = new Configuration.ConfigurationDescriptor(500, usbInterfaces);
// Create the string descriptors
Configuration.StringDescriptor manufacturerName = new Configuration.StringDescriptor(1, Consts.MANUFACTURER);
Configuration.StringDescriptor productName = new Configuration.StringDescriptor(2, Consts.PRODUCT_NAME);
Configuration.StringDescriptor serialNumber = new Configuration.StringDescriptor(3, Consts.SERIAL_NO);
Configuration.StringDescriptor displayName = new Configuration.StringDescriptor(4, Consts.DISPLAYED_NAME);
Configuration.StringDescriptor friendlyName = new Configuration.StringDescriptor(5, Consts.FRENDLY_NAME);
// Create the final configuration
Configuration configuration = new Configuration();
configuration.descriptors = new Configuration.Descriptor[]
{
device,
config,
manufacturerName,
productName,
serialNumber,
displayName,
friendlyName
};
try
{
// Set the configuration
usbController.Configuration = configuration;
if (UsbController.ConfigError.ConfigOK != usbController.ConfigurationError)
throw new ArgumentException();
// If all ok, start the USB controller.
bRet = usbController.Start();
}
catch (ArgumentException)
{
Debug.Print(Consts.CONFIG_ERR + usbController.ConfigurationError.ToString());
}
return bRet;
}
private static string GetCommand(byte[] data)
{
return new string(Encoding.UTF8.GetChars(data));
}
private static byte[] GetDataToSend(Reading data, JsonSerializer serializer)
{
return Encoding.UTF8.GetBytes(serializer.Serialize(data));
}
private static void UsbMainLoop(UsbStream usbStream, AnalogInput supplyInput, AnalogInput dataInput, OutputPort recievingDataIndicator, OutputPort seindingDataIndicator, JsonSerializer dataSerializer)
{
byte[] readData = new byte[100];
for (;;)
{
recievingDataIndicator.Write(true);
int bytesRead = usbStream.Read(readData, 0, readData.Length);
recievingDataIndicator.Write(false);
if (bytesRead > 0)
{
string command = GetCommand(readData);
switch (command)
{
case "READ":
seindingDataIndicator.Write(true);
byte[] dataToSend = GetDataToSend(Reading.GetReading(supplyInput, dataInput), dataSerializer);
usbStream.Write(dataToSend, 0, dataToSend.Length);
seindingDataIndicator.Write(false);
break;
}
}
}
}
private static UsbController CheckSupportAndAccessibility(UsbController[] usbControllers, out string message)
{
UsbController usbController = null;
if (0 == usbControllers.Length)
{
message = Consts.USB_NOT_SUPPORTED;
}
else
{
bool foundedFreeUsb = false;
foreach (UsbController controller in usbControllers)
{
if (UsbController.PortState.Stopped == controller.Status)
{
usbController = controller;
foundedFreeUsb = true;
break;
}
}
if (foundedFreeUsb)
{
message = string.Empty;
}
else
{
message = Consts.NO_FREE_USB;
}
}
return usbController;
}
private static void OtherMainProgramLoop()
{
AnalogInput temperature0 = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
AnalogInput supply0 = new AnalogInput(Cpu.AnalogChannel.ANALOG_1);
double t0, r0, z0;
while (true)
{
z0 = supply0.Read() * 3;
r0 = Reading.GetRt(z0, temperature0.Read() * z0);
t0 = Reading.GetTemp(r0);
Debug.Print("Supply:" + z0.ToString() + "[V]");
Debug.Print("Rt:" + r0.ToString() + "[Ohm]");
Debug.Print("Temperature:" + t0.ToString() + "[^C]");
Thread.Sleep(1000);
}
}
public static void Main()
{
UsbController[] controllers = UsbController.GetControllers();
string msg;
UsbController usbController = CheckSupportAndAccessibility(controllers, out msg);
if (null == usbController)
{
Debug.Print(msg);
OtherMainProgramLoop();
//return;
}
else
{
UsbStream usbStream = null;
try
{
if (ConfigureUSBController(usbController))
usbStream = usbController.CreateUsbStream(WRITE_EP, READ_EP);
else
throw new Exception();
}
catch (Exception)
{
Debug.Print(Consts.USB_CREATE_STREAM_ERR + usbController.ConfigurationError.ToString());
OtherMainProgramLoop();
//return;
}
AnalogInput temperatureSource = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
AnalogInput supplySource = new AnalogInput(Cpu.AnalogChannel.ANALOG_1);
OutputPort ledGreen = new OutputPort((Cpu.Pin)60, false);
OutputPort ledYellow = new OutputPort((Cpu.Pin)61, false);
UsbMainLoop(usbStream, supplySource, temperatureSource, ledYellow, ledGreen, new JsonSerializer());
usbStream.Close();
}
}
}
}
Thanks for any help.

C# Memory management (Memory leak?)

I am working on a program in WPF that basically retrieves JSON data from a WEB API and parses it then saves it to database with EF.
The problem is the memory usage of the program keeps on increasing as the time goes by. (From 20MB to 2gigs).
The following is the code that I am using.
Is there any optimization i can perform to keep the memory under a limit and say the unused objects gets deleted periodically.
void getMatchInfo_Work(object sender, DoWorkEventArgs e)
{
HttpClient client = new HttpClient();
DataConnection dc = new DataConnection();
dc.Configuration.AutoDetectChangesEnabled = false;
dc.Configuration.ValidateOnSaveEnabled = false;
do{
do
{
using (Stream s = client.GetStreamAsync("http://api.steampowered.com/IDOTA2Match_570/GetMatchHistoryBySequenceNum" +
"/v1/?key="+devkey+"&start_at_match_seq_num=" + matchseq.ToString()).Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
MatchMain match;
MatchDesc player;
RootElement matchSeq = serializer.Deserialize<RootElement>(reader);
if (matchSeq.result.status == 1)
{
foreach (var m in matchSeq.result.matches)
{
match = new MatchMain();
match.MatchID = m.match_id;
match.Win = m.radiant_win;
match.Duration = m.duration;
match.StartTime = ConvertFromUnixTimestamp(m.start_time);
match.TimeStamp = m.start_time;
match.SeqNo = m.match_seq_num;
matchseq = m.match_seq_num + 1;
match.RadTower = m.tower_status_radiant;
match.DireTower = m.tower_status_dire;
match.RadRax = m.barracks_status_radiant;
match.DireRax = m.barracks_status_dire;
match.cluster = m.cluster;
match.FBTime = m.first_blood_time;
match.LobbyType = m.lobby_type;
match.HumanCount = m.human_players;
match.LeagueID = m.leagueid;
match.GameMode = m.game_mode;
dc.MatchMain.Add(match);
count++;
foreach (var p in m.players)
{
player = new MatchDesc();
player.MatchID = m.match_id;
player.AccountID = p.account_id;
player.PlayerSlot = p.player_slot;
player.HeroID = p.hero_id;
player.First = p.item_0;
player.Second = p.item_1;
player.Third = p.item_2;
player.Fourth = p.item_3;
player.Fifth = p.item_4;
player.Sixth = p.item_5;
player.Kills = p.kills;
player.Deaths = p.deaths;
player.Assists = p.assists;
player.LeaverStatus = p.leaver_status;
player.Gold = p.gold;
player.LastHits = p.last_hits;
player.Denies = p.denies;
player.GPM = p.gold_per_min;
player.XPM = p.xp_per_min;
player.GoldSpent = p.gold_spent;
player.HeroDamage = p.hero_damage;
player.TowerDamage = p.tower_damage;
player.Healing = p.hero_healing;
player.HeroLevel = p.level;
dc.MatchDesc.Add(player);
}
getMatchInfo.ReportProgress(1);
}
dc.SaveChanges();
}
else
{
result = 0;
}
}
} while (result == 1);
Thread.Sleep(60000);
}while( result>-999);
}
void getMatchInfo_Progress(object sender, ProgressChangedEventArgs e)
{
if (result != 0)
{
txtProgress.Text = count + " matches updated in database and continuing.";
}
else
{
txtProgress.Text = count + " matches updated in database and waiting for API.";
}
txtTime.Text =sw.Elapsed.Hours.ToString()+" hours "+ sw.Elapsed.Minutes.ToString()+" minutes "+
sw.Elapsed.Seconds.ToString()+" seconds";
}
Edit: Button click code
private void btnRetrieveData_Click(object sender, RoutedEventArgs e)
{
getMatchInfo.DoWork += new DoWorkEventHandler(getMatchInfo_Work);
getMatchInfo.ProgressChanged += new ProgressChangedEventHandler(getMatchInfo_Progress);
getMatchInfo.WorkerReportsProgress = true;
txtProgress.Text = "Process started";
matchseq = Convert.ToInt64(txtSeqNo.Text);
devkey = txtKey.Text;
sw.Start();
getMatchInfo.RunWorkerAsync();
}
DataConnection context keeps tracking all objects that it ever saw. Put creation of dc inside the loop and dispose it every time. You don't need the context after each SaveChanges is called.

Categories

Resources