Little Fox
Little Fox

Reputation: 1252

Sending utf-8 chars in SMS via GSM modem

I'm using a Nokia 5228 to send a SMS via the COM port, and I get wrong symbols when I send UTF-8 chars. English chars are working good.
How can I solve that problem?

        public static string SMSMessage = "Привет";
        public static string CellNumber = "number...";

        private void Form1_Load(object sender, EventArgs e)
        {
            sp = new SerialPort();
            sp.PortName = "COM12";
            sp.Encoding = UTF8Encoding.UTF8;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                if (!sp.IsOpen)
                {
                    sp.Open();
                    this.sp.WriteLine(@"AT" + (char)(13));
                    Thread.Sleep(200);
                    this.sp.WriteLine("AT+CMGF=1" + (char)(13));
                    Thread.Sleep(200);
                    this.sp.WriteLine(@"AT+CMGS=""" + CellNumber + @"""" + (char)(13));
                    Thread.Sleep(200);
                    this.sp.WriteLine(SMSMessage + (char)(26));
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Exception : {0}", ex.Message), "Port Error");
            }
        }

Upvotes: 1

Views: 1079

Answers (1)

Little Fox
Little Fox

Reputation: 1252

The problem was, that I had to use UCS2.

this.sp.WriteLine(StringToUCS2("Привет, привіт !@#%") + char.ConvertFromUtf32(26));

public static string StringToUCS2(string str)
        {
            UnicodeEncoding ue = new UnicodeEncoding();
            byte[] ucs2 = ue.GetBytes(str);

            int i = 0;
            while (i < ucs2.Length)
            {
                byte b = ucs2[i + 1];
                ucs2[i + 1] = ucs2[i];
                ucs2[i] = b;
                i += 2;
            }
            return BitConverter.ToString(ucs2).Replace("-", "");
        }

Upvotes: 1

Related Questions