private void SP1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender; if (connecting) { connecting = false; connected = true; } if (!connected) { try { string str = sp.ReadExisting(); if (str.Contains("a")) { sp.DiscardInBuffer(); connected = true; } } catch { lb1SetText("nelze se připojit k procesoru"); } sp.DiscardInBuffer(); } else { try { //sp.DiscardInBuffer(); if (sp.ReadChar() == 'a') { System.Threading.Thread.Sleep(2); if (sp.BytesToRead > 176) { ulong[] inpData = new ulong[11]; for (int i = 0; i != 11; i++) { if (!ulong.TryParse(sp.ReadLine().Trim(), out inpData[i])) { sp.ReadExisting(); break; } } sp.DiscardInBuffer(); UpdateImg(inpData); } } } catch (Exception ex) { lb1SetText("catch exeption" + ex.Message); timer1.Stop(); return; } } }
void spIOPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { m_buffer += spIOPort.ReadChar(); if (m_buffer.Contains("\x0D\x0A")) { DataAvailableEventArgs m_e = new DataAvailableEventArgs(); m_e.data = m_buffer; //We have a newline! Time to go! OnDataAvailable(m_e); } }
public bool ReadChar(out char cc, out uint numRead) { if (serialPort.BytesToRead == 0) { cc = '\n'; numRead = 0; return(true); } cc = (char)serialPort.ReadChar(); if (cc == (char)0xffff) { numRead = 0; return(false); } numRead = 1; return(true); }
public void WorkerThreadMain() { while (true) { //Interlocked.Increment AwakeEvent.WaitOne(); AwakeEvent.Reset(); do { MessageRecord mr = PopMessage(); if (mr == null) { break; // !! } // System.Console.WriteLine("Message:{0}",mr.Message.ToString()); switch (mr.Message) { case MessageRecord.MsgType.Clear: DaraRecordList.Clear(); break; case MessageRecord.MsgType.SetPortName: Portname = (string)mr.Data; break; case MessageRecord.MsgType.SetDevice: CurrentBoard = (Board)mr.Data; break; case MessageRecord.MsgType.SetBaud: ReciveBaudRate = (int)mr.Data; break; case MessageRecord.MsgType.SetRecord: DaraRecordList.Add((DataRecord)mr.Data); break; case MessageRecord.MsgType.SetAfterWait: AfterWait = (bool)mr.Data; break; case MessageRecord.MsgType.Start: break; case MessageRecord.MsgType.Abort: SerialIOThread.Abort(); break; } if (mr.Message == MessageRecord.MsgType.Start) { break; } } while (true); AfterPopMessageEvent.Set(); Interlocked.Increment(ref CriticalCounter); // Enter critical section if (CurrentBoard == null) { continue; } byte[] rbuf = new byte[256]; MainState = MainStateEnum.Reset; ErrorState = ErrorStatusEnum.None; RecordIndex = 0; RecordCount = DaraRecordList.Count; System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort(Portname); port.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(port_ErrorReceived); { try { port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); } catch (Exception exp) { System.Console.WriteLine("{0}", exp.Message); ErrorState = ErrorStatusEnum.PortNotFound; goto ErrorExit; } if (StateCallback != null) { StateCallback(); } port.BaudRate = CurrentBoard.UpLoadSpeed; port.WriteTimeout = 1000; port.ReadTimeout = 1000; switch (CurrentBoard.DTRControl) { case Board.DTRControlTypeEnum.Enable1000mSecAndDisable: port.DtrEnable = true; port.DiscardInBuffer(); port.DiscardOutBuffer(); Thread.Sleep(1000); port.DtrEnable = false; port.DiscardInBuffer(); port.DiscardOutBuffer(); Thread.Sleep(100); port.DiscardInBuffer(); port.DiscardOutBuffer(); break; case Board.DTRControlTypeEnum.EnableAndThrough: port.DtrEnable = true; port.DiscardInBuffer(); port.DiscardOutBuffer(); Thread.Sleep(500); port.DiscardInBuffer(); port.DiscardOutBuffer(); break; } for (int i = 0; i < 3; i++) {// Get sync byte[] com = { Cmnd_STK_GET_SYNC, Sync_CRC_EOP }; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.RequestTimeout; goto ErrorExit; } } if (CurrentBoard.SoftwareMajorVersion < 4) { {// Software major version (No implementation on optiboot V4-) byte[] com = { Cmnd_STK_GET_PARAMETER, Param_STK_SW_MAJOR, Sync_CRC_EOP }; byte[] rq = { Resp_STK_INSYNC, CurrentBoard.SoftwareMajorVersion, Resp_STK_OK }; if (!RequestForAnswerThanLess(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.InvalidVersion; goto ErrorExit; } } {// Enter programming mode (No implementation on optiboot V4-) byte[] com = { Cmnd_STK_ENTER_PROGMODE, Sync_CRC_EOP }; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.CannotEnterProgrammingMode; goto ErrorExit; } } } foreach (DataRecord record in DaraRecordList) { if (DaraRecordList.Count > 0) { MainState = MainStateEnum.Send; } if (StateCallback != null) { StateCallback(); } if (!CheckData(record)) { ErrorState = ErrorStatusEnum.AddressFault; goto ErrorExit; } int sendcount; RecordProcessing = 0; for (sendcount = 0; sendcount < record.Data.Length;) { {// Load address byte[] com = new byte[4]; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; int address = record.Address + sendcount; com[0] = Cmnd_STK_LOAD_ADDRESS; com[1] = (byte)((address >> 1) & 0xff); com[2] = (byte)((address >> 9) & 0xff); com[3] = Sync_CRC_EOP; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.SetAddress; goto ErrorExit; } } byte cur_send = 128; if (sendcount + cur_send > record.Data.Length) { cur_send = (byte)(record.Data.Length - sendcount); } {// Write page byte[] com = new byte[cur_send + 5]; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; com[0] = Cmnd_STK_PROG_PAGE; com[1] = 0x00; com[2] = cur_send; com[3] = (byte)'F';// 'F'=flash 'E'=eeprom for (int i = 0; i < cur_send; i++) { com[4 + i] = record.Data[sendcount + i]; } com[com.Length - 1] = Sync_CRC_EOP; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.WriteData; goto ErrorExit; } } sendcount += cur_send; RecordProcessing = (float)sendcount / (float)record.Data.Length; if (StateCallback != null) { StateCallback(); } } if (record.Verify) { if (DaraRecordList.Count > 0) { MainState = MainStateEnum.Verify; } if (StateCallback != null) { StateCallback(); } RecordProcessing = 0; for (sendcount = 0; sendcount < record.Data.Length;) { {// Load address byte[] com = new byte[4]; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; int address = record.Address + sendcount; com[0] = Cmnd_STK_LOAD_ADDRESS; com[1] = (byte)((address >> 1) & 0xff); com[2] = (byte)((address >> 9) & 0xff); com[3] = Sync_CRC_EOP; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.SetAddress; goto ErrorExit; } } byte cur_recv = 128; if (sendcount + cur_recv > record.Data.Length) { cur_recv = (byte)(record.Data.Length - sendcount); } {// Read page byte[] com = new byte[5]; com[0] = Cmnd_STK_READ_PAGE; com[1] = 0x00; com[2] = cur_recv; com[3] = (byte)'F'; com[4] = Sync_CRC_EOP; if (!RequestForAnswer(port, com, rbuf, cur_recv + 2)) { ErrorState = ErrorStatusEnum.ReadData; goto ErrorExit; } if (rbuf[0] != Resp_STK_INSYNC || rbuf[cur_recv + 1] != Resp_STK_OK) { ErrorState = ErrorStatusEnum.VerifyUnmuch; goto ErrorExit; } for (int i = 0; i < cur_recv; i++) { if (record.Data[sendcount + i] != rbuf[i + 1]) { ErrorState = ErrorStatusEnum.VerifyUnmuch; goto ErrorExit; } } } sendcount += cur_recv; RecordProcessing = (float)sendcount / (float)record.Data.Length; if (StateCallback != null) { StateCallback(); } } } RecordIndex++; } {// Leave programming mode byte[] com = { Cmnd_STK_LEAVE_PROGMODE, Sync_CRC_EOP }; byte[] rq = { Resp_STK_INSYNC, Resp_STK_OK }; if (!RequestForAnswer(port, com, rq, rbuf)) { ErrorState = ErrorStatusEnum.Unknown; goto ErrorExit; } } if (AfterWait) { Interlocked.Decrement(ref CriticalCounter);// Exit critical section port.BaudRate = ReciveBaudRate; MainState = MainStateEnum.ConsoleMonitor; if (StateCallback != null) { StateCallback(); } System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (true) { if (CountMessage() > 0) { port.Close(); port.Dispose(); MainState = MainStateEnum.Idle; ErrorState = ErrorStatusEnum.Success; // ここでstateをメインに返してInvokeするとAwakeWorkerに突入中の場合デッドロックするのでそのまま次に回す break; } if (port.BytesToRead == 0) { Thread.Sleep(20); continue; } do { char c = (char)port.ReadChar(); sb.Append(c); } while (port.BytesToRead > 0); if (sb.Length > 0) { if (ReciveCallback != null) { ReciveCallback(sb.ToString()); } sb.Remove(0, sb.Length); } } } else { port.Close(); port.Dispose(); Interlocked.Decrement(ref CriticalCounter); MainState = MainStateEnum.Idle; ErrorState = ErrorStatusEnum.Success; if (StateCallback != null) { StateCallback(); } continue; } continue; ErrorExit: while (PopMessage() != null) { ; } port.Close(); port.Dispose(); if (CriticalCounter == 1) { Interlocked.Decrement(ref CriticalCounter); } MainState = MainStateEnum.Abort; if (StateCallback != null) { StateCallback(); } continue; } } }
public int ReadChar() { return(sp.ReadChar()); }
private bool WriteData(System.IO.Ports.SerialPort sp) { System.Diagnostics.Debug.WriteLine("Update: Writing Data"); this.Step = Steps.WriteData; wait.Set(); var oldWTimeOut = sp.WriteTimeout; var oldRTimeOut = sp.ReadTimeout; sp.WriteTimeout = 1500; sp.ReadTimeout = 1000; bool result = true; //进入编程 sp.Write("p"); int errcnt = 0; for (int i = 0; i < this.UpdateDate.Data.Length; i++) { //System.Threading.Thread.Sleep(100); String item = this.UpdateDate.Data[i]; wait.Set(); System.Diagnostics.Debug.WriteLine("Send:" + item); try { sp.Write(item); System.Threading.Interlocked.Increment(ref _WriteCount); if (WriteCount == this.UpdateDate.Data.Length) { String msg = sp.ReadTo("WT");//写入完成 返回FHWT //string t = sp.ReadTo("FH"); if (!msg.StartsWith("FH")) { this.ERROR = msg.Replace("WT", String.Empty); result = false; } else { //sp.Write("g"); //Debug.WriteLine("g"); result = true; } } else { var feedback = sp.ReadChar(); if (feedback == '?') { System.Diagnostics.Debug.WriteLine("数据写入失败"); if (errcnt >= 3) { errcnt = 0; continue; } else { i--; } WriteCount--; errcnt++; continue; } else if (feedback == 'S') { continue; } else if (feedback != '*') { this.ERROR = "Unkown Error"; result = false; break; } } } catch (TimeoutException e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); i--; continue; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); result = false; break; } } return(result); }
public override int ReadChar() { return(_Port.ReadChar()); }
void mandarSeñal(Skeleton esqueleto) { if (esqueleto.Joints[JointType.HandRight].Position.X != j.Position.X) { Joint arm = esqueleto.Joints[JointType.HandRight]; int angle = (int)(esqueleto.Joints[JointType.HandRight].Position.X * 100.0f); // if (angle >= 0 && valY >= 0 || angle <= 0 && valY <= 0) { // ArduinoPort.WriteLine("X" + angle.ToString()); // Console.WriteLine(" Ang:" + angle); servoVal = servoVal + angle; //while (((char)ArduinoPort.ReadChar()) != 'E') ; valX = angle; // } } if (esqueleto.Joints[JointType.HandRight].Position.Y != j.Position.Y) { Joint arm = esqueleto.Joints[JointType.HandRight]; int angle = (int)(esqueleto.Joints[JointType.HandRight].Position.Y * 100.0f); //if (angle >= 0 && valY >= 0 || angle <= 0 && valY <= 0){ //ArduinoPort.WriteLine("Y"+angle.ToString()); servoVal = servoVal + "," + angle; //while (((char)ArduinoPort.ReadChar()) != 'E') ; valY = angle; // } } if (esqueleto.Joints[JointType.HandRight].Position.Z != j.Position.Z) { Joint arm = esqueleto.Joints[JointType.HandRight]; // double radians = Math.Atan2(esqueleto.Joints[JointType.HandRight].Position.Y, esqueleto.Joints[JointType.HandRight].Position.X); // double angle = radians * (360/ Math.PI); int angle = (int)(esqueleto.Joints[JointType.HandRight].Position.Z * 100.0f); //ArduinoPort.WriteLine("Z" + angle.ToString()); servoVal = servoVal + "," + angle; Console.WriteLine(" Ang:" + angle); // int aux = ((char)ArduinoPort.ReadChar()); //while (((char)ArduinoPort.ReadChar()) != 'E') ; } Console.WriteLine(" X:" + esqueleto.Joints[JointType.HandRight].Position.X + " Y:" + esqueleto.Joints[JointType.HandRight].Position.Y + " Z:" + esqueleto.Joints[JointType.HandRight].Position.Z); this.j = esqueleto.Joints[JointType.HandRight]; if (servoVal.Length > 0) { if (this.isGrip) { servoVal = servoVal + ",10x"; } else { servoVal = servoVal + ",100x"; } Console.WriteLine(servoVal); ArduinoPort.WriteLine(servoVal); while (((char)ArduinoPort.ReadChar()) != 'E') { ; } // this.dis = ArduinoPort.ReadByte().ToString(); } this.servoVal = ""; }
static CashDrawerResult OpenCashDrawer() { /* * LibUsbDotNet.Main.UsbDeviceFinder finder = new LibUsbDotNet.Main.UsbDeviceFinder(0x0451, 0x0909); * LibUsbDotNet.UsbDevice device = LibUsbDotNet.UsbDevice.OpenUsbDevice(finder); * * LibUsbDotNet.IUsbDevice iusb = (device as LibUsbDotNet.IUsbDevice); * if (iusb != null) * { * iusb.SetConfiguration(1); * iusb.ClaimInterface(0); * } * * LibUsbDotNet.UsbEndpointWriter writer = device.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep01); * int transferLength = 0; * * System.IO.MemoryStream ms = new System.IO.MemoryStream(); * UniversalEditor.IO.BinaryWriter bw = new UniversalEditor.IO.BinaryWriter(ms); * bw.WriteFixedLengthString("a\r\n"); * bw.Close(); * byte[] data = ms.ToArray(); * * writer.Write(data, 1000, out transferLength); * writer.Flush(); * * device.Close(); */ System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort("COM1"); port.Open(); bool p = port.IsOpen; port.ReadTimeout = 1000; int status = port.ReadChar(); CashDrawerResult result = CashDrawerResult.Undefined; if (status == 1) { port.Write("a"); // close and reopen the port to reset - otherwise the driver // caches the result of the next status read (probably because it // assumes the drawer opened successfully after an attempt to open it?) port.Close(); port.Open(); System.Threading.Thread.Sleep(100); status = port.ReadChar(); if (status == 1) { // cash drawer is closed nid.ShowBalloonTip(3000, "Cash drawer did not open", "The open command was sent, but the cash drawer reported that it is still closed. Is there something blocking the tray?", ToolTipIcon.Error); result = CashDrawerResult.Locked; } else { // cash drawer is open nid.ShowBalloonTip(3000, "Cash drawer opened", "Please accept the customer's payment and issue the correct change. Don't forget to thank them for their business!", ToolTipIcon.Info); result = CashDrawerResult.Opened; } } else { // cash drawer is open nid.ShowBalloonTip(3000, "Cash drawer did not open", "The cash drawer reported that it is already open.", ToolTipIcon.Error); result = CashDrawerResult.AlreadyOpened; } port.Close(); return(result); }