Web page get serial data

Source: Internet
Author: User

Recently do a B/s project, need to read the value of the electronic scale, has not done before, and no experience, so found on the internet a lot of roughly two kinds of

    1. Using ActiveX controls, JS calls MSCOMM32.dll's serial control to control the serial port
    2. Control the serial port using the C # language control, and then use Js+ajax to interact with C # to obtain serial port data

For details see Using JS to get serial data http://blog.csdn.net/xuing/article/details/6688306 but the younger brother uses both methods to get the data

The serial port configuration is as follows:

1                  serialport1.portname = "COM1";          Port Name 2             serialport1.baudrate =;            Baud Rate 3             serialport1.parity = Parity.none;       Parity 4             serialport1.stopbits = Stopbits.one;    Efficacy 5             serialport1.databits = 8;               Data bit length per byte

Finally, a different idea: use C # to write an ActiveX control (auspicious teacher reminder) The last embedded Web page reads the data as follows:

  1. The first step: Create a new project, such as selecting a class library project under Windows.
  2. Add a class to your project: IObjectSafety.cs
  3. The IObjectSafety.cs code is as follows:
    Using system;using system.collections.generic;using system.text;using system.runtime.interopservices;namespace myactive{    //guid Unique, immutable, otherwise will not be able to pass the security authentication of IE Browser ActiveX control      [ComImport, Guid (" cb5bdc81-93c1-11cf-8f20-00805f2cd064 ")]    [InterfaceType (Cominterfacetype.interfaceisiunknown)]    public Interface IObjectSafety    {        [preservesig]        void getinterfaccesafyoptions (int riid,out int pdwsupportedoptions,out int pdwenabledoptions);}    }

  4. Add a user control MyActiveXControl.cs
  5. Modify the MyActiveXControl.cs code to inherit the IObjectSafety and define the appropriate GUID, which is the ActiveX ClassID
    Using System; Using System.Collections.Generic; Using System.ComponentModel; Using System.Drawing; Using System.Data; Using System.Text; Using System.Windows.Forms; Using System.runtime.interopservices;namespace myactivex {     [Guid ("218849af-1b2c-457b-acd5-b42ac8d17eb7"), ComVisible (true)] public     partial class myactivexcontrol:usercontrol,iobjectsafety     {         public Myactivexcontrol ()         {             InitializeComponent ();         }        #region IObjectSafety member for ActiveX control Security Trust public        void getinterfaccesafyoptions (int riid, out int pdwsupportedoptions , out int pdwenabledoptions)         {             pdwsupportedoptions = 1;             Pdwenabledoptions = 2;         }        public void setinterfacesafetyoptions (int riid, int dwoptionssetmask, int dwenabledoptions)         {             throw new NotImplementedException ();         }         #endregion     }}

    Now that the active control is finished, we'll add a text box, button, SerialPort, Timer control to test

  6. The event code to add the response is as follows
    Using system;using system.collections.generic;using system.componentmodel;using system.drawing;using System.Data; Using system.io.ports;using system.text;using system.threading;using system.windows.forms;using System.runtime.interopservices;using myactive;namespace myactivex{//cannot be changed [Guid (" 218849af-1b2c-457b-acd5-b42ac8d17eb7 "), ComVisible (true)] public partial class Myactivexcontrol:usercontrol, Iobject        Safety {public Myactivexcontrol () {InitializeComponent (); public delegate void Handleinterfaceupdatadelegate (string text);//define a delegate private Hand Leinterfaceupdatadelegate interfaceupdatahandle;//declares that bool Isclose = false;//is closed #region IObjectSafety members are used to ActiveX control Security Trust public void getinterfaccesafyoptions (int riid, out int pdwsupportedoptions, out int pdwenabledoptions            ) {pdwsupportedoptions = 1;        Pdwenabledoptions = 2; } public void SetInterfacesafetyoptions (int riid, int dwoptionssetmask, int dwenabledoptions) {throw new Notimplementedexc        Eption ();            } #endregion private void Button1_Click (object sender, EventArgs e) {try                 {interfaceupdatahandle = new handleinterfaceupdatadelegate (updatetextbox);//instantiation of Delegate Object                serialport1.datareceived + = new Serialdatareceivedeventhandler (serialport1_datareceived);                if (!serialport1.isopen) {serialport1.open (); } button2.                Enabled = true; Button1.            Enabled=false; } catch (Exception ex) {MessageBox.Show (ex.                Message);            Return } timer1.                    Enabled = true; }///<summary>///Control load events///</summary>//<param name= "Sender" ></para m>//&LT;param name= "E" ></param> private void Myactivexcontrol_load (object sender, EventArgs e) {        Setorgcomb ();            }///<summary>//Initialize serial port///</summary> private void Setorgcomb () {          Serialport1.portname = "COM1";            Port name serialport1.baudrate = 1200;       Baud rate serialport1.parity = Parity.none;    Parity checksum serialport1.stopbits = Stopbits.one;               Efficacy serialport1.databits = 8; Data bit length per byte}///<summary>//Update data///</summary>//<param name= "Te XT "></param> private void Updatetextbox (string text) {//richtextbox1.text = text +" \n\            T "+ richtextbox1.text;        richTextBox1.Text = Text; }///<summary>//////</summary>//<param name= "Sender" ></par am>//<paRam Name= "E" ></param> private void Serialport1_datareceived (object sender, Serialdatareceivedeventargs e) {//Gets the number of bytes of data in the receive buffer if (Serialport1.bytestoread > 5) {string str Temp = Serialport1.readexisting ();//reads the serial port double weight = -1;//gets to the weight of the foreach (String str in                    Strtemp.split (' = '))//Get the stable value {double flog = 0; If the data is normal if (double. TryParse (str, out flog) &&str. IndexOf ('. ') >0&&str[str.                    length-1]!= '. ') {//Data conversion serial port gets to the data is flashbacks and therefore reverses char[] Chararray = str.                        ToCharArray ();                        Array.reverse (Chararray); String left = new String (Chararray). Split ('. ')                        [0]; String right = new string (Chararray). Split ('. ')                        [1]; if (right.       length==2) {                     weight = Int. Parse (left) + int.                        Parse (right)/100.0; }}} if (weight>=0) {//In the owning control's underlying window handle                                        , executes the specified delegate with the specified argument list. This. Invoke (Interfaceupdatahandle, weight. ToString ());//Fetch Data Update}}} private void Button2_Click (object sender, EventArgs E) {try {button1.                Enabled = true; Button2.                Enabled = false;                Serialport1.close (); Timer1.                                           Enabled = false; } catch (Exception ex) {MessageBox.Show (ex.            Message);                }} private void Timer1_Tick (object sender, EventArgs e) {if (isclose) {            Return } try {string send = "" + (ChaR) + ' P ';            Send = Serialport1.readexisting (); } catch (Exception ex) {MessageBox.Show (ex.                Message);            button2_click (null, NULL); }        }    }}


  7. Now that the active control reading the serial data is finished, let's create an installation package, create a new Installation project
  8. Add the ActiveX DLL:MyActiveX.dll we made earlier in the file system of the installation project
    (Special note: After the file is added, right-click on the file Selection property and set its property register value to: vsdracom)

9. Build the installer, locate the Setup1.msi under Project Myactivex\setup1\debug, and double-click Install it.
Then create a new HTML file (test.html) in this directory to test our Acticex control. The HTML code is as follows:

Open test.html under IE browser and click Start to listen

Web page get serial data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.