Click here to Skip to main content
15,891,828 members
Articles / Web Development / ASP.NET

Store and forward GPS data for Smart Phones

Rate me:
Please Sign up or sign in to vote.
4.64/5 (6 votes)
28 Jul 2009CPOL3 min read 30.4K   911   35  
How to deliver GPS data asynchronously to the server over the internet without queues.
using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Xml;
using System.Threading;

namespace MobileGps {
    delegate void WriteOutputDel(object txt);

    public partial class MainFrm : Form {
        int buffersize = 1024;
        string comPort = "COM5";
        SerialPort sp = new SerialPort();
        StreamWriter swLogFile = null;
        Thread t;
        VVXGps.GPSWebService gpsSvc = null; //= new MobileGps.VVXGps.GPSWebService();
        string id = string.Empty;
        string ver = string.Empty;
        string msg = string.Empty;
        int sendInterval = 1000 * 10; //10sec

        public MainFrm() {
            try {
                InitializeComponent();
                Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                ver = string.Format("Version:{0}.{1}.{2}.{3}\r\n", v.Major, v.Minor, v.Build, v.Revision);
                //msg += "Init\r\n";
                ReadConfig();
                //msg += "ReadConfig done\r\n";
                string logFile = Util.GetLogFile();
                msg += "log file directory:" + logFile + "\r\n";
                try {
                    swLogFile = File.AppendText(logFile);
                } catch (Exception ioe) { msg += ioe.Message; }

                //msg += "Get LogFile Stream\r\n";
                gpsSvc = new MobileGps.VVXGps.GPSWebService();
                
                //msg += "Init gps service\r\n";
                lblOutput.Text = ver + msg;
                
            } catch (Exception ex) {
                lblOutput.Text = ver + "\r\n" + msg + ex.Message;
            }
        }

        private void ReadConfig() {
            try {
                XmlDocument xDoc = new XmlDocument();
                string fname = Util.GetConfigFile();
                if (string.IsNullOrEmpty(fname)) {
                    Util.Reset();
                    fname = Util.GetConfigFile();
                }
                xDoc.Load(fname);
                XmlNode comNode = xDoc.SelectSingleNode("//COM");
                if (comNode != null) {
                    comPort = comNode.InnerText;
                }
                XmlNode idNode = xDoc.SelectSingleNode("//ID");
                if (idNode != null) {
                    id = idNode.InnerText;
                }
                XmlNode sendNode = xDoc.SelectSingleNode("//SendInterval");
                if (sendNode != null) {
                    sendInterval = Int32.Parse(sendNode.InnerText) * 1000;
                }
                //Start process of sending files.
                PickUpFileInput();
            } catch (Exception ex) {
                MessageBox.Show("Read Config error:\r\n" + ex.Message);
            }
        }

        private void PickUpFileInput() {
            Thread t = new Thread(new ThreadStart(GpsFileListner));
            t.Start();
            //Helper h = new Helper();
            //TimerCallback timeCB = new TimerCallback(h.CleanUpOldFiles);
            //System.Threading.Timer t = new System.Threading.Timer(timeCB, null, 100, sendInterval);            
        }

        private void GpsFileListner() {
            Helper h = new Helper();
            while (true) {
                h.CleanUpOldFiles(null);
                Thread.Sleep(sendInterval);
            }
        }

        private void mnuStart_Click(object sender, EventArgs e) {
            sp = new SerialPort(comPort);
//#if !DEBUG
            Connect(sp);
//#endif
            StartCOMPortListner();            
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            WriteOutputDel del = new WriteOutputDel(WriteOut);
            Invoke(del, new object[] { sender });
            SerialData sd = e.EventType;
            //if (swLogFile != null)
            //    LogData(string.Format("Sender {0}\r\ne:{1}\r\nSize{2}", sender.ToString(), e.ToString(), sd.ToString()));
        }

        private void WriteOut(object obj) {
            if (InvokeRequired) {
                WriteOutputDel del = new WriteOutputDel(WriteOut);
                Invoke(del, obj);
                return;
            }
            string s = obj.ToString();
            lblOutput.Text = s;
        }

        public bool Connect(SerialPort serialport) {
            if (!this.OpenSerialPort(serialport)) return false; //open a serial port            
            return true;
        }

        public bool OpenSerialPort(System.IO.Ports.SerialPort serialPort1) {
            try {
                if (serialPort1.IsOpen) serialPort1.Close();
                serialPort1.ReadBufferSize = buffersize;
                serialPort1.Open();
                return true;
            } catch (Exception ex) {
                MessageBox.Show("Cann't open serial port." + ex.Message);
                return false;
            }
        }

        private void StartCOMPortListner() {
            t = new Thread(new ThreadStart(Start));
            t.Start();
        }

        private void Start() {
            string line;
            WriteOutputDel del = new WriteOutputDel(WriteOut);
            while (true) {
                try {
                    Thread.Sleep(500);
                   line = sp.ReadLine();

                    if (line != null) {
                        try {
                            if (line.StartsWith("$GPRMC")) {
                                Util.SaveToBatchSend(line);                                                                                            
                                Invoke(del, line);
                            }
                        } catch (Exception ex) {
                            Invoke(del, "Error in Start function:\n" + ex.Message);
                        }                       
                    }
                } catch (Exception ex) {
                    Invoke(del, "Read COM Port input Error");
                    Thread.Sleep(1000);
                }
            }
        }

        //void ProcessServiceInformation(IAsyncResult status) {            
        //    WriteOutputDel del = new WriteOutputDel(WriteOut);
        //    try {
        //        if (status.IsCompleted) {
        //            //Try to send all the batch data;
        //            Invoke(del, "\r\n Sending Batch file");
        //            Application.DoEvents();
        //            Thread.Sleep(sendInterval);
        //            Util.SendBatchData();
        //        } 
        //        gpsSvc.EndConnected(status);
        //    } catch (Exception ex) {
        //        Invoke(del, ex.Message);
        //    } 
        //}

        private void LogData(string line) {
            if (swLogFile != null) {
                swLogFile.WriteLine(line);
                swLogFile.Flush();
            } else {
                WriteOut(line);
            }
        }

        private void mnuConfigure_Click(object sender, EventArgs e) {
            Config frmConfig = new Config();
            frmConfig.ShowDialog();
            ReadConfig();
        }

        private void mnuExit_Click(object sender, EventArgs e) {
            try {
                try { t.Abort(); } catch { }
                sp.Close();
                this.Close();
                Application.Exit();
            } catch { }
        }

        private void mnuClearLog_Click(object sender, EventArgs e) {
            try {
                Util.ClearLogFile(Util.GetLogFile());
            } catch { }
        }

        private void MainFrm_KeyDown(object sender, KeyEventArgs e) {
            if ((e.KeyCode == System.Windows.Forms.Keys.F1)) {
                // Soft Key 1
                // Not handled when menu is present.
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.F2)) {
                // Soft Key 2
                // Not handled when menu is present.
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Up)) {
                // Up
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down)) {
                // Down
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left)) {
                // Left
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right)) {
                // Right
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter)) {
                // Enter
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D1)) {
                // 1
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D2)) {
                // 2
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D3)) {
                // 3
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D4)) {
                // 4
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D5)) {
                // 5
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D6)) {
                // 6
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D7)) {
                // 7
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D8)) {
                // 8
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D9)) {
                // 9
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.F8)) {
                // *
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.D0)) {
                // 0
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.F9)) {
                // #
            }

        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Tateeda Media Networks
United States United States

Software development is my passion as well as photography.


If you got a sec stop by to see my photography work at http://sk68.com


Tateeda Media Network

Comments and Discussions