【问题标题】:How to use c# methods with serial port in asp .net core?如何在asp .net核心中使用带有串口的c#方法?
【发布时间】:2018-10-30 18:19:05
【问题描述】:

我的任务是使用 ASP .NET core 2.0 创建 Web 应用程序,您可以在其中与调制解调器通信并使用 AT 命令发送 SMS。我有一段代码可以使用串行端口发送消息,但 ASP 没有这个库,那么我如何在 ASP .NET 中使用这个代码?
方法:

private SerialPort _serialPort;

    public void SendSms()
    {
        Console.WriteLine("Write phone number");
        string phoneNr = Console.ReadLine();
        Console.WriteLine("Write message");
        string message = Console.ReadLine();

        _serialPort = new SerialPort("COM2", 9600);

        Thread.Sleep(1000);

        _serialPort.Open();

        Thread.Sleep(1000);

        _serialPort.Write("AT+CMGF=1\r");

        Thread.Sleep(1000);

        _serialPort.Write("AT+CMGS=\"" + phoneNr + "\"\r\n");

        Thread.Sleep(1000);

        _serialPort.Write(message + "\x1A");

        Thread.Sleep(1000);

        _serialPort.Close();
    }


同样在我的应用程序中,我有聊天窗口,所以我想使用输入框和按钮来编写和发送短信。

 <form method="post">
            <input asp-for="MessageBody" id="textInput" type="text" placeholder="Enter message..." class="form-control " />
            <button asp-action="SendMessage" id="sendButton" class="btn btn-primary btn-block" type="submit">Send</button>
 </form>


目前 SendMessage 仅将消息保存到数据库中。
抱歉,如果我的问题没有以最好的方式提出,第一次写在这里。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core serial-port


    【解决方案1】:

    这是您要查找的文档Serial port communication in .net core

    链接中的示例以确保完整性:

    using System;
    using System.IO.Ports;
    using System.Threading;
    
    public class PortChat
    {
    static bool _continue;
    static SerialPort _serialPort;
    
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);
    
        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();
    
        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
    
        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;
    
        _serialPort.Open();
        _continue = true;
        readThread.Start();
    
        Console.Write("Name: ");
        name = Console.ReadLine();
    
        Console.WriteLine("Type QUIT to exit");
    
        while (_continue)
        {
            message = Console.ReadLine();
    
            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }
    
        readThread.Join();
        _serialPort.Close();
    }
    
    public static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }
    
    // Display Port values and prompt user to enter a port.
    public static string SetPortName(string defaultPortName)
    {
        string portName;
    
        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }
    
        Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
        portName = Console.ReadLine();
    
        if (portName == "" || !(portName.ToLower()).StartsWith("com"))
        {
            portName = defaultPortName;
        }
        return portName;
    }
    // Display BaudRate values and prompt user to enter a value.
    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;
    
        Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();
    
        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }
    
        return int.Parse(baudRate);
    }
    
    // Display PortParity values and prompt user to enter a value.
    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;
    
        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }
    
        Console.Write("Enter Parity value (Default: {0}):",             defaultPortParity.ToString(), true);
        parity = Console.ReadLine();
    
        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }
    
        return (Parity)Enum.Parse(typeof(Parity), parity, true);
    }
    // Display DataBits values and prompt user to enter a value.
    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;
    
        Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();
    
        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }
    
        return int.Parse(dataBits.ToUpperInvariant());
    }
    
    // Display StopBits values and prompt user to enter a value.
    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;
    
        Console.WriteLine("Available StopBits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }
    
        Console.Write("Enter StopBits value (None is not supported and \n" +
         "raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();
    
        if (stopBits == "" )
        {
            stopBits = defaultPortStopBits.ToString();
        }
    
        return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
    }
    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;
    
        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }
    
        Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();
    
        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }
    
        return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
    }
    

    }

    【讨论】:

      【解决方案2】:

      你可以尝试在这一行添加“\n”吗?

      _serialPort.Write("AT+CMGF=1\r");
      

      应该是这样的

      _serialPort.Write("AT+CMGF=1\r\n");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-22
        • 2019-06-23
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 2019-04-02
        • 2018-10-17
        • 2018-04-02
        相关资源
        最近更新 更多