본문 바로가기
2_ 바삭바삭 프로그래밍/C# and Visual C++

C# - GPS_timer(3) : Client

by 준환이형님_ 2010. 7. 23.

단말기(클라이언트 역할)는 GPS값을 일정한 시간간격으로 받아와 그 밖의 정보(시간, 배터리상태)와 함께 TCP/IP 통신(단말기에서는 Wi-Pi)을 통해 서버로 보내준 뒤 하단 리스트 박스에 로그를 남기게 됩니다.

실행순서는
 
1. PC에서 서버를 우선 실행하면 자신의 아이피를 출력한뒤 클라이언트의 접속을 대기 하게 됩니다.


2. 윈모폰에서 클라이언트를 실행합니다.(SMS는 지원하지 않습니다. 단말기는 항상 무선인터넷이 가능해야 해요)


3. 서버의 주소와 GPS를 받아올 시간간격을 정한 뒤 확인 버튼을 누릅니다.


본래 단순히 [시간간격에 따른 GPS 수신 배터리 체크 프로그램]이었는데
이런저런 기능을 넣다보니.. 어느덧 산에 조금 올라가 있군요 :D


 
using System;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Status;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Microsoft.WindowsMobile.Samples.Location;

namespace SmartDeviceProject1
{
    public partial class Form1 : Form
    {
        private SystemState battery;
        Gps gps;
        String state = "수신미확인 ";
        String Level_val = "배터리미확인 ";
        String text_IP1 = "";
        String text_IP2 = "";
        String text_IP3 = "";
        String text_IP4 = "";        
        BatteryLevel Level;
        int checktime = 10;
        int linecounter = 0;
        int ontimer = 0;      

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            // 초침의 시작위치를 구하기 위해
            // 현재 몇 초인지 구한다.
            battery = new SystemState(SystemProperty.PowerBatteryStrength);
            battery.Changed += new ChangeEventHandler(batteryState_changed);
            UpdateBatteryStrength(SystemState.PowerBatteryStrength);
            Level = new BatteryLevel();

            float startS = DateTime.Now.Second;
            gps = new Gps();
            gps.Open();  //GPS 활성화            

            listBox4.Items.Add(" GPS 체크 간격과 IP주소 입력");
            listBox5.Items.Add(" -");
            listBox6.Items.Add(" -");
            listBox7.Items.Add(" -");            
        }

        void batteryState_changed(object sender, ChangeEventArgs args)
        {
            UpdateBatteryStrength((BatteryLevel)args.NewValue);
        }

        void UpdateBatteryStrength(BatteryLevel Level)
        {
            switch (Level)
            {
                case BatteryLevel.VeryHigh: Level_val = "100%미만"; break;
                case BatteryLevel.High: Level_val = "75%미만"; break;
                case BatteryLevel.Medium: Level_val = "50%미만"; break;
                case BatteryLevel.Low: Level_val = "25%미만"; break;
                case BatteryLevel.VeryLow: Level_val = "5%미만"; break;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            String s = "GPStimer";
          
            int hour = DateTime.Now.Hour - 1;
            int min = DateTime.Now.Minute;
            int sec = DateTime.Now.Second;

            label12.Text = hour.ToString();
            label13.Text = min.ToString();
            label14.Text = sec.ToString();

            if (ontimer == 1 && (min * 60 + sec) % checktime == 0)
            {

                listBox4.Items.Add(" " + hour.ToString() + ":" + min.ToString() + ":" + sec.ToString() + " - " + state + Level_val);
                linecounter++;

                GpsPosition position = gps.GetPosition(); //GPS  위치 정보를 가진 객체 생성

                double lat = position.Latitude;        //위도
                double lon = position.Longitude;       //경도

                listBox5.Items.Clear();
                listBox6.Items.Clear();
                listBox7.Items.Clear();

                listBox5.Items.Add(" " + lat);
                listBox6.Items.Add(" " + lon);
                listBox7.Items.Add(" " + position.SatelliteCount);
                label11.Text = " (" + hour.ToString() + ":" + min.ToString() + ":" + sec.ToString() + " Updated)";

                if (lat == 0) { state = "수신불량 "; } else { state = "수신양호 "; }

                listBox4.TopIndex = linecounter;

                //////////////////////////////////////////////////////////////////////////

                IPAddress ip = IPAddress.Parse(text_IP1 + "." + text_IP2 + "." + text_IP3 + "." + text_IP4);//인자값 : 서버측 IP
                IPEndPoint endPoint = new IPEndPoint(ip, 8000);//인자값 : IPAddress,포트번호
             
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    socket.Connect(endPoint);

                    byte[] sendBuffer = Encoding.UTF8.GetBytes(" " + lat + " " + lon + " " + position.SatelliteCount +
                    "  배터리 " + Level_val + " (" + hour.ToString() + ":" + min.ToString() + ":" + sec.ToString() + ")");

                    socket.Send(sendBuffer);
                    socket.Close();
                }
                catch{ }
            }
            /*  string ss = string.Format("{0}시 {1}분 {2}초", hour, min, sec);     */

            s += " - " + state;

            this.Text = s;

            // 1초마다 Invalidate() 를 호출한다.
            // Invalidate() 는 OnPaint() 를 자동으로 호출한다.
            // 초침이 이동한 것을 반영하여 다시 그린다.
            this.Invalidate(); // 새로 갱신->OnPaint 호출
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (textBox5.Text == " -" || textBox5.Text == "0") { checktime = 10; textBox5.Text = "10"; } else { checktime = Convert.ToInt16(textBox5.Text); }
            listBox4.Items.Clear();
            listBox4.Items.Add(" GPS의 체크간격을 " + checktime + "초로 합니다");
            linecounter = 0;
            ontimer = 1;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox5.Items.Clear();
            listBox6.Items.Clear();
            listBox7.Items.Clear();
            
            listBox5.Items.Add(" -");
            listBox6.Items.Add(" -");
            listBox7.Items.Add(" -");

            label11.Text = "(Reseted)";
            listBox4.Items.Add(" 초기화 하였습니다");
            textBox5.Text = " -";

            linecounter++;
            ontimer = 0;
            listBox4.TopIndex = linecounter;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            text_IP1 = textBox1.Text;
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            text_IP2 = textBox2.Text;
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            text_IP3 = textBox3.Text;
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            text_IP4 = textBox4.Text;
        }
    }
}