Tra cứu thông tin và điều khiển thiết bị điện qua tin nhắn sms

LỜI NÓI ĐẦU Cùng với thoại, SMS là một trong những tính năng được khai thác nhiều nhất của thiết bị di động (DĐ) cầm tay. SMS đang được ứng dụng ngày càng sâu rộng, mang lại hiệu quả kinh tế và là phương tiện giải trí cho số đông người dùng, đặc biệt là giới trẻ. Tuy nhiên, SMS đi cùng một số rủi ro, nên có những dịch vụ quy định người chi tiêu thường xuyên 3 triệu đồng/tháng trở lên mới được sử dụng . SMS (Short Message Service - dịch vụ thông điệp ngắn gọn) là dịch vụ cho phép gửi những tin nhắn ngắn 160 ký tự. Đối tượng là các thiết bị DĐ như ĐTDĐ, Smartphones, PDAs. Hiện cách thức mở rộng của SMS khá rộng như: gửi SMS giữa các thiết bị DĐ với nhau; gửi từ website đến thiết bị DĐ và ngược lại; gửi/nhận từ điện thoại cố định có hỗ trợ tính năng nhắn tin với các thiết bị DĐ khác . SMS có thể tham gia các quá trình điều khiển, tự động hóa, kinh doanh, thanh toán . Hiện tại, ngay cả các cửa hàng kinh doanh viễn thông, các công ty tin học và nhiều cơ quan truyền thông cũng đã tham gia vào thị trường này. SMS đang trở thành một loại hạ tầng thông tin không thể thiếu trong cuộc sống thường ngày từ vui chơi giải trí, thương mại, xã hội . Ứng dụng tra cứu thông tin, giải trí là loại ứng dụng phổ thông nhất của SMS và đang được sử dụng nhiều nhất hiện nay. Người sử dụng chỉ việc nhắn tin theo cú pháp định sẵn đến 1 số tổng đài nhất định, tổng đài sẽ tra cứu thông tin và phản hồi về (tra cứu thông tin) hoặc sẽ xác nhận người sử dụng tham gia vào một chương trình giải trí nào đó (đố vui, trúng thưởng .). Có thể kể đến các ứng dụng cụ thể như tra cứu danh bạ điện thoại; địa chỉ nhà hàng, khách sạn; địa chỉ đặt ATM; giá cổ phiếu; kết quả xổ số, bóng đá . Một số khả năng của SMS đã được khai thác trên thế giới và chắc chắn cũng sẽ có mặt ở Việt Nam. Ví dụ, dùng SMS điều khiển từ xa. Ông Ngô Chí Đức, công ty SQS cũng tỏ ra rất tâm huyết với phương án dùng SMS điều khiển từ xa các thiết bị điện trong nhà. Trong khi đó, ông Nguyễn Anh Tiến, trưởng phòng CNTT công ty Tân Lai, TP.HCM cho biết, bài toán này đã được ứng dụng ở một số nước (bật tắt các thiết bị điện trong nhà) và TP.HCM có một nhóm đã nghiên cứu đề tài này. Từ những yêu cầu thực tế, những đòi hỏi ngày càng cao của cuộc sống, cộng với sự hợp tác, phát triển mạnh mẽ của mạng di động nên chúng em đã chọn đề tài "Tra cứu thông tin và Điều khiển thiết bị điện qua Tin nhắn SMS" để đáp ứng được nhu cầu ngày càng cao của con người và góp phần vào sự tiến bộ, văn minh, hiện đại của nước nhà. Đề tài này được chia làm 3 phần như sau: o Phần A. Giới thiệu (Lời cảm ơn, lời nói đầu, mục lục ) o Phần B. Nội dung chính của đề tài (chương 1 đến chương 6) o Phần C. Phụ lục và tài liệu tham khảo Mặc dù em đã có nhiều cố gắng trong quá trình viết báo cáo, nhưng chắc chắn không tránh khỏi những khiếm khuyết. Vì vậy rất mong nhận được sự góp ý từ quý Thầy GIỚI HẠN ĐỀ TÀI Để thực thi một hệ thống điều khiển thiết bị từ xa thông qua tin nhắn SMS áp dụng cho một ngôi nhà hoàn chỉnh như nói trên là rất phức tạp và rất tốn kém. Để đáp ứng việc điều khiển toàn bộ các thiết bị này đòi hỏi phải có một lượng thời gian, kiến thức nhất định. Bên cạnh đó còn là vấn đề tài chính. Với lượng thời gian và kiến thức có hạn, trong đề tài này nhóm em chỉ thực thi một phần của hệ thống hoàn chỉnh đó. Đó là điều khiển đóng mở đèn, quạt Với những gì đã trình bày trên, nhóm em đã tiến hành nghiên cứu, khảo sát và thực hiện và dự kiến đạt được các mục tiêu đặt ra như sau:  Nhận tin nhắn đến, phân tích nội dung xem tin nhắn yêu cầu tra cứu điểm của học sinh nào và tự động trả lời  Điều khiển các thiết bị trong nhà (cụ thể là điều khiển một thiết bị công suất trung bình) bằng tin nhắn SMS tại ví trí có phủ sóng của mạng thông tin di động trong nước như viettel, mobifone, vinaphone  Tự động gửi tin nhắn ngược trở lại cho người điều khiển, với nội dung tin nhắn chứa thông tin hoạt động của thiết bị (on/off) TP. Hồ Chí Minh, Ngày 4 Tháng 1 Năm 2011 “Tra cứu thông tin và Điều khiển thiết bị điện qua tin nhắn” Trang| vii MỤC LỤC LỜI CẢM ƠN . . i QUYẾT ĐỊNH GIAO ĐỀ TÀI . . ii NHẬN XÉT CỦA GIÁO VIÊN HƯỚNG DẪN . . iii NHẬN XÉT CỦA GIÁO VIÊN PHẢN BIỆN . . iv LỜI NÓI ĐẦU . . v MỤC LỤC . . vii TỪ VIẾT TẮT . . x LIỆT KÊ HÌNH . xi LIỆT KÊ BẢNG . . xiii CHƯƠNG 1.TỔNG QUÁT VỀ HỆ THỐNG THÔNG TIN DI ĐỘNG GSM VÀ TIN NHẮN SMS . 1 1.1 TỔNG QUÁT VỀ HỆ THỐNG THÔNG TIN DI ĐỘNG GSM . 1 1.1.1 Giới thiệu . . 1 1.1.2 Cấu trúc mạng GSM . . 2 1.2 TỔNG QUÁT VỀ TIN NHẮN SMS . . 9 1.2.1 Giới thiệu SMS . . 9 1.2.2 Cấu trúc một tin nhắn SMS . . 11 1.2.3 Tin nhắn SMS chuỗi/ Tin nhắn SMS dài . 11 1.2.4 SMS Centre /SMSC . . 11 1.2.5 Nhắn tin SMS quốc tế . . 12 CHƯƠNG 2.GSM MODEM, TẬP LỆNH AT . 13 2.1 GSM MODEM . . 13 2.1.1 Giới thiệu . . 13 2.1.2 WAVECOM Fastrack Supreme 20 . . 13 2.2 TẬP LỆNH AT DÙNG CHO SMS . . 16 2.2.1 Giới thiệu . . 16 2.2.2 Tập lệnh AT dùng cho dịch vụ cuộc gọi và SMS . . 17 CHƯƠNG 3.VI ĐIỀU KHIỂN AT89S52 VÀ LCD HD44780 . 25 3.1 VI ĐIỀU KHIỂN AT89S52 . . 25 3.1.1 Giới thiệu . . 25 3.1.2 Tổ chức bộ nhớ của AT89S52 . 27 3.1.3 Timer . . 30 3.1.4 Truyền dữ liệu nối tiếp . 32 3.1.5 Tóm tắt tập lệnh của vi điều khiển AT89S52 . . 34 3.2 LCD HD44780 . . 36 3.2.1 Chức năng các chân LCD 16x2 . . 36 3.2.2 Sơ đồ khối của LCD 16x2 . . 37 3.2.3 Các thanh ghi và vùng RAM của LCD . 38 CHƯƠNG 4. XÂY DỰNG HỆ THỐNG TRA CỨU THÔNG TIN QUA TIN NHẮN . 48 4.1 SƠ ĐỒ KHỐI . 49 4.2 LƯU ĐỒ . 50 4.3 THIẾT KẾ . 51 4.3.1 Một số hàm cơ bản liên quan đến lập trình SMS . 51 4.3.2 Kết nối Access Database với C# . 51 4.3.3 Truyền nhận dữ liệu qua cổng com (RS232) . 53 4.3.4 Làm việc với chuỗi . 59 4.3.5 Cơ sở dữ liệu . 59 4.3.6 Cấu hình Modem GSM . 60 4.4 GIAO DIỆN CHƯƠNG TRÌNH . 61 4.4.1 Cài đặt kết nối . 61 4.4.2 Giao diện chương trình chính . 61 4.4.3 Khi có tin nhắn tới . 62 4.4.4 Trong Tab Message gồm 4 menu: Send, Send Multiple, Read, Delete . 62 4.4.5 Menu Send . 63 4.4.6 Menu Send Multiple . 63 4.4.7 Menu Read Message . 63 4.4.8 Menu Delete . 64 4.5 TESTING . 64 CHƯƠNG 5. THIẾT KẾ, THI CÔNG MẠCH ĐIỀU KHIỂN THIẾT BỊ ĐIỆN QUA TIN NHẮN . . 68 5.1 SƠ ĐỒ KHỐI . . 68 5.2 THIẾT KẾ MẠCH . 68 5.2.1 Khối GSM Modem . . 68 5.2.2 Khối hiển thị . 72 5.2.3 Khối Relay . 73 5.3 LƯU ĐỒ CHƯƠNG TRÌNH . . 73 5.4 TESTING . . 82 CHƯƠNG 6.KẾT LUẬN, HƯỚNG PHÁT TRIỂN ĐỀ TÀI . . 87 6.1 KẾT LUẬN . . 87 6.2 HƯỚNG PHÁT TRIỂN ĐỀ TÀI . . 87 PHỤ LỤC . 89 A. BẢNG MÃ ASCII . . 89 B. GSM EQUIPMENT AND NETWORK ERROR CODES . . 98 C. CÚ PHÁP TIN NHẮN . . 102 D. HƯỚNG DẪN KẾT NỐI VÀ SỬ DỤNG . 104 E. CODE CHƯƠNG TRÌNH ĐIỀU KHIỂN THIẾT BỊ . . 110 F. CODE CHƯƠNG TRÌNH TRA CỨU . 121 TÀI LIỆU THAM KHẢO . . 160

pdf173 trang | Chia sẻ: lvcdongnoi | Lượt xem: 2891 | Lượt tải: 2download
Bạn đang xem trước 20 trang tài liệu Tra cứu thông tin và điều khiển thiết bị điện qua tin nhắn sms, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
.DefaultTimeout; PortAccess.Output(888, 0); frmConnection dlg = newfrmConnection(); dlg.StartPosition = FormStartPosition.CenterScreen; dlg.SetData(port, baudRate, timeout); if (dlg.ShowDialog(this) == DialogResult.OK) { dlg.GetData(out port, out baudRate, out timeout); CommSetting.Comm_Port = port; CommSetting.Comm_BaudRate = baudRate; CommSetting.Comm_TimeOut = timeout; } else { Close(); return; } Cursor.Current = Cursors.WaitCursor; CommSetting.comm = newGsmCommMain(port, baudRate, timeout); Cursor.Current = Cursors.Default; CommSetting.comm.PhoneConnected += newEventHandler(comm_PhoneConnected); //thông báo khi có tin nhắn mới CommSetting.comm.MessageReceived += newMessageReceivedEventHandler(comm_MessageReceived); //comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived) //CommSetting.comm.EnableMessageNotifications(); //CommSetting.comm.EnableMessageNotifications(); //CommSetting.comm.EnableMessageRouting(); Output("Message notifications activated."); Output(""); Cursor.Current = Cursors.Default; bool retry; do { retry = false; try { Cursor.Current = Cursors.WaitCursor; CommSetting.comm.Open(); Cursor.Current = Cursors.Default; } catch (Exception) { Cursor.Current = Cursors.Default; if (MessageBox.Show(this, "Unable to open the port.", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry) retry = true; else { Close(); return; } T r a n g | 132 Đồ án tốt nghiệp } } while (retry); } privatedelegatevoidConnectedHandler(bool connected); privatevoid OnPhoneConnectionChange(bool connected) { lbl_phone_status.Text = "CONNECTED"; } privatevoid comm_MessageReceived(object sender, GsmComm.GsmCommunication.MessageReceivedEventArgs e) { Cursor.Current = Cursors.WaitCursor; try { IMessageIndicationObject obj = e.IndicationObject; MemoryLocation loc = (MemoryLocation)obj; //Output(string.Format("New message received in storage \"{0}\", index {1}.", // loc.Storage, loc.Index)); index = loc.Index; } catch (Exception E) { MessageBox.Show("Error occured: " + E.Message); } MessageReceived(); XuLyTinNhan(); GuiTinTraLoi(); noidungTN = ""; DecodedShortMessage[] msgs = CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, PhoneStorageType.Sim); foreach (DecodedShortMessage msg in msgs) { Output(string.Format("Message status = {0}, Location = {1}/{2}", StatusToString(msg.Status), msg.Storage, msg.Index)); ShowMessage(msg.Data); Output(""); if (!(noidungTN == "")) { XuLyTinNhan(); GuiTinTraLoi(); } } Cursor.Current = Cursors.Default; } privatevoid MessageReceived() { DecodedShortMessage message = CommSetting.comm.ReadMessage(index, PhoneStorageType.Sim); Output(string.Format("Message status = {0}, Location = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index)); ShowMessage(message.Data); SmsDeliverPdu data = (SmsDeliverPdu)message.Data; xNumber = data.OriginatingAddress; noidungTN = data.UserDataText; } privatevoid XuLyTinNhan() { if (noidungTN.Length>=4) { T r a n g | 133 Đồ án tốt nghiệp string noidung = noidungTN.Substring(0,3); string TTGV = noidungTN.Substring(0,5); if (noidung == "DT " || TTGV=="TT GV") { if (noidung == "DT ") { TraDatabaseHS(); } if (TTGV=="TT GV") { TraDatabaseGV(); } } else { xMessage = "Cu phap khong dung!"; } } else { xMessage = "Cu phap khong dung!"; } } /// /// Tra database lấy du lieu. /// privatevoid TraDatabaseHS() { NoiDungTra = noidungTN.Substring(3, 4); string conString = @"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=D:\DATA.mdb"; OleDbConnection conn = newOleDbConnection(conString); try { // create an open the connection conn.Open(); // create the adapter and fill the DataSet OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT MSHS, Name, Toan, Ly, Hoa FROM Pupils WHERE MSHS = \'" + NoiDungTra + "\'", conn); dataSet1.Clear(); int numberOfRowsFeched = adapter1.Fill(dataSet1, "Pupils"); if (numberOfRowsFeched > 0) { DataTable dt = dataSet1.Tables["Pupils"]; xMessage = "MSHS:" + " " + dt.Rows[0][0] + ", " + dt.Rows[0][1] + ": Toan: " + dt.Rows[0][2].ToString() + ", Ly: " + dt.Rows[0][3].ToString() + ", Hoa: " + dt.Rows[0][4].ToString(); } else { xMessage = "ID not found."; } } catch (Exception E) { MessageBox.Show("Error occured: " + E.Message); } finally { conn.Close(); } T r a n g | 134 Đồ án tốt nghiệp } privatevoid TraDatabaseGV() { NoiDungTra = noidungTN.Substring(3, 5); string conString = @"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=D:\DATA.mdb"; OleDbConnection conn = newOleDbConnection(conString); try { // create an open the connection conn.Open(); // create the adapter and fill the DataSet OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT MSGV, Name, HocVi, Mobile, Email FROM Teachers WHERE MSGV = \'" + NoiDungTra + "\'", conn); dataSet1.Clear(); int numberOfRowsFeched = adapter1.Fill(dataSet1, "Teachers"); if (numberOfRowsFeched > 0) { DataTable dt = dataSet1.Tables["Teachers"]; xMessage = "MSGV:" + dt.Rows[0][0] + ", " + dt.Rows[0][1] + ", Hoc vi: " + dt.Rows[0][2] + ", Mobile: " + dt.Rows[0][3] + ", Email: " + dt.Rows[0][4]; } else { xMessage = "ID not found."; } } catch (Exception E) { MessageBox.Show("Error occured: " + E.Message); } finally { conn.Close(); } } /// /// Gửi tin nhắn trả lời. /// privatevoid GuiTinTraLoi() { try { // Send an SMS message SmsSubmitPdu pdu; string smsc = "+84900000022"; pdu = newSmsSubmitPdu(xMessage, xNumber, smsc); CommSetting.comm.SendMessage(pdu); Output("1 Message sent to " + xNumber); Output(""); if (index == 10) { int index_del; index_del = 1; // Delete the message with the specified index from storage CommSetting.comm.DeleteMessage(index_del, PhoneStorageType.Sim); index_del = 2; // Delete the message with the specified index from storage CommSetting.comm.DeleteMessage(index_del, PhoneStorageType.Sim); index_del = 9; T r a n g | 135 Đồ án tốt nghiệp // Delete the message with the specified index from storage CommSetting.comm.DeleteMessage(index_del, PhoneStorageType.Sim); index_del = 10; // Delete the message with the specified index from storage CommSetting.comm.DeleteMessage(index_del, PhoneStorageType.Sim); //MessageBox.Show("Message With Index " + index_del + " Deleted", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } //} } catch (Exception ex) { MessageBox.Show(ex.Message); } } privatevoid comm_PhoneConnected(object sender, EventArgs e) { this.Invoke(newConnectedHandler(OnPhoneConnectionChange), newobject[] { true }); } privatestring StatusToString(PhoneMessageStatus status) { // Map a message status to a string string ret; switch (status) { casePhoneMessageStatus.All: ret = "All"; break; casePhoneMessageStatus.ReceivedRead: ret = "Read"; break; casePhoneMessageStatus.ReceivedUnread: ret = "Unread"; break; casePhoneMessageStatus.StoredSent: ret = "Sent"; break; casePhoneMessageStatus.StoredUnsent: ret = "Unsent"; break; default: ret = "Unknown (" + status.ToString() + ")"; break; } return ret; } privatevoid Output(string text) { if (this.txtOutput.InvokeRequired) { SetTextCallback stc = newSetTextCallback(Output); this.Invoke(stc, newobject[] { text }); } else { txtOutput.AppendText(text); txtOutput.AppendText("\r\n"); } } T r a n g | 136 Đồ án tốt nghiệp privatevoid ShowMessage(SmsPdu pdu) { if (pdu isSmsSubmitPdu) { // Stored (sent/unsent) message SmsSubmitPdu data = (SmsSubmitPdu)pdu; Output("SENT/UNSENT MESSAGE"); Output("Recipient: " + data.DestinationAddress); Output("Message text: " + data.UserDataText); Output("-----------------------); return; } if (pdu isSmsDeliverPdu) { // Received message SmsDeliverPdu data = (SmsDeliverPdu)pdu; Output("RECEIVED MESSAGE"); Output("Sender: " + data.OriginatingAddress); Output("Sent: " + data.SCTimestamp.ToString()); Output("Message text: " + data.UserDataText); xNumber = data.OriginatingAddress; noidungTN = data.UserDataText; Output("-----------------------------------------"); return; } if (pdu isSmsStatusReportPdu) { // Status report SmsStatusReportPdu data = (SmsStatusReportPdu)pdu; Output("STATUS REPORT"); Output("Recipient: " + data.RecipientAddress); Output("Status: " + data.Status.ToString()); Output("Timestamp: " + data.DischargeTime.ToString()); Output("Message ref: " + data.MessageReference.ToString()); Output("-----------------------------------------"); return; } Output("Unknown message type: " + pdu.GetType().ToString()); } privatevoid mnu_send_click(object sender, System.EventArgs e) { Send send_sms = newSend(); send_sms.Show(); } privatevoid mnu_read_click(object sender, System.EventArgs e) { Receive receice_sms = newReceive(); receice_sms.Show(); } privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Clean up comm object if (CommSetting.comm != null) { // Unregister events CommSetting.comm.PhoneConnected -= newEventHandler(comm_PhoneConnected); CommSetting.comm.MessageReceived -= newMessageReceivedEventHandler(comm_MessageReceived); // Close connection to phone T r a n g | 137 Đồ án tốt nghiệp if (CommSetting.comm != null&&CommSetting.comm.IsOpen()) CommSetting.comm.Close(); CommSetting.comm = null; } } publicvoid ExitApplication() { // Display a message box asking users if they // want to exit the application. if (MessageBox.Show("Do you want to exit?", "My Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Application.Exit(); } } privatevoid aboutToolStripMenuItem1_Click(object sender, EventArgs e) { MessageBox.Show("Trường Đại học Sư phạm Kỹ thuật TPHCM\nKhoa Điện - Điện tử\nĐồ án tốt nghiệp ngành Điện tử viễn thông\n'Tra cứu thông tin và Điều khiển thiết bị điện qua tin nhắn SMS'\nGiáo viên hướng dẫn: ThS. Đinh Quốc Hùng\nSinh viên thực hiện: Lưu Văn Đại, Trần Hoàng Lê Chuyên\nTháng 1 năm 2011\nContact Us: luudai511@gmail.com", "About", MessageBoxButtons.OK, MessageBoxIcon.Information); } privatevoid sendToolStripMenuItem_Click(object sender, EventArgs e) { Send send_sms = newSend(); send_sms.Show(); } privatevoid sendMultipleToolStripMenuItem_Click(object sender, EventArgs e) { SendMulti sendMulti_sms = newSendMulti(); sendMulti_sms.Show(); } privatevoid readToolStripMenuItem_Click(object sender, EventArgs e) { Receive receice_sms = newReceive(); receice_sms.Show(); } privatevoid deleteToolStripMenuItem_Click(object sender, EventArgs e) { Delete delete = newDelete(); delete.Show(); } privatevoid aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Trường Đại học Sư phạm Kỹ thuật TPHCM\nKhoa Điện - Điện tử\nĐồ án tốt nghiệp ngành Điện tử viễn thông\n'Tra cứu thông tin và Điều khiển thiết bị điện qua tin nhắn SMS'\nGiáo viên hướng dẫn: ThS. Đinh Quốc Hùng\nSinh viên thực hiện: Lưu Văn Đại, Trần Hoàng Lê Chuyên\nTháng 1 năm 2011\nContact Us: luudai511@gmail.com", "About", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } 3. Send Multiple SMS T r a n g | 138 Đồ án tốt nghiệp using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using GsmComm.PduConverter; using GsmComm.GsmCommunication; namespace SMS { publicpartialclassSendMulti : Form { privatedelegatevoidSetTextCallback(string text); string timlop, xNumber, xlop, ten, lop; int numberOfRowsFeched; DataTable dt; public SendMulti() { InitializeComponent(); cmbk12.Items.Add("12A1"); cmbk12.Items.Add("12A2"); cmbk12.Items.Add("12A3"); cmbk12.Items.Add("Ca khoi 12"); cmbk11.Items.Add("11A1"); cmbk11.Items.Add("11A2"); cmbk11.Items.Add("11A3"); cmbk11.Items.Add("Ca khoi 11"); cmbk10.Items.Add("10A1"); cmbk10.Items.Add("10A2"); cmbk10.Items.Add("10A3"); cmbk10.Items.Add("Ca khoi 10"); cmbgv.Items.Add("GVT"); cmbgv.Items.Add("GVL"); cmbgv.Items.Add("GVH"); cmbgv.Items.Add("All GV"); } privatevoid SendMulti_Load(object sender, System.EventArgs e) { T r a n g | 139 Đồ án tốt nghiệp chkMultipleTimes.Checked = true; } privatevoid cmbk12_SelectedIndexChanged(object sender, EventArgs e) { timlop = cmbk12.SelectedItem.ToString(); kiemtraHS(); textBox1.Text = "Chọn gửi tới: " + cmbk12.SelectedItem + "\r\nTổng số: " + numberOfRowsFeched.ToString(); } privatevoid cmbk11_SelectedIndexChanged(object sender, EventArgs e) { timlop = cmbk11.SelectedItem.ToString(); kiemtraHS(); textBox1.Text = "Chọn gửi tới: " + cmbk11.SelectedItem + "\r\nTổng số: " + numberOfRowsFeched.ToString(); } privatevoid cmbk10_SelectedIndexChanged(object sender, EventArgs e) { timlop = cmbk10.SelectedItem.ToString(); kiemtraHS(); textBox1.Text = "Chọn gửi tới: " + cmbk10.SelectedItem + "\r\nTổng số: " + numberOfRowsFeched.ToString(); } privatevoid cmbgv_SelectedIndexChanged(object sender, EventArgs e) { timlop = cmbgv.SelectedItem.ToString(); kiemtraGV(); textBox1.Text = "Chọn gửi tới: " + cmbgv.SelectedItem + "\r\nTổng số: " + numberOfRowsFeched.ToString(); } privatevoid btnbochon_Click(object sender, EventArgs e) { textBox1.Text = ""; timlop = ""; } privatevoid BtnClear_Click(object sender, System.EventArgs e) { txt_message.Text = ""; txt_message.Focus(); } privatevoid textBox1_TextChanged(object sender, System.EventArgs e) { int remaining = int.Parse(txt_text_remaining.Text.Trim()); remaining -= 1; txt_text_remaining.Text = remaining.ToString(); } privatevoid kiemtraHS() { Cursor.Current = Cursors.WaitCursor; string conString = @"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=D:\DATA.mdb"; OleDbConnection conn = newOleDbConnection(conString); try { // create an open the connection conn.Open(); // create the adapter and fill the DataSet if (timlop == "Ca khoi 12") { timlop = "12A"; xlop = "HS"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name, Class FROM Pupils WHERE LEFT(Class ,3) = \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Pupils"); T r a n g | 140 Đồ án tốt nghiệp dt = dataSet1.Tables["Pupils"]; } elseif (timlop == "Ca khoi 11") { timlop = "11A"; xlop = "HS"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name, Class FROM Pupils WHERE LEFT(Class ,3) = \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Pupils"); dt = dataSet1.Tables["Pupils"]; } elseif (timlop == "Ca khoi 10") { timlop = "10A"; xlop = "HS"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name, Class FROM Pupils WHERE LEFT(Class ,3) = \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Pupils"); dt = dataSet1.Tables["Pupils"]; } else { xlop = "HS"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name, Class FROM Pupils WHERE Class = \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Pupils"); dt = dataSet1.Tables["Pupils"]; } } catch (Exception E) { MessageBox.Show("Error occured: " + E.Message); } finally { conn.Close(); } } privatevoid kiemtraGV() { Cursor.Current = Cursors.WaitCursor; string conString = @"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=D:\DATA.mdb"; OleDbConnection conn = newOleDbConnection(conString); try { // create an open the connection conn.Open(); // create the adapter and fill the DataSet if (timlop == "All GV") { timlop = "GV"; xlop = "GV"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name FROM Teachers WHERE Left(MSGV ,2)= \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Teachers"); dt = dataSet1.Tables["Teachers"]; } else T r a n g | 141 Đồ án tốt nghiệp { xlop = "GV"; OleDbDataAdapter adapter1 = newOleDbDataAdapter("SELECT Mobile, Name, ChuyenMon FROM Teachers WHERE Left(MSGV ,3)= \'" + timlop + "\'", conn); dataSet1.Clear(); numberOfRowsFeched = adapter1.Fill(dataSet1, "Teachers"); dt = dataSet1.Tables["Teachers"]; } } catch (Exception E) { MessageBox.Show("Error occured: " + E.Message); } finally { conn.Close(); } } privatevoid btnSendMessage_Click(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; for (int i = 0; i < numberOfRowsFeched; i++) { xNumber = dt.Rows[i][0].ToString(); ten = dt.Rows[i][1].ToString(); //Output(xNumber); GuiTinNhan(); if (xlop == "HS") { lop = dt.Rows[i][2].ToString(); ten = dt.Rows[i][1].ToString(); Output("Đã gửi thông báo đến Phụ huynh em: " + ten + ", Lớp" + lop); Output(""); } else { lop = dt.Rows[i][2].ToString(); Output("Đã gửi thông báo đến giáo viên : " + ten + ", Chuyên môn: "+ dt.Rows[i][2].ToString()); Output(""); } } Cursor.Current = Cursors.Default; } privatevoid GuiTinNhan() { // Send an SMS message SmsSubmitPdu pdu; bool alert = chkAlert.Checked; bool unicode = chkUnicode.Checked; string smsc = "+84900000022";//smscMobifone if (!alert && !unicode) { // The straightforward version pdu = newSmsSubmitPdu(txt_message.Text, xNumber, smsc); // "" indicate SMSC No } else { // The extended version with dcs byte dcs; T r a n g | 142 Đồ án tốt nghiệp if (!alert && unicode) dcs = DataCodingScheme.NoClass_16Bit; elseif (alert && !unicode) dcs = DataCodingScheme.Class0_7Bit; elseif (alert && unicode) dcs = DataCodingScheme.Class0_16Bit; else dcs = DataCodingScheme.NoClass_7Bit; // should never occur here pdu = newSmsSubmitPdu(txt_message.Text, xNumber, smsc, dcs); } // Send the same message multiple times if this is set int times = chkMultipleTimes.Checked ? int.Parse(txtSendTimes.Text) : 1; // Send the message the specified number of times for (int i = 0; i < times; i++) { CommSetting.comm.SendMessage(pdu); } } privatevoid Output(string text) { if (this.txtOutput.InvokeRequired) { SetTextCallback stc = newSetTextCallback(Output); this.Invoke(stc, newobject[] { text }); } else { txtOutput.AppendText(text); txtOutput.AppendText("\r\n"); } } } } 4. Send using System; using System.Drawing; using System.Collections; using System.ComponentModel; T r a n g | 143 Đồ án tốt nghiệp using System.Windows.Forms; using GsmComm.PduConverter; using GsmComm.GsmCommunication; namespace SMS { /// /// Summary description for Send. /// publicclassSend : System.Windows.Forms.Form { private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txt_destination_numbers; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txt_text_remaining; private System.Windows.Forms.Button btnSendMessage; private System.Windows.Forms.Button BtnClear; private System.Windows.Forms.TextBox txt_message; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.CheckBox chkUnicode; private System.Windows.Forms.CheckBox chkAlert; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label19; private System.Windows.Forms.TextBox txtSendTimes; private System.Windows.Forms.CheckBox chkMultipleTimes; /// /// Required designer variable. /// private System.ComponentModel.Container components = null; privatedelegatevoidSetTextCallback(string text); public Send() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protectedoverridevoid Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify T r a n g | 144 Đồ án tốt nghiệp /// the contents of this method with the code editor. /// privatevoid InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Send)); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.txt_destination_numbers = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txt_message = new System.Windows.Forms.TextBox(); this.txt_text_remaining = new System.Windows.Forms.TextBox(); this.btnSendMessage = new System.Windows.Forms.Button(); this.BtnClear = new System.Windows.Forms.Button(); this.txtOutput = new System.Windows.Forms.TextBox(); this.chkUnicode = new System.Windows.Forms.CheckBox(); this.chkAlert = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtSendTimes = new System.Windows.Forms.TextBox(); this.chkMultipleTimes = new System.Windows.Forms.CheckBox(); this.label19 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage"))) ; this.pictureBox1.Location = new System.Drawing.Point(0, 2); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(371, 104); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(0, 112); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 24); this.label1.TabIndex = 1; this.label1.Text = "Destination Number :"; // // txt_destination_numbers // this.txt_destination_numbers.Location = new System.Drawing.Point(0, 136); this.txt_destination_numbers.Name = "txt_destination_numbers"; this.txt_destination_numbers.Size = new System.Drawing.Size(224, 20); this.txt_destination_numbers.TabIndex = 2; this.txt_destination_numbers.Text = "+84"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(0, 168); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 16); this.label2.TabIndex = 3; this.label2.Text = "Message:"; T r a n g | 145 Đồ án tốt nghiệp // // txt_message // this.txt_message.Location = new System.Drawing.Point(0, 192); this.txt_message.Multiline = true; this.txt_message.Name = "txt_message"; this.txt_message.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txt_message.Size = new System.Drawing.Size(224, 112); this.txt_message.TabIndex = 4; this.txt_message.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // txt_text_remaining // this.txt_text_remaining.BackColor = System.Drawing.SystemColors.Control; this.txt_text_remaining.Enabled = false; this.txt_text_remaining.Location = new System.Drawing.Point(224, 288); this.txt_text_remaining.Name = "txt_text_remaining"; this.txt_text_remaining.Size = new System.Drawing.Size(40, 20); this.txt_text_remaining.TabIndex = 5; this.txt_text_remaining.Text = "160"; // // btnSendMessage // this.btnSendMessage.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnSendMessage.Location = new System.Drawing.Point(144, 320); this.btnSendMessage.Name = "btnSendMessage"; this.btnSendMessage.Size = new System.Drawing.Size(80, 24); this.btnSendMessage.TabIndex = 16; this.btnSendMessage.Text = "Send"; this.btnSendMessage.Click += new System.EventHandler(this.btnSendMessage_Click); // // BtnClear // this.BtnClear.FlatStyle = System.Windows.Forms.FlatStyle.System; this.BtnClear.Location = new System.Drawing.Point(56, 320); this.BtnClear.Name = "BtnClear"; this.BtnClear.Size = new System.Drawing.Size(80, 24); this.BtnClear.TabIndex = 17; this.BtnClear.Text = "Clear"; this.BtnClear.Click += new System.EventHandler(this.BtnClear_Click); // // txtOutput // this.txtOutput.Location = new System.Drawing.Point(0, 352); this.txtOutput.Multiline = true; this.txtOutput.Name = "txtOutput"; this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtOutput.Size = new System.Drawing.Size(504, 120); this.txtOutput.TabIndex = 56; // // chkUnicode // this.chkUnicode.FlatStyle = System.Windows.Forms.FlatStyle.System; this.chkUnicode.Location = new System.Drawing.Point(16, 56); this.chkUnicode.Name = "chkUnicode"; this.chkUnicode.Size = new System.Drawing.Size(208, 24); this.chkUnicode.TabIndex = 58; this.chkUnicode.Text = "Send as Unicode (UCS2)"; // // chkAlert // this.chkAlert.FlatStyle = System.Windows.Forms.FlatStyle.System; this.chkAlert.Location = new System.Drawing.Point(16, 24); this.chkAlert.Name = "chkAlert"; T r a n g | 146 Đồ án tốt nghiệp this.chkAlert.Size = new System.Drawing.Size(176, 24); this.chkAlert.TabIndex = 57; this.chkAlert.Text = "Request immediate display (alert)"; // // groupBox1 // this.groupBox1.Controls.Add(this.chkUnicode); this.groupBox1.Controls.Add(this.chkAlert); this.groupBox1.Controls.Add(this.txtSendTimes); this.groupBox1.Controls.Add(this.chkMultipleTimes); this.groupBox1.Controls.Add(this.label19); this.groupBox1.Location = new System.Drawing.Point(240, 112); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(264, 128); this.groupBox1.TabIndex = 59; this.groupBox1.TabStop = false; this.groupBox1.Text = "Option"; // // txtSendTimes // this.txtSendTimes.Location = new System.Drawing.Point(120, 88); this.txtSendTimes.Name = "txtSendTimes"; this.txtSendTimes.Size = new System.Drawing.Size(48, 20); this.txtSendTimes.TabIndex = 61; this.txtSendTimes.Text = "1"; // // chkMultipleTimes // this.chkMultipleTimes.FlatStyle = System.Windows.Forms.FlatStyle.System; this.chkMultipleTimes.Location = new System.Drawing.Point(16, 88); this.chkMultipleTimes.Name = "chkMultipleTimes"; this.chkMultipleTimes.Size = new System.Drawing.Size(104, 24); this.chkMultipleTimes.TabIndex = 60; this.chkMultipleTimes.Text = "Send message"; // // label19 // this.label19.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label19.Location = new System.Drawing.Point(176, 88); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(72, 23); this.label19.TabIndex = 62; this.label19.Text = "times"; this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // Send // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 478); this.Controls.Add(this.groupBox1); this.Controls.Add(this.txtOutput); this.Controls.Add(this.BtnClear); this.Controls.Add(this.btnSendMessage); this.Controls.Add(this.txt_text_remaining); this.Controls.Add(this.txt_message); this.Controls.Add(this.label2); this.Controls.Add(this.txt_destination_numbers); this.Controls.Add(this.label1); this.Controls.Add(this.pictureBox1); this.Name = "Send"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Send SMS"; this.Load += new System.EventHandler(this.Send_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBox1.ResumeLayout(false); T r a n g | 147 Đồ án tốt nghiệp this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion privatevoid textBox1_TextChanged(object sender, System.EventArgs e) { int remaining=int.Parse(txt_text_remaining.Text.Trim()); remaining-=1; txt_text_remaining.Text=remaining.ToString(); } privatevoid BtnClear_Click(object sender, System.EventArgs e) { txt_message.Text=""; txt_message.Focus(); } privatevoid btnSendMessage_Click(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; try { // Send an SMS message SmsSubmitPdu pdu; bool alert = chkAlert.Checked; bool unicode = chkUnicode.Checked; string smsc = "+84900000022"; if (!alert && !unicode) { // The straightforward version pdu = newSmsSubmitPdu(txt_message.Text, txt_destination_numbers.Text,smsc); // "" indicate SMSC No } else { // The extended version with dcs byte dcs; if (!alert && unicode) dcs = DataCodingScheme.NoClass_16Bit; elseif (alert && !unicode) dcs = DataCodingScheme.Class0_7Bit; elseif (alert && unicode) dcs = DataCodingScheme.Class0_16Bit; else dcs = DataCodingScheme.NoClass_7Bit; // should never occur here pdu = newSmsSubmitPdu(txt_message.Text, txt_destination_numbers.Text, smsc, dcs); } // Send the same message multiple times if this is set int times = chkMultipleTimes.Checked ? int.Parse(txtSendTimes.Text) : 1; // Send the message the specified number of times for (int i=0;i<times;i++) { CommSetting.comm.SendMessage(pdu); T r a n g | 148 Đồ án tốt nghiệp Output("Message {0} of {1} sent.", i+1, times); Output(""); } } catch(Exception ex) { MessageBox.Show(ex.Message); } Cursor.Current = Cursors.Default; } privatevoid Output(string text) { if (this.txtOutput.InvokeRequired) { SetTextCallback stc = newSetTextCallback(Output); this.Invoke(stc, newobject[] { text }); } else { txtOutput.AppendText(text); txtOutput.AppendText("\r\n"); } } privatevoid Send_Load(object sender, System.EventArgs e) { chkMultipleTimes.Checked=true; } privatevoid Output(string text, paramsobject[] args) { string msg = string.Format(text, args); Output(msg); } } } 5. Receive T r a n g | 149 Đồ án tốt nghiệp using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; using GsmComm.PduConverter; using GsmComm.GsmCommunication; namespace SMS { /// /// Summary description for Receive. /// publicclassReceive : System.Windows.Forms.Form { private System.Windows.Forms.Button btnReadMessage; private System.Windows.Forms.RadioButton rbMessagePhone; private System.Windows.Forms.RadioButton rbMessageSIM; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.DataGrid dataGrid1; /// /// Required designer variable. /// private System.ComponentModel.Container components = null; privateDataTable dt=newDataTable(); privatedelegatevoidSetTextCallback(string text); public Receive() { // T r a n g | 150 Đồ án tốt nghiệp // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protectedoverridevoid Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// privatevoid InitializeComponent() { this.btnReadMessage = new System.Windows.Forms.Button(); this.rbMessagePhone = new System.Windows.Forms.RadioButton(); this.rbMessageSIM = new System.Windows.Forms.RadioButton(); this.txtOutput = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // btnReadMessage // this.btnReadMessage.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnReadMessage.Location = new System.Drawing.Point(192, 80); this.btnReadMessage.Name = "btnReadMessage"; this.btnReadMessage.Size = new System.Drawing.Size(112, 24); this.btnReadMessage.TabIndex = 17; this.btnReadMessage.Text = "Read All Messages"; this.btnReadMessage.Click += new System.EventHandler(this.btnReadMessage_Click); // // rbMessagePhone // this.rbMessagePhone.FlatStyle = System.Windows.Forms.FlatStyle.System; this.rbMessagePhone.Location = new System.Drawing.Point(16, 56); this.rbMessagePhone.Name = "rbMessagePhone"; this.rbMessagePhone.Size = new System.Drawing.Size(64, 24); this.rbMessagePhone.TabIndex = 25; this.rbMessagePhone.TabStop = true; this.rbMessagePhone.Text = "Phone"; // // rbMessageSIM // T r a n g | 151 Đồ án tốt nghiệp this.rbMessageSIM.Checked = true; this.rbMessageSIM.FlatStyle = System.Windows.Forms.FlatStyle.System; this.rbMessageSIM.Location = new System.Drawing.Point(16, 24); this.rbMessageSIM.Name = "rbMessageSIM"; this.rbMessageSIM.Size = new System.Drawing.Size(64, 24); this.rbMessageSIM.TabIndex = 24; this.rbMessageSIM.TabStop = true; this.rbMessageSIM.Text = "SIM"; // // txtOutput // this.txtOutput.Location = new System.Drawing.Point(6, 304); this.txtOutput.Multiline = true; this.txtOutput.Name = "txtOutput"; this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtOutput.Size = new System.Drawing.Size(492, 144); this.txtOutput.TabIndex = 57; // // groupBox1 // this.groupBox1.Controls.Add(this.rbMessageSIM); this.groupBox1.Controls.Add(this.rbMessagePhone); this.groupBox1.Location = new System.Drawing.Point(8, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(176, 96); this.groupBox1.TabIndex = 58; this.groupBox1.TabStop = false; this.groupBox1.Text = "Message Storage"; // // dataGrid1 // this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(7, 120); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.RowHeadersVisible = false; this.dataGrid1.SelectionBackColor = System.Drawing.Color.CornflowerBlue; this.dataGrid1.Size = new System.Drawing.Size(492, 176); this.dataGrid1.TabIndex = 59; // // Receive // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 478); this.Controls.Add(this.dataGrid1); this.Controls.Add(this.groupBox1); this.Controls.Add(this.txtOutput); this.Controls.Add(this.btnReadMessage); this.Name = "Receive"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Read Messages"; this.Load += new System.EventHandler(this.Receive_Load); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion privatevoid btnReadMessage_Click(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; string storage = GetMessageStorage(); T r a n g | 152 Đồ án tốt nghiệp try { // Read all SMS messages from the storage DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage); foreach (DecodedShortMessage message in messages) { Output(string.Format("Message status = {0}, Location = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index)); ShowMessage(message.Data); Output(""); } Output(string.Format("{0,9} messages read.", messages.Length.ToString())); Output(""); } catch (Exception ex) { MessageBox.Show(ex.Message); } } privatevoid BindGrid(SmsPdu pdu) { DataRow dr = dt.NewRow(); SmsDeliverPdu data = (SmsDeliverPdu)pdu; dr[0] = data.OriginatingAddress.ToString(); dr[1] = data.SCTimestamp.ToString(); dr[2] = data.UserDataText; dt.Rows.Add(dr); dataGrid1.DataSource = dt; } privatevoid ShowMessage(SmsPdu pdu) { if (pdu isSmsSubmitPdu) { // Stored (sent/unsent) message SmsSubmitPdu data = (SmsSubmitPdu)pdu; Output("SENT/UNSENT MESSAGE"); Output("Recipient: " + data.DestinationAddress); Output("Message text: " + data.UserDataText); Output("------------------------------"); return; } if (pdu isSmsDeliverPdu) { // Received message SmsDeliverPdu data = (SmsDeliverPdu)pdu; Output("RECEIVED MESSAGE"); Output("Sender: " + data.OriginatingAddress); Output("Sent: " + data.SCTimestamp.ToString()); Output("Message text: " + data.UserDataText); Output("---------------------------------"); BindGrid(pdu); return; } T r a n g | 153 Đồ án tốt nghiệp if (pdu isSmsStatusReportPdu) { // Status report SmsStatusReportPdu data = (SmsStatusReportPdu)pdu; Output("STATUS REPORT"); Output("Recipient: " + data.RecipientAddress); Output("Status: " + data.Status.ToString()); Output("Timestamp: " + data.DischargeTime.ToString()); Output("Message ref: " + data.MessageReference.ToString()); Output("-----------------------------------"); return; } Output("Unknown message type: " + pdu.GetType().ToString()); } privatestring StatusToString(PhoneMessageStatus status) { // Map a message status to a string string ret; switch(status) { casePhoneMessageStatus.All: ret = "All"; break; casePhoneMessageStatus.ReceivedRead: ret = "Read"; break; casePhoneMessageStatus.ReceivedUnread: ret = "Unread"; break; casePhoneMessageStatus.StoredSent: ret = "Sent"; break; casePhoneMessageStatus.StoredUnsent: ret = "Unsent"; break; default: ret = "Unknown (" + status.ToString() + ")"; break; } return ret; } privatestring GetMessageStorage() { string storage = string.Empty; if (rbMessageSIM.Checked) storage = PhoneStorageType.Sim; if (rbMessagePhone.Checked) storage = PhoneStorageType.Phone; if (storage.Length == 0) thrownewApplicationException("Unknown message storage."); else return storage; } privatevoid Output(string text) { if (this.txtOutput.InvokeRequired) T r a n g | 154 Đồ án tốt nghiệp { SetTextCallback stc = newSetTextCallback(Output); this.Invoke(stc, newobject[] { text }); } else { txtOutput.AppendText(text); txtOutput.AppendText("\r\n"); } } privatevoid Receive_Load(object sender, System.EventArgs e) { dt.Columns.Add("Sender",typeof(string)); dt.Columns.Add("Time",typeof(string)); dt.Columns.Add("Message",typeof(string)); } privatevoid Output(string text, paramsobject[] args) { string msg = string.Format(text, args); Output(msg); } } } 6. Delete using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; T r a n g | 155 Đồ án tốt nghiệp using GsmComm.PduConverter; using GsmComm.GsmCommunication; namespace SMS { /// /// Summary description for Delete. /// publicclassDelete : System.Windows.Forms.Form { private System.Windows.Forms.DataGrid dataGrid1; /// /// Required designer variable. /// private System.ComponentModel.Container components = null; private System.Windows.Forms.Button btn_delete; private System.Windows.Forms.Button btn_delete_all; private System.Windows.Forms.TextBox txt_message_index; privateDataTable dt=newDataTable(); privatedelegatevoidSetTextCallback(string text); public Delete() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protectedoverridevoid Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// privatevoid InitializeComponent() { this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.btn_delete = new System.Windows.Forms.Button(); this.btn_delete_all = new System.Windows.Forms.Button(); this.txt_message_index = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // dataGrid1 // T r a n g | 156 Đồ án tốt nghiệp this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(8, 40); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(484, 284); this.dataGrid1.TabIndex = 60; this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown); // // btn_delete // this.btn_delete.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btn_delete.Location = new System.Drawing.Point(56, 8); this.btn_delete.Name = "btn_delete"; this.btn_delete.Size = new System.Drawing.Size(75, 23); this.btn_delete.TabIndex = 62; this.btn_delete.Text = "Delete"; this.btn_delete.Click += new System.EventHandler(this.btn_delete_Click); // // btn_delete_all // this.btn_delete_all.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btn_delete_all.Location = new System.Drawing.Point(136, 8); this.btn_delete_all.Name = "btn_delete_all"; this.btn_delete_all.Size = new System.Drawing.Size(75, 23); this.btn_delete_all.TabIndex = 63; this.btn_delete_all.Text = "Delete All"; this.btn_delete_all.Click += new System.EventHandler(this.btn_delete_all_Click); // // txt_message_index // this.txt_message_index.Location = new System.Drawing.Point(8, 8); this.txt_message_index.Name = "txt_message_index"; this.txt_message_index.Size = new System.Drawing.Size(40, 20); this.txt_message_index.TabIndex = 64; // // Delete // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 478); this.Controls.Add(this.txt_message_index); this.Controls.Add(this.btn_delete_all); this.Controls.Add(this.btn_delete); this.Controls.Add(this.dataGrid1); this.Name = "Delete"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Delete"; this.Load += new System.EventHandler(this.Delete_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion privatevoid Delete_Load(object sender, System.EventArgs e) { dataGrid1.PreferredColumnWidth=100; dt.Columns.Add("Index",typeof(int)); dt.Columns.Add("Sender",typeof(string)); dt.Columns.Add("Time",typeof(string)); dt.Columns.Add("Message",typeof(string)); T r a n g | 157 Đồ án tốt nghiệp ReadMessage(); } privatevoid ReadMessage() { Cursor.Current = Cursors.WaitCursor; string storage = GetMessageStorage(); try { // Read all SMS messages from the storage DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage); foreach(DecodedShortMessage message in messages) { ShowMessage(message.Data,message.Index); } } catch(Exception ex) { MessageBox.Show(ex.Message); } Cursor.Current = Cursors.Default; } privatevoid BindGrid(SmsPdu pdu,int index) { DataRow dr=dt.NewRow(); SmsDeliverPdu data = (SmsDeliverPdu)pdu; dr[0]=index.ToString(); dr[1]=data.OriginatingAddress.ToString(); dr[2]=data.SCTimestamp.ToString(); dr[3]=data.UserDataText; dt.Rows.Add(dr); dataGrid1.DataSource=dt; } privatevoid ShowMessage(SmsPdu pdu,int index) { if (pdu isSmsSubmitPdu) { // Stored (sent/unsent) message SmsSubmitPdu data = (SmsSubmitPdu)pdu; return; } if (pdu isSmsDeliverPdu) { // Received message SmsDeliverPdu data = (SmsDeliverPdu)pdu; BindGrid(pdu,index); return; } if (pdu isSmsStatusReportPdu) { // Status report SmsStatusReportPdu data = (SmsStatusReportPdu)pdu; T r a n g | 158 Đồ án tốt nghiệp return; } } privatestring StatusToString(PhoneMessageStatus status) { // Map a message status to a string string ret; switch(status) { casePhoneMessageStatus.All: ret = "All"; break; casePhoneMessageStatus.ReceivedRead: ret = "Read"; break; casePhoneMessageStatus.ReceivedUnread: ret = "Unread"; break; casePhoneMessageStatus.StoredSent: ret = "Sent"; break; casePhoneMessageStatus.StoredUnsent: ret = "Unsent"; break; default: ret = "Unknown (" + status.ToString() + ")"; break; } return ret; } privatestring GetMessageStorage() { string storage = PhoneStorageType.Sim; return storage; } privatevoid btn_delete_all_Click(object sender, System.EventArgs e) { if (!Confirmed()) return; Cursor.Current = Cursors.WaitCursor; string storage = GetMessageStorage(); try { // Delete all messages from phone memory CommSetting.comm.DeleteMessages(DeleteScope.All, storage); dt.Clear(); dataGrid1.DataSource=dt; } catch(Exception ex) { MessageBox.Show(ex.Message); } Cursor.Current = Cursors.Default; } privatebool Confirmed() { T r a n g | 159 Đồ án tốt nghiệp return (MessageBox.Show(this, "Really?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes); } privatevoid dataGrid1_MouseDown (object sender, System.Windows.Forms.MouseEventArgs e) { System.Windows.Forms.DataGrid.HitTestInfo myHitTest; // Use the DataGrid control's HitTest method with the x and y properties. myHitTest = dataGrid1.HitTest(e.X,e.Y); txt_message_index.Text=dataGrid1[myHitTest.Row ,0].ToString(); } privatevoid btn_delete_Click(object sender, System.EventArgs e) { if( txt_message_index.Text.Equals("")==true) { MessageBox.Show("Please Click on Grid","Message",MessageBoxButtons.OK,MessageBoxIcon.Information); return; } int index; try { index = int.Parse(txt_message_index.Text); } catch(Exception ex) { MessageBox.Show(ex.Message); return; } if (!Confirmed()) return; Cursor.Current = Cursors.WaitCursor; string storage = GetMessageStorage(); try { // Delete the message with the specified index from storage CommSetting.comm.DeleteMessage(index, storage); MessageBox.Show("Message With Index " + index + " Deleted","Message",MessageBoxButtons.OK,MessageBoxIcon.Information); } catch(Exception ex) { MessageBox.Show(ex.Message); } Cursor.Current = Cursors.Default; dt.Clear(); dataGrid1.DataSource=null; ReadMessage(); } } } T r a n g | 160 Đồ án tốt nghiệp TÀI LIỆU THAM KHẢO [1] Nguyễn Trung Chính, “Tập lệnh AT của module SIM508 dùng cho SMS”, 2009 [2] Nguyễn Trọng Kiên - Phạm Văn Nam, “Điều khiển thiết bị từ xa qua tin nhắn SMS bằng máy tính”,Đại học Sư Phạm Kỹ Thuật TPHCM, 2009 [3] Nguyễn Quang Ninh, “Nghiên cứu công nghệ SMS – Xây dựng hệ thống tra cứu điểm qua mạng điện thoại di động”,Đại học Sư Phạm TPHCM, 2005 [4]Nguyễn Đình Phú, “Giáo trình Vi xử lý 1”,Đại học Sư Phạm Kỹ Thuật TPHCM, 2006 [5] Trần Phạm Thanh Tùng, C# Fast Food, Năm 2008 [6] “AT Command Interface Guide”,WAVECOM, 2006 [7]GSM 07.05, ver 5.5.0 - Use of Data Terminal Equipment - Data Circuit Terminating Equipment (DTE - DCE) interface for Short Message Service (SMS) and Cell Broadcast Service (CBS) [8] GSM07.07, ver 5.0.0 - AT command set for GSM Mobile Equipment (ME) [9] SMS source samples (for GSM phones), [10] How To Send and Receive SMS using GSM Modem, www.codeproject.com.vn [11] GSM Modem Userguide, www.inet.vn [12] Bảng mãASCCII, Website: www.pcworld.com.vn, www.codeproject.com.vn

Các file đính kèm theo tài liệu này:

  • pdfTra cứu thông tin và Điều khiển thiết bị điện qua tin nhắn SMS.pdf