/// <summary> /// 把Configation对象转为结构体CAN_InitConfig /// </summary> private Like.CAN_InitConfig Conver2InitConfig(Configation cfg) { Like.CAN_InitConfig res = new Like.CAN_InitConfig(); res.dwBtr = new byte[4]; res.dwReserved = 0; if (cfg.IsListenOnly) res.bMode = 1; else res.bMode = 0; if (cfg.BaudrateTypeIsSJA1000) res.nBtrType = 1; else res.nBtrType = 0; byte[] btr = new byte[4]; btr = BitConverter.GetBytes((uint)cfg.Baudrate); res.dwBtr = btr; res.nFilter = (byte)cfg.FilterMode; res.dwAccCode = cfg.AccCode; res.dwAccMask = cfg.AccMask; return res; }
/// <summary> /// 打开CAN通道 /// </summary> private void button1_Click(object sender, EventArgs e) { uint acc = 0x00000000, mask = 0xFFFFFFFF; if (maskedTextBox1.Enabled) acc = Convert.ToUInt32(maskedTextBox1.Text, 16); if (maskedTextBox2.Enabled) mask = Convert.ToUInt32(maskedTextBox2.Text, 16); Configation cfg = new Configation((CAN_Baudrate)comboBox1.SelectedValue, true, (bool)comboBox2.SelectedValue, (CAN_FilterMode)comboBox3.SelectedValue, acc, mask); if (CANChannel != null) { if (CANChannel.Start(cfg)) { //在打开端口事件处理函数中改变控制状态 } else { MessageBox.Show("打开CAN口失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("打开通道前\n请先通过CANChannel属性设置通道对象", "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// 开启CAN通道 /// </summary> public bool Start(Configation conf) { if (this.IsRuning) { System.Windows.Forms.MessageBox.Show(string.Format("CAN{0}已经打开,若要重新打开请先关闭!", this.Channel), "提示:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); return false; } else { Like.CAN_InitConfig init = Conver2InitConfig(conf); uint resualt = Like.CAN_ChannelStart(this._handle, this.Channel, ref init); if (resualt != 0) { this._isRuning = true; this._startTime = DateTime.Now; Debug.WriteLine(string.Format("打开\t CAN{0}\t成功", this.Channel), this.StartTime.ToString()); //触发CAN通道打开事件 if (EventStart != null) EventStart(this, new EventArgs()); return true; } else { this._isRuning = false; Debug.WriteLine(string.Format("打开\t CAN{0}\t失败", this.Channel)); return false; } } }