public new void Open() { // 500ms write timeout - win32 api default this.WriteTimeout = 500; if (base.IsOpen) { return; } try { // Console.WriteLine("Doing SerialPortFixer"); // SerialPortFixer.Execute(this.PortName); // Console.WriteLine("Done SerialPortFixer"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (PortName.StartsWith("/")) { if (!File.Exists(PortName)) { throw new Exception("No such device"); } } base.Open(); }
/* protected override void Dispose(bool disposing) { try { try { Type mytype = typeof(System.IO.Ports.SerialPort); FieldInfo field = mytype.GetField("internalSerialStream", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { Stream stream = (Stream)field.GetValue(this); if (stream != null) { try { stream.Dispose(); } catch (Exception ex) { Console.WriteLine("1 " + ex.ToString()); } stream = null; } } } catch (Exception ex) { Console.WriteLine("2 " + ex.ToString()); } base.Dispose(disposing); } catch (Exception ex) { Console.WriteLine("3 " + ex.ToString()); } } */ public new void Open() { // 500ms write timeout - win32 api default this.WriteTimeout = 500; if (base.IsOpen) return; try { // this causes element not found with bluetooth devices. if (BaudRate > 115200) { Console.WriteLine("Doing SerialPortFixer"); SerialPortFixer.Execute(this.PortName); Console.WriteLine("Done SerialPortFixer"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (PortName.StartsWith("/")) if (!File.Exists(PortName)) throw new Exception("No such device"); try { base.Open(); } catch { try { Close(); } catch { } throw; } }
float Force; //存储上一次力值,避免 丰仪仪表不准确的情况发生 /// <summary> /// 开始采集 /// </summary> /// <param name="ControllerOrder"></param> public void StartAcquisition() { if (rfpcomm == null) { rfpcomm = new FyComm(); rfpcomm.OnAddItem += new IFyCommEvents_OnAddItemEventHandler(rfpcomm_OnAddItem); rfpcomm.Baud = Convert.ToUInt32(PortBaud); rfpcomm.PortNo = Convert.ToInt32(PortName.Substring(3)); } IsContinue = true; IsFinished = false; try { if (!rfpcomm.Active) { rfpcomm.Active = true; } while (!IsContinue) { rfpcomm.Active = false; } } catch (Exception ex) { _Log.Error(ex.ToString()); } }
public void Open() { if (this.BaudRate < 1) { throw new ArgumentOutOfRangeException("BaudRate"); } if (PortName.StartsWith("COM", false, null) && PortName.Length == 4) { if (PortName.EndsWith("1") || PortName.EndsWith("2") || PortName.EndsWith("3") || PortName.EndsWith("4")) { IsOpen = true; } else if (PortName.EndsWith("5")) { throw new UnauthorizedAccessException("COM5 already in use."); } else { throw new IOException("Invalid COM port."); } } else { throw new ArgumentException("ERROR: Invalid Port Name. PortName must begin with COM followed by a number."); } }
public void SaveUserData() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["CommunicationMode"].Value = CommunicationMode.ToString(); config.AppSettings.Settings["IPAddress"].Value = IPAddress.ToString(); config.AppSettings.Settings["TCPPort"].Value = TCPPort.ToString(); config.AppSettings.Settings["PortName"].Value = PortName.ToString(); config.AppSettings.Settings["Baud"].Value = Baud.ToString(); config.AppSettings.Settings["Parity"].Value = Parity.ToString(); config.AppSettings.Settings["SlaveId"].Value = SlaveId.ToString(); config.AppSettings.Settings["DataBits"].Value = DataBits.ToString(); config.AppSettings.Settings["StopBits"].Value = StopBits.ToString(); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); //Properties.Settings.Default.CommunicationMode = CommunicationMode.ToString(); //Properties.Settings.Default.IPAddress = IPAddress.ToString(); //Properties.Settings.Default.DisplayFormat = DisplayFormat.ToString(); //Properties.Settings.Default.TCPPort = TCPPort; //Properties.Settings.Default.PortName = PortName; //Properties.Settings.Default.Baud = Baud; //Properties.Settings.Default.Parity = Parity; //Properties.Settings.Default.StartAddress = StartAddress; //Properties.Settings.Default.DataLength = DataLength; //Properties.Settings.Default.SlaveId = SlaveId; //Properties.Settings.Default.SlaveDelay = SlaveDelay; //Properties.Settings.Default.DataBits = DataBits; //Properties.Settings.Default.StopBits = StopBits; //Properties.Settings.Default.Save(); }
public override int GetHashCode() { unchecked { var hashCode = ServiceName?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ (PortName?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Protocol?.GetHashCode() ?? 0); return(hashCode); } }
public override string ToString() { List <string> paraList = new List <string>(); paraList.Add(PortName.ToString()); paraList.Add(BaudRate.ToString()); paraList.Add(DataBits.ToString()); paraList.Add(StopBits.ToString()); paraList.Add(Parity.ToString()); return(String.Format("{0}://{1}", Prefix, String.Join(SpitChar, paraList))); }
public override int GetHashCode() { return (PortName.GetHashCode() ^ BaudRate.GetHashCode() ^ DataBits.GetHashCode() ^ Parity.GetHashCode() ^ StopBits.GetHashCode()); }
public void Save() { Basic.SetRegistryKey("UseScale", UseScale.ToString()); Basic.SetRegistryKey("Commend", Commend.ToString()); Basic.SetRegistryKey("PortName", PortName.ToString()); Basic.SetRegistryKey("BaudRate", BaudRate.ToString()); Basic.SetRegistryKey("Parity", Parity.ToString()); Basic.SetRegistryKey("DataBit", DataBit.ToString()); Basic.SetRegistryKey("StopBit", StopBit.ToString()); Basic.SetRegistryKey("ScaleType", ScaleType.ToString()); Basic.SetRegistryKey("DefaultWeight", DefaultWeight.ToString()); Basic.SetRegistryKey("BarcodeSize", BarcodeSize.ToString()); }
protected ParallelPortDevice(RegistryKey deviceKey) { DeviceKeyName = deviceKey.Name; string HKLM_BackSlash = CurrentControlSetDeviceEnumerator.CombinePath(CurrentControlSetDeviceEnumerator.HKLM, string.Empty); if (DeviceKeyName.StartsWith(HKLM_BackSlash)) { DeviceKeyName = DeviceKeyName.Replace(HKLM_BackSlash, string.Empty); } object _class = deviceKey.GetValue("Class"); // do not translate Class = objectToString(_class); object deviceDesc = deviceKey.GetValue("DeviceDesc"); // do not translate DeviceDesc = objectToString(deviceDesc); object friendlyName = deviceKey.GetValue("FriendlyName"); // do not translate FriendlyName = objectToString(friendlyName); object mfg = deviceKey.GetValue("Mfg"); // do not translate Mfg = objectToString(mfg); using (RegistryKey deviceParametersKey = deviceKey.OpenSubKey("Device Parameters")) // do not translate { if (null != deviceParametersKey) { object portName = deviceParametersKey.GetValue("PortName"); // do not translate PortName = objectToString(portName); if (PortName.EndsWith(":")) { PortName = PortName.Substring(0, PortName.Length - 1); } object ieee1284Manufacturer = deviceParametersKey.GetValue("IEEE_1284_Manufacturer"); IEEE_1284_Manufacturer = objectToString(ieee1284Manufacturer); object ieee1284Model = deviceParametersKey.GetValue("IEEE_1284_Model"); IEEE_1284_Model = objectToString(ieee1284Model); } } object upperFilters = deviceKey.GetValue("UpperFilters"); // do not translate UpperFilters = objectToString(upperFilters); object service = deviceKey.GetValue("Service"); // do not translate Service = objectToString(service); }
/// <summary> /// Occurs when users clicks connect. Once in the connected state, the /// buttons becomes a disconnect button. Clicking in the disconnected state /// will connect, clicking in the connected will disconnect. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnConnect_Click(object sender, RoutedEventArgs e) { // We're already connected - don't connect again! if (IsConnected) { validator.Close(); btnConnect.Content = "Connect"; IsConnected = false; return; } PortName = AvailablePorts.Text; if (string.IsNullOrEmpty(PortName) || PortName.Equals("Select Port")) { MessageBox.Show("Please select a port"); return; } // Instantiate a validator and register for all the handlers we need IsConnected = true; btnConnect.Content = "Disconnect"; // Create a new instance using the specified port and in escrow mode config = new RS232Config(PortName, IsEscrowMode); validator = new PyramidAcceptor(config); // Configure logging - see DebugData_Sample.cs validator.OnSerialData += config_OnSerialData; ConsoleLoggerMaster.ItemsSource = debugQueueMaster; ConsoleLoggerSlave.ItemsSource = debugQueueSlave; // Configure events and state (All optional) - see StateAndEvents_Sample.cs validator.OnEvent += validator_OnEvent; validator.OnStateChanged += validator_OnStateChanged; validator.OnError += validator_OnError; validator.OnCashboxAttached += validator_CashboxAttached; // Required if you are in escrow mode - see CreditAndEscrow_Sample.cs validator.OnEscrow += validator_OnEscrow; // Technically optional but you probably want this event - see CreditAndEscrow_Sample.cs validator.OnCredit += validator_OnCredit; // This starts the acceptor - REQUIRED!! validator.Connect(); }
public bool HasValidOperationForInput(IPortModel port, TypeHandle typeHandle) { PortName portName = ReferenceEquals(port, InputPortA) ? PortName.PortA : PortName.PortB; var otherPort = portName == PortName.PortA ? InputPortB : InputPortA; var dataType = typeHandle.Resolve(Stencil); if (otherPort.Connected) { Type otherPortType = otherPort.DataType.Resolve(Stencil); return(portName == PortName.PortB ? TypeSystem.IsBinaryOperationPossible(otherPortType, dataType, Kind) : TypeSystem.IsBinaryOperationPossible(dataType, otherPortType, Kind)); } return(TypeSystem.GetOverloadedBinaryOperators(dataType).Contains(Kind)); }
public override string ToString() { var s = new StringBuilder(); s.Append(NodeName.ValueToQuotedLiteral()); if (HasPort) { s.Append(":").Append(PortName.ValueToQuotedLiteral()); } if (HasCompass) { s.Append(":").Append(Compass.Value); } return(s.ToString()); }
public void OpenIt() { Log.PrintLog(this, "OpenSerialPort[" + OpenCnt.ToString() + "]", LogDetailLevel.LogRelevant); OpenCnt++; BufferedBDAddress = null; /* * Generate a number for temp BD address for TxRx test* */ PortNum = 0; char[] Chars = PortName.ToArray(); int FirstNumIndex = Chars.Length; for (int i = 0; i < Chars.Length; i++) { FirstNumIndex--; if (Chars[FirstNumIndex] < '0' || Chars[FirstNumIndex] > '9') { FirstNumIndex++; break; } } if (FirstNumIndex < Chars.Length) { try { PortNum = Convert.ToInt32(PortName.Substring(FirstNumIndex)); } catch { PortNum = 0; } } if (PortNum == 0) { Log.PrintLog(this, "Failed to parse the PortNumber from PortName", LogDetailLevel.LogRelevant); } base.Open(); }
/// <summary> /// Initializes a new instance of the class using the specified port name, baud rate, parity bit, data bits, and stop bit. /// </summary> /// <param name="portName">The port to use.</param> /// <param name="baudRate">The baud rate.</param> /// <param name="parity">One of the Parity values.</param> /// <param name="dataBits">The data bits value.</param> /// <param name="stopBits">The stop bits value.</param> /// <exception cref="System.ArgumentNullException">PortName cannot be null.</exception> public UartPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) { if (portName == null) { throw new ArgumentNullException("portName", "PortName cannot be null."); } PortName = portName.Trim(); if (IsRunningOnMono == false) { PortName = PortName.ToUpperInvariant(); } BaudRate = baudRate; Parity = parity; DataBits = dataBits; StopBits = stopBits; NewLine = "\n"; ReadTimeout = UartPort.InfiniteTimeout; WriteTimeout = UartPort.InfiniteTimeout; }
private List <NamedPort> BuildNamedPorts() { var ports = new List <NamedPort>(); if (NamedPort != null) { ports.AddRange(NamedPort); } if (PortName.Length != PortNumber.Length) { throw new PSInvalidOperationException( "PortName and PortNumber must have the same number of arguments."); } Func <string, int, NamedPort> buildNamedPort = (name, number) => new NamedPort { Name = name, Port = number }; ports.AddRange(PortName.Zip(PortNumber, buildNamedPort)); return(ports); }
// function fetches ships data from ports using web browser public static void getShipsFromPort(PortName portName) { string url = string.Empty; WebBrowserDocumentCompletedEventHandler cbFunc = null; // sanity check if (portName == PortName.Unknown) { OrdersParser._Form.log(string.Format("Unknown port: {0}", portName.ToString()), OrdersParser.LogLevel.Error); return; } OrdersParser._Form.log(string.Format("Fetching data from {0} port", portName.ToString())); // increase counter to inform on web activity Interlocked.Increment(ref webDataReadyCounter); if (portName == PortName.Ashdod) { url = ASHDOD_URL; cbFunc = browser_DocumentCompletedAshdod; } if (portName == PortName.Haifa) { url = HAIFA_URL; cbFunc = browser_DocumentCompletedHaifa; } var th = new Thread(() => { var br = new WebBrowser(); br.ScriptErrorsSuppressed = true; br.DocumentCompleted += cbFunc; br.Navigate(url); Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); }
//**************************************************************************** //メソッド名:OutBit(指定ポートにビット単位での出力) //引数:引数�@ ポート名("P00"、"P01"・・・"P07")引数�A出力値(H:0/ L: 1) //戻り値:正常0、異常1 //**************************************************************************** public int OutBit(PortName pName, BitName bName, OutData data) { //ポートの特定 byte PortOutData = 0; switch (pName) { case PortName.P0: this.Port = EPX64R_PORT0; PortOutData = this.p0Outdata; break; case PortName.P1: this.Port = EPX64R_PORT1; PortOutData = this.p1Outdata; break; case PortName.P2: this.Port = EPX64R_PORT2; PortOutData = this.p2Outdata; break; case PortName.P3: this.Port = EPX64R_PORT3; PortOutData = this.p3Outdata; break; case PortName.P4: this.Port = EPX64R_PORT4; PortOutData = this.p4Outdata; break; case PortName.P5: this.Port = EPX64R_PORT5; PortOutData = this.p5Outdata; break; case PortName.P6: this.Port = EPX64R_PORT6; PortOutData = this.p6Outdata; break; case PortName.P7: this.Port = EPX64R_PORT7; PortOutData = this.p7Outdata; break; default: return(1); } //ビットの特定 byte Temp = 0; int Num = 0; switch (bName) { case BitName.b0: Num = 0; Temp = 0xFE; break; case BitName.b1: Num = 1; Temp = 0xFD; break; case BitName.b2: Num = 2; Temp = 0xFB; break; case BitName.b3: Num = 3; Temp = 0xF7; break; case BitName.b4: Num = 4; Temp = 0xEF; break; case BitName.b5: Num = 5; Temp = 0xDF; break; case BitName.b6: Num = 6; Temp = 0xBF; break; case BitName.b7: Num = 7; Temp = 0x7F; break; } //データの出力 byte Data = 0; switch (data) { case OutData.H: Data = 1; break; case OutData.L: Data = 0; break; } byte OutputValue = (byte)((PortOutData & Temp) | (Data << Num));//byteでキャストしないと怒られる int flag = EPX64R.EPX64R_OutputPort(this.hDevice, Port, OutputValue); if (flag != EPX64R.EPX64R_OK) { EPX64R.EPX64R_Close(this.hDevice); // Device Close //MessageBox.Show("EPX64R_OutputPort() Error"); return(1); } switch (pName) { case PortName.P0: this.p0Outdata = OutputValue; break; case PortName.P1: this.p1Outdata = OutputValue; break; case PortName.P2: this.p2Outdata = OutputValue; break; case PortName.P3: this.p3Outdata = OutputValue; break; case PortName.P4: this.p4Outdata = OutputValue; break; case PortName.P5: this.p5Outdata = OutputValue; break; case PortName.P6: this.p6Outdata = OutputValue; break; case PortName.P7: this.p7Outdata = OutputValue; break; } return(0); }
public override string ToString() { return(String.Format("{0}-{1}-{2}-{3}-{4}", PortName.ToString(), BaudRate.ToString(), DataBits.ToString(), StopBits.ToString(), Parity.ToString())); }
public void Open() { // 500ms write timeout - win32 api default WriteTimeout = 500; if (IsOpen) { return; } if (PortName.StartsWith("/")) { if (!File.Exists(PortName)) { throw new Exception("No such device"); } } try { IsOpen = false; BaseStream = new MemoryStream(20000); var dwFlagsAndAttributes = 128; safeFileHandle = CreateFile("\\\\.\\" + PortName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero); if (safeFileHandle.IsInvalid) { throw new Exception("Invalid Port"); } var num1 = 0; var commProp = default(COMMPROP); if (!GetCommProperties(safeFileHandle, ref commProp) || !GetCommModemStatus(safeFileHandle, ref num1)) { var lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == 87 || lastWin32Error == 6) { //throw new ArgumentException(SR.GetString("Arg_InvalidSerialPortExtended"), "portName"); } //WinIOError(lastWin32Error, string.Empty); } //var comStat = default(COMSTAT); var dcb = default(DCB); if (!GetCommState(safeFileHandle, ref dcb)) { } dcb.BaudRate = (uint)BaudRate; dcb.ByteSize = 8; dcb.StopBits = 0; dcb.Parity = 0; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363214(v=vs.85).aspx SetDcbFlag(dcb, 0, 1); //fBinary SetDcbFlag(dcb, 1, 0); //fParity SetDcbFlag(dcb, 2, 1); //fOutxCtsFlow SetDcbFlag(dcb, 3, 0); // fOutxDsrFlow SetDcbFlag(dcb, 4, 0); //fDtrControl SetDcbFlag(dcb, 5, 0); //fDsrSensitivity SetDcbFlag(dcb, 6, 0); //fTXContinueOnXoff SetDcbFlag(dcb, 7, 0); //fOutX SetDcbFlag(dcb, 8, 0); //fInX SetDcbFlag(dcb, 9, 0); //fErrorChar SetDcbFlag(dcb, 10, 0); //fNull SetDcbFlag(dcb, 11, 1); //fRtsControl SetDcbFlag(dcb, 14, 0); //fAbortOnError if (!SetCommState(safeFileHandle, ref dcb)) { } commTimeouts.ReadTotalTimeoutConstant = 0; commTimeouts.ReadTotalTimeoutMultiplier = 0; commTimeouts.ReadIntervalTimeout = -1; if (!SetCommTimeouts(safeFileHandle, ref commTimeouts)) { } //ThreadPool.BindHandle(safeFileHandle); // SetCommMask(safeFileHandle, 507); IsOpen = true; var th = new Thread(() => { while (IsOpen) { var buffer = new byte[4096]; uint read = 0; ReadFile(safeFileHandle, buffer, (uint)buffer.Length, out read, IntPtr.Zero); if (!IsOpen) { continue; } lock (locker) { var pos = BaseStream.Position; BaseStream.Write(buffer, 0, (int)read); BaseStream.Seek(pos, SeekOrigin.Begin); } } safeFileHandle.Dispose(); }); th.IsBackground = true; th.Name = "CommsSerialPipe reader"; th.Start(); } catch { try { Close(); } catch { } throw; } }
//Load - Application Settings public void SettingsLoad() { try { Debug.WriteLine("Loading application settings..."); //Check connected com ports foreach (string PortName in SerialPort.GetPortNames()) { int PortNumberRaw = Convert.ToInt32(PortName.Replace("COM", string.Empty)); cb_ComPort.Items[PortNumberRaw - 1] = PortName + " (Connected)"; if (Convert.ToBoolean(ConfigurationManager.AppSettings["FirstLaunch2"])) { SettingsFunction.Save("ComPort", PortNumberRaw.ToString()); } } //Load - Com Port cb_ComPort.SelectedIndex = (Convert.ToInt32(ConfigurationManager.AppSettings["ComPort"]) - 1); //Load - Baud Rate textbox_BaudRate.Text = ConfigurationManager.AppSettings["BaudRate"].ToString(); //Load - Led Automatic Before bool LedAutoOnOffBefore = Convert.ToBoolean(ConfigurationManager.AppSettings["LedAutoOnOffBefore"]); cb_LedAutoOnOffBefore.IsChecked = LedAutoOnOffBefore; timepicker_LedAutoTimeBefore.IsEnabled = LedAutoOnOffBefore; timepicker_LedAutoTimeBefore.DateTimeValue = DateTime.Parse(ConfigurationManager.AppSettings["LedAutoTimeBefore"], vAppCultureInfo); //Load - Led Automatic After bool LedAutoOnOffAfter = Convert.ToBoolean(ConfigurationManager.AppSettings["LedAutoOnOffAfter"]); cb_LedAutoOnOffAfter.IsChecked = LedAutoOnOffAfter; timepicker_LedAutoTimeAfter.IsEnabled = LedAutoOnOffAfter; timepicker_LedAutoTimeAfter.DateTimeValue = DateTime.Parse(ConfigurationManager.AppSettings["LedAutoTimeAfter"], vAppCultureInfo); //Load - Server Port tb_ServerPort.Text = ConfigurationManager.AppSettings["ServerPort"].ToString(); //Load - Monitor Capture cb_MonitorCapture.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["MonitorCapture"]); //Load - Led Mode cb_LedMode.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedMode"]); //Load - Adjust Black Bars cb_AdjustBlackBars.IsChecked = Convert.ToBoolean(ConfigurationManager.AppSettings["AdjustBlackBars"]); //Load - Led Bottom Gap tb_LedBottomGap.Text = "Led gap bottom stand: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedBottomGap"]) + " leds"; sldr_LedBottomGap.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedBottomGap"]); //Load - Led contrast level tb_LedContrast.Text = "Contrast level: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedContrast"]); sldr_LedContrast.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedContrast"]); //Load - Led brightness level tb_LedBrightness.Text = "Brightness level: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedBrightness"]) + "%"; sldr_LedBrightness.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedBrightness"]); //Load - Led Minimum Brightness tb_LedMinBrightness.Text = "Minimum brightness level: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedMinBrightness"]) + "%"; sldr_LedMinBrightness.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedMinBrightness"]); //Load - Led Gamma tb_LedGamma.Text = "Gamma level: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedGamma"]) + "%"; sldr_LedGamma.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedGamma"]); //Load - Led Saturation tb_LedSaturation.Text = "Color saturation: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedSaturation"]) + "%"; sldr_LedSaturation.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedSaturation"]); //Load - Led Temperature tb_LedTemperature.Text = "Color temperature: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedTemperature"]) + "K"; sldr_LedTemperature.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedTemperature"]); //Load - Color Loop Speed tb_ColorLoopSpeed.Text = "Color loop speed: " + Convert.ToInt32(ConfigurationManager.AppSettings["ColorLoopSpeed"]) + " ms"; sldr_ColorLoopSpeed.Value = Convert.ToInt32(ConfigurationManager.AppSettings["ColorLoopSpeed"]); //Load - Spectrum Rotation Speed tb_SpectrumRotationSpeed.Text = "Spectrum rotation speed: " + Convert.ToInt32(ConfigurationManager.AppSettings["SpectrumRotationSpeed"]) + " sec"; sldr_SpectrumRotationSpeed.Value = Convert.ToInt32(ConfigurationManager.AppSettings["SpectrumRotationSpeed"]); //Load - Solid Led Color string SolidLedColor = ConfigurationManager.AppSettings["SolidLedColor"].ToString(); button_ColorPickerSolid.Background = new BrushConverter().ConvertFrom(SolidLedColor) as SolidColorBrush; //Load - Led Hue tb_LedHue.Text = "Color hue: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedHue2"]) + "°"; sldr_LedHue.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedHue2"]); //Load - Led Minimum Color tb_LedMinColor.Text = "Minimum color brightness: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedMinColor"]) + "%"; sldr_LedMinColor.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedMinColor"]); //Load - Led Color Red tb_LedColorRed.Text = "Red: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedColorRed"]) + "%"; sldr_LedColorRed.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedColorRed"]); //Load - Led Color Green tb_LedColorGreen.Text = "Green: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedColorGreen"]) + "%"; sldr_LedColorGreen.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedColorGreen"]); //Load - Led Color Blue tb_LedColorBlue.Text = "Blue: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedColorBlue"]) + "%"; sldr_LedColorBlue.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedColorBlue"]); //Load - Led Capture Range tb_LedCaptureRange.Text = "Led capture range: " + Convert.ToInt32(ConfigurationManager.AppSettings["LedCaptureRange"]) + "%"; sldr_LedCaptureRange.Value = Convert.ToInt32(ConfigurationManager.AppSettings["LedCaptureRange"]); //Load - Blackbar detect rate tb_AdjustBlackbarRate.Text = "Blackbar detection rate: " + Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackbarRate"]) + " ms"; sldr_AdjustBlackbarRate.Value = Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackbarRate"]); //Load - Blackbar detect range tb_AdjustBlackbarRange.Text = "Blackbar detection range: " + Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackbarRange"]) + "%"; sldr_AdjustBlackbarRange.Value = Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackbarRange"]); //Load - Adjust Blackbar Brightness tb_AdjustBlackBarBrightness.Text = "Blackbar minimum brightness: " + Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackBarBrightness"]) + "%"; sldr_AdjustBlackBarBrightness.Value = Convert.ToInt32(ConfigurationManager.AppSettings["AdjustBlackBarBrightness"]); //Load - Led Side Types combobox_LedSideFirst.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedSideFirst"]); combobox_LedSideSecond.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedSideSecond"]); combobox_LedSideThird.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedSideThird"]); combobox_LedSideFourth.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedSideFourth"]); //Load - Led Count textbox_LedCountFirst.Text = Convert.ToString(ConfigurationManager.AppSettings["LedCountFirst"]); textbox_LedCountSecond.Text = Convert.ToString(ConfigurationManager.AppSettings["LedCountSecond"]); textbox_LedCountThird.Text = Convert.ToString(ConfigurationManager.AppSettings["LedCountThird"]); textbox_LedCountFourth.Text = Convert.ToString(ConfigurationManager.AppSettings["LedCountFourth"]); int totalCount = Convert.ToInt32(textbox_LedCountFirst.Text) + Convert.ToInt32(textbox_LedCountSecond.Text) + Convert.ToInt32(textbox_LedCountThird.Text) + Convert.ToInt32(textbox_LedCountFourth.Text); textblock_LedCount.Text = "Total led count: " + totalCount + " (must be equal with arduino script)"; //Load - Led Output cb_LedOutput.SelectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["LedOutput"]); //Load - Update Rate int updateRateMs = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateRate"]); string updateRateFps = Convert.ToInt32(1000 / updateRateMs).ToString(); tb_UpdateRate.Text = "Led update rate: " + updateRateMs + " ms (" + updateRateFps + " fps)"; sldr_UpdateRate.Value = updateRateMs; //Load - Led Smoothing int smoothingFrames = Convert.ToInt32(ConfigurationManager.AppSettings["LedSmoothing"]); tb_LedSmoothing.Text = "Led smoothing: " + smoothingFrames + " frames"; sldr_LedSmoothing.Value = smoothingFrames; //Load - Debug Mode checkbox_DebugMode.IsChecked = Convert.ToBoolean(ConfigurationManager.AppSettings["DebugMode"]); checkbox_DebugBlackBar.IsChecked = Convert.ToBoolean(ConfigurationManager.AppSettings["DebugBlackBar"]); checkbox_DebugColor.IsChecked = Convert.ToBoolean(ConfigurationManager.AppSettings["DebugColor"]); checkbox_DebugSave.IsChecked = Convert.ToBoolean(ConfigurationManager.AppSettings["DebugSave"]); //Check if application is set to launch on Windows startup string targetName = Assembly.GetEntryAssembly().GetName().Name; string targetFileShortcut = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), targetName + ".url"); if (File.Exists(targetFileShortcut)) { cb_WindowsStartup.IsChecked = true; } } catch (Exception ex) { Debug.WriteLine("Failed to load the settings: " + ex.Message); } }
public override void Single() { foreach (PIMTestTrace tr in ItemList) { (tr.TestResult as XYTraceResult).ResultData.Clear(); } if (GeneTestSetup.Instance.IsSimulated) { switch (CalType) { case PIMCalType.Point: foreach (PIMTestTrace tr in ItemList) { (tr.TestResult as XYTraceResult).ResultData.Clear(); if (tr.TypeName == PIMTestTraceType.PIMTrace1) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = 0, Y = GeneFun.GetRand(-140, -100) }); } if (tr.TypeName == PIMTestTraceType.PIMTrace2) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = 0, Y = GeneFun.GetRand(-140, -100) }); } } PIMPower1 = GeneFun.GetRand(42, 44); PIMPower2 = GeneFun.GetRand(42, 44); break; case PIMCalType.Sweep: foreach (PIMTestTrace tr in ItemList) { (tr.TestResult as XYTraceResult).ResultData.Clear(); if (tr.SweepSource == PIMSweepSourceEnum.F1) { double[] freqList = GeneFun.GenerateIndexedArray(StartFreq1, StopFreq1, points1); foreach (var freq in freqList) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = freq, Y = GeneFun.GetRand(-140, -100) }); } } if (tr.SweepSource == PIMSweepSourceEnum.F2) { double[] freqList = GeneFun.GenerateIndexedArray(StartFreq2, StopFreq2, points2); foreach (var freq in freqList) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = freq, Y = GeneFun.GetRand(-140, -100) }); } } } PIMPower1 = GeneFun.GetRand(42, 44); PIMPower2 = GeneFun.GetRand(42, 44); break; case PIMCalType.TimeDomain: int num = PIMOrder / 2; double dblIMF = (((num + 1) * CWFreq1) - (num * CWFreq2)); foreach (PIMTestTrace tr in ItemList) { (tr.TestResult as XYTraceResult).ResultData.Clear(); if (tr.SweepSource == PIMSweepSourceEnum.F1) { for (int i = 0; i < 50; i++) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = i, Y = GeneFun.GetRand(-140, -100) }); } } if (tr.SweepSource == PIMSweepSourceEnum.F2) { for (int i = 0; i < 50; i++) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = i, Y = GeneFun.GetRand(-140, -100) }); } } } PIMPower1 = GeneFun.GetRand(42, 44); PIMPower2 = GeneFun.GetRand(42, 44); break; default: break; } } else { //setting to instru MeasInfo.InstruInfoList[0].InstruDriver.Reset(); PIMTester.setFreq(CWFreq1, CWFreq2); PIMTester.setPow(CWPOW1, CWPOW2); PIMTester.setMeasMode(MeasMode.ToString()); PIMTester.setUnit(ResultUnit.ToString()); PIMTester.setIMOrder(PIMOrder); PIMTester.setPort(PortName.ToString()); if (CalType == PIMCalType.Point) { int num = PIMOrder / 2; double dblIMF = ((num + 1) * CWFreq1) - (num * CWFreq2); PIMTester.setModeStandard(dblIMF); PIMTester.setPowOn(true, true); List <XYData> lstRes = new List <XYData>(); double[] strRes = new double[3]; if (ResultUnit == ResultUnit.dBm) { strRes = PIMTester.getPointIMPow(0); } else { strRes = PIMTester.getPointIMPow(CWPOW1); } PIMPower1 = strRes[0]; PIMPower2 = strRes[1]; //XYData xyData = new XYData(); ////赋值 //xyData.X = dblIMF; //xyData.Y = strRes[2]; //lstRes.Add(xyData); //PIMTestResult1 = (XYDataArr)lstRes; foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace1) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = dblIMF, Y = strRes[2] }); } if (tr.TypeName == PIMTestTraceType.PIMTrace2) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = dblIMF, Y = strRes[2] }); } } } else if (CalType == PIMCalType.Sweep) { SweepFlag = PIMTester.getSweepFlag(); //int number = (PIMOrder / 2); //double dblTestStep1 = TestStepper * (number + 1f); //double dblTestStep2 = TestStepper * number; int intTotalCount1 = (SweepFlag == "F1UP" ? (int)((StopFreq1 - StartFreq1) / TestStepper) : (int)((StopFreq2 - StartFreq2) / TestStepper)); int intTotalCount2 = (SweepFlag == "F1UP" ? (int)((StopFreq2 - StartFreq2) / TestStepper) : (int)((StopFreq1 - StartFreq1) / TestStepper)); PIMTester.setModeSweepTx(TestStepper, CWFreq1, CWFreq2); PIMTester.setPowOn(true, true); double newData1 = -200; double newData2 = -200; double dblIMF1 = 0; double dblIMF2 = 0; for (int i = 0; i < (intTotalCount1 + intTotalCount2 + 2); i++) { bool bRunState = GetRunState(); if (!bRunState) { PIMTester.setPowOn(false, false); foreach (PIMTestTrace tr in ItemList) { (tr.TestResult as XYTraceResult).ResultData.Clear(); } return; } double dblNowFreq1 = 0; double dblNowFreq2 = 0; int j = 0; if (i <= intTotalCount1) { j = i; dblNowFreq1 = (SweepFlag == "F1UP" ? (StartFreq1 + i * TestStepper) : StartFreq1); dblNowFreq2 = (SweepFlag == "F1UP" ? StopFreq2 : (StopFreq2 - j * TestStepper)); } else { j = (i - intTotalCount1 - 1); dblNowFreq1 = (SweepFlag == "F1UP" ? StartFreq1 : (StartFreq1 + i * TestStepper)); dblNowFreq2 = (SweepFlag == "F1UP" ? (StopFreq2 - j * TestStepper) : StopFreq2); } PIMTester.setPowATT("CARR1", CWPOW1); PIMTester.setPowATT("CARR2", CWPOW2); double[] strRes = new double[4]; if (ResultUnit == ResultUnit.dBm) { strRes = PIMTester.getSweepIMPow(PIMOrder, dblNowFreq1, dblNowFreq2, 0); } else { strRes = PIMTester.getSweepIMPow(PIMOrder, dblNowFreq1, dblNowFreq2, CWPOW1); } PIMPower1 = strRes[0]; PIMPower2 = strRes[1]; if (i <= intTotalCount1) { if (SweepFlag == "F1UP") { foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace1) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = strRes[2], Y = strRes[3] }); } } if (newData1 < strRes[3]) { dblIMF1 = strRes[2]; newData1 = strRes[3]; } } else { foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace2) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = strRes[2], Y = strRes[3] }); } } if (newData2 < strRes[3]) { dblIMF2 = strRes[2]; newData2 = strRes[3]; } } } else { if (SweepFlag == "F1UP") { foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace2) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = strRes[2], Y = strRes[3] }); } } if (newData2 < strRes[3]) { dblIMF2 = strRes[2]; newData2 = strRes[3]; } } else { foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace1) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = strRes[2], Y = strRes[3] }); } } if (newData1 < strRes[3]) { dblIMF1 = strRes[2]; newData1 = strRes[3]; } } } } } else { int num = PIMOrder / 2; double dblIMF = (((num + 1) * CWFreq1) - (num * CWFreq2)); PIMTester.setModeStandard(dblIMF); PIMTester.setPowOn(true, true); List <XYData> lstRes = new List <XYData>(); DateTime TimeOld = System.DateTime.Now; int i = 0; while (System.DateTime.Now.Subtract(TimeOld).TotalSeconds < TestTime) { bool bRunState = GetRunState(); if (!bRunState) { PIMTester.setPowOn(false, false); return; } PIMTester.setPowATT("CARR1", CWPOW1); PIMTester.setPowATT("CARR2", CWPOW2); double[] strRes = new double[3]; if (ResultUnit == ResultUnit.dBm) { strRes = PIMTester.getPointIMPow(0); } else { strRes = PIMTester.getPointIMPow(CWPOW1); } PIMPower1 = strRes[0]; PIMPower2 = strRes[1]; foreach (PIMTestTrace tr in ItemList) { if (tr.TypeName == PIMTestTraceType.PIMTrace1) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = i, Y = strRes[2] }); } if (tr.TypeName == PIMTestTraceType.PIMTrace2) { (tr.TestResult as XYTraceResult).ResultData.Add(new XYData { X = i, Y = strRes[2] }); } } i++; } } PIMTester.setPowOn(false, false); } SingleDBTime = DataUtils.StaticInfo.DBTime; }
public void Open() { if (PortName.ToUpper().StartsWith("COM")) { SerialPort sPort; sPort = new SerialPort(); sPort.PortName = PortName; sPort.WriteTimeout = 5000; sPort.ReadTimeout = -1; sPort.BaudRate = PortBaudRate; sPort.Parity = Parity.None; sPort.DataBits = 8; sPort.StopBits = StopBits.One; sPort.Handshake = Handshake.None; sPort.DtrEnable = false; sPort.RtsEnable = false; sPort.NewLine = System.Environment.NewLine; sPort.Open(); serialPort = sPort; } else { UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class FTDI myFtdiDevice = new FTDI(); // Determine the number of FTDI devices connected to the machine if (string.IsNullOrEmpty(PortName) || PortName.ToLower() == "auto") { Console.WriteLine("Searhing for dumper (FTDI device with name \"{0}\")...", DeviceName); ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString()); Console.WriteLine(""); } else { throw new IOException("Failed to get number of devices (error " + ftStatus.ToString() + ")"); } // If no devices available, return if (ftdiDeviceCount == 0) { throw new IOException("Failed to get number of devices (error " + ftStatus.ToString() + ")"); } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); PortName = null; if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { Console.WriteLine("Device Index: " + i.ToString()); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString()); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString()); Console.WriteLine(""); if (ftdiDeviceList[i].Description == DeviceName) { PortName = ftdiDeviceList[i].SerialNumber; } } } if (PortName == null) { throw new IOException("Famicom Dumper/Programmer not found"); } } // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(PortName); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to open device (error " + ftStatus.ToString() + ")"); } // Set data characteristics - Data bits, Stop bits, Parity ftStatus = myFtdiDevice.SetTimeouts(300000, 5000); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to set timeouts (error " + ftStatus.ToString() + ")"); } ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to set data characteristics (error " + ftStatus.ToString() + ")"); } // Set flow control ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x11, 0x13); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to set flow control (error " + ftStatus.ToString() + ")"); } // Set up device data parameters ftStatus = myFtdiDevice.SetBaudRate(PortBaudRate); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to set Baud rate (error " + ftStatus.ToString() + ")"); } d2xxPort = myFtdiDevice; } if (readingThread != null) { readingThread.Abort(); } readingThread = new Thread(readThread); readingThread.Start(); cpuInitOk = ppuInitOk = false; }
// function returns ship's arrival status to port public static ShipStatus shipStatusInPort(string vesselName, PortName portName, out string summaryStr) { List <Common.Anchoring> templist = new List <Common.Anchoring>(); string status = string.Empty; string arrivalDateStr = string.Empty; string dateFormat = "dd/MM/yy HH:mm"; summaryStr = string.Empty; // sanity check if (portName == PortName.Unknown) { summaryStr = "Unknown port"; return(ShipStatus.Unknown); } if (portName == PortName.Ashdod) { templist = Common.ashdodAnchoringList.Where(x => x.shipName.ToLower().Contains(vesselName.ToLower())) .OrderBy(x => x.importManifest) .ToList(); if (templist.Count > 0) { // Haifa port has the following statuses: // integer, means that ship is at berth // anchor, sailed, expected, means that ship is not at berth status = templist.FirstOrDefault().status; arrivalDateStr = templist.FirstOrDefault().arrivalDate.ToString(dateFormat); int res; if (int.TryParse(status, out res) == true) { // the value doesn't matter, but ship has arrived summaryStr = string.Format("Status: Arrived\r\nArrival Date: {0}", arrivalDateStr); return(ShipStatus.Arrived); } } } if (portName == PortName.Haifa) { templist = Common.haifaAnchoringList.Where(x => x.shipName.ToLower().Contains(vesselName.ToLower())) .OrderBy(x => x.importManifest) .ToList(); if (templist.Count > 0) { // Ashdod port has only 3 possible Hebrew string statuses status = templist.FirstOrDefault().status; arrivalDateStr = templist.FirstOrDefault().arrivalDate.ToString(dateFormat); // check if arrived if (status == AT_BERTH_HEB) { summaryStr = string.Format("Status: Arrived\r\nArrival Date: {0}", arrivalDateStr); return(ShipStatus.Arrived); } } } // check in the expected list keywords if (expectedStrList.Contains(status.ToLower())) { summaryStr = string.Format("Status: Expected\r\nArrival Date: {0}", arrivalDateStr); return(ShipStatus.Expected); } // error: didn't find anything - should not happen summaryStr = "Ship is not found in port"; return(ShipStatus.Unknown); }
public IPortModel GetPort(PortName portName) { return(portName == PortName.PortA ? InputPortA : InputPortB); }
//**************************************************************************** //メソッド名:OutByte(指定ポートにバイト単位での出力) //引数:引数�@ ポート名("P0"、"P1"・・・"P7")引数�A出力値(0x00〜0xFF) //戻り値:正常0、異常1 //**************************************************************************** public int OutByte(PortName pName, byte Data) { int flag = 0; //ポートの特定と出力データバッファの更新 switch (pName) { case PortName.P0: this.Port = EPX64R_PORT0; this.p0Outdata = Data; break; case PortName.P1: this.Port = EPX64R_PORT1; this.p1Outdata = Data; break; case PortName.P2: this.Port = EPX64R_PORT2; this.p2Outdata = Data; break; case PortName.P3: this.Port = EPX64R_PORT3; this.p3Outdata = Data; break; case PortName.P4: this.Port = EPX64R_PORT4; this.p4Outdata = Data; break; case PortName.P5: this.Port = EPX64R_PORT5; this.p5Outdata = Data; break; case PortName.P6: this.Port = EPX64R_PORT6; this.p6Outdata = Data; break; case PortName.P7: this.Port = EPX64R_PORT7; this.p7Outdata = Data; break; default: return(1); //ポート名間違えたら異常とする } //データの出力 flag = EPX64R.EPX64R_OutputPort(this.hDevice, this.Port, Data); if (flag != EPX64R.EPX64R_OK) { EPX64R.EPX64R_Close(this.hDevice); // Device Close //MessageBox.Show("EPX64R_OutputPort() Error"); return(1); } return(0); }
public override string ToString() { return(PortName.ToString() + ", " + BaudRate + (RtsCtsEnabled ? ", RTC/CTS Enabled" : "")); }
/// <summary> /// Opens a new serial port connection. /// </summary> /// <exception cref="System.InvalidOperationException">Port is already open.</exception> /// <exception cref="System.IO.IOException">The port is in an invalid state. -or- An attempt to set the state of the underlying port failed.</exception> /// <exception cref="System.UnauthorizedAccessException">Access is denied to the port.</exception> public void Open() { if (IsOpen) { throw new InvalidOperationException("Port is already open."); } if (IsRunningOnMono == false) { var portName = (PortName.StartsWith(@"\\?\", StringComparison.Ordinal) ? "" : @"\\?\") + PortName; Handle = NativeMethods.CreateFileW( portName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, //exclusive access IntPtr.Zero, NativeMethods.OPEN_EXISTING, 0, IntPtr.Zero ); if (IsOpen == false) { throw new IOException("The port is in an invalid state."); } var config = new NativeMethods.COMMCONFIG(); config.dwSize = Marshal.SizeOf(config); config.wVersion = 1; config.wReserved = 0; config.dcb = new NativeMethods.DCB(); config.dcb.DCBlength = Marshal.SizeOf(config.dcb); config.dcb.BaudRate = BaudRate; config.dcb.fBinary = 1; config.dcb.fParity = 0; config.dcb.fOutxCtsFlow = 0; config.dcb.fOutxDsrFlow = 0; config.dcb.fDtrControl = NativeMethods.DTR_CONTROL_ENABLE; config.dcb.fDsrSensitivity = 0; config.dcb.fTXContinueOnXoff = 0; config.dcb.fOutX = 0; config.dcb.fInX = 0; config.dcb.fErrorChar = 0; config.dcb.fNull = 0; config.dcb.fRtsControl = NativeMethods.RTS_CONTROL_ENABLE; config.dcb.fAbortOnError = 0; config.dcb.fDummy2 = 0; config.dcb.wReserved = 0; config.dcb.XonLim = 0; config.dcb.XoffLim = 0; config.dcb.ByteSize = (byte)DataBits; switch (Parity) { case Parity.None: config.dcb.Parity = NativeMethods.NOPARITY; break; case Parity.Odd: config.dcb.Parity = NativeMethods.ODDPARITY; break; case Parity.Even: config.dcb.Parity = NativeMethods.EVENPARITY; break; case Parity.Mark: config.dcb.Parity = NativeMethods.MARKPARITY; break; case Parity.Space: config.dcb.Parity = NativeMethods.SPACEPARITY; break; default: throw new IOException("An attempt to set the state of the underlying port failed (invalid parity)."); } switch (StopBits) { case StopBits.One: config.dcb.StopBits = NativeMethods.ONESTOPBIT; break; case StopBits.OnePointFive: config.dcb.StopBits = NativeMethods.ONE5STOPBITS; break; case StopBits.Two: config.dcb.StopBits = NativeMethods.TWOSTOPBITS; break; default: throw new IOException("An attempt to set the state of the underlying port failed (invalid stop bit count)."); } config.dcb.XonChar = 0x11; config.dcb.XoffChar = 0x13; config.dcb.ErrorChar = 0x3F; config.dcb.EofChar = 0; config.dcb.EvtChar = 0; config.dcb.wReserved1 = 0; config.dwProviderSubType = NativeMethods.PST_RS232; config.dwProviderOffset = 0; config.dwProviderSize = 0; config.wcProviderData = null; var resultConfigSet = NativeMethods.SetCommConfig(Handle, ref config, config.dwSize); if (resultConfigSet != true) { throw new IOException("An attempt to set the state of the underlying port failed.", new Win32Exception()); } var commTimeouts = new NativeMethods.COMMTIMEOUTS { ReadIntervalTimeout = NativeMethods.MAXDWORD, ReadTotalTimeoutMultiplier = (ReadTimeout == 0) ? 0 : -1, ReadTotalTimeoutConstant = (ReadTimeout != InfiniteTimeout) ? ReadTimeout : -2, WriteTotalTimeoutMultiplier = 0, WriteTotalTimeoutConstant = (ReadTimeout != InfiniteTimeout) ? WriteTimeout : 0 }; var resultTimeouts = NativeMethods.SetCommTimeouts(Handle, ref commTimeouts); if (resultTimeouts != true) { throw new IOException("An attempt to set the state of the underlying port failed.", new Win32Exception()); } } else { var portName = (PortName.StartsWith(@"\\?\", StringComparison.Ordinal) ? PortName.Remove(0, 4).Trim() : PortName.Trim()); FrameworkSerialPort = new SerialPort(portName, BaudRate, Parity, DataBits, StopBits) { ReadTimeout = ReadTimeout, WriteTimeout = WriteTimeout, DtrEnable = true, RtsEnable = true }; FrameworkSerialPort.Open(); } Purge(); }
//**************************************************************************** //メソッド名:ReadInputData(指定ポートのデータを取り込む) //引数:ポート名("P0"、"P1"・・・"P7") //戻り値:取り込んだデータ正常0、異常1 //**************************************************************************** public int ReadInputData(PortName pName) { switch (pName) { case PortName.P0: this.Port = EPX64R.EPX64R_PORT0; // PORT0 break; case PortName.P1: this.Port = EPX64R.EPX64R_PORT1; // PORT1 break; case PortName.P2: this.Port = EPX64R.EPX64R_PORT2; // PORT2 break; case PortName.P3: this.Port = EPX64R.EPX64R_PORT3; // PORT3 break; case PortName.P4: this.Port = EPX64R.EPX64R_PORT4; // PORT4 break; case PortName.P5: this.Port = EPX64R.EPX64R_PORT5; // PORT5 break; case PortName.P6: this.Port = EPX64R.EPX64R_PORT6; // PORT6 break; case PortName.P7: this.Port = EPX64R.EPX64R_PORT7; // PORT7 break; default: return(1); //ポート名間違えたら異常とする } // Input this.Status = EPX64R.EPX64R_InputPort(this.hDevice, this.Port, ref this.InputValue); if (Status != EPX64R.EPX64R_OK) { EPX64R.EPX64R_Close(hDevice); // Device Close //MessageBox.Show("EPX64R_InputPort() Error"); return(1); } switch (pName) { case PortName.P0: this.P0InputData = this.InputValue; break; case PortName.P1: this.P1InputData = this.InputValue; break; case PortName.P2: this.P2InputData = this.InputValue; break; case PortName.P3: this.P3InputData = this.InputValue; break; case PortName.P4: this.P4InputData = this.InputValue; break; case PortName.P5: this.P5InputData = this.InputValue; break; case PortName.P6: this.P6InputData = this.InputValue; break; case PortName.P7: this.P7InputData = this.InputValue; break; } return(0); }
/// <summary> /// Opens the serial port specified by <see cref="PortName" />. /// </summary> /// <exception cref="System.ObjectDisposedException"/> /// <exception cref="System.InvalidOperationException"> /// Port must first be set; /// or /// Serial Port currently open. /// </exception> /// <exception cref="System.IO.IOException">Wrong file type.</exception> /// <remarks> /// Opening the serial port does not set any settings (such as baud rate, etc.). On the windows implementation, /// it only sets the internal driver input and output queue. /// </remarks> public void Open() { if (m_IsDisposed) { throw new ObjectDisposedException("WinNativeSerial"); } if (PortName == null || PortName.Trim() == "") { throw new InvalidOperationException("Port must first be set"); } if (IsOpen) { throw new InvalidOperationException("Serial Port currently open"); } m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + PortName, NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE, NativeMethods.FileShare.FILE_SHARE_NONE, IntPtr.Zero, NativeMethods.CreationDisposition.OPEN_EXISTING, NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (m_ComPortHandle.IsInvalid) { WinIOError(); } NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle); bool validOverride = false; if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN) { foreach (string port in GetPortNames()) { #if NETSTANDARD15 if (port.Equals(PortName, StringComparison.OrdinalIgnoreCase)) { validOverride = true; break; } #else if (port.Equals(PortName, StringComparison.InvariantCultureIgnoreCase)) { validOverride = true; break; } #endif } if (!validOverride) { m_ComPortHandle.Dispose(); m_ComPortHandle = null; throw new IOException("Wrong file type: " + PortName); } } // Set the default parameters UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue); m_CommState = new CommState(m_ComPortHandle); m_CommProperties = new CommProperties(m_ComPortHandle); m_CommModemStatus = new CommModemStatus(m_ComPortHandle); m_CommOverlappedIo = new CommOverlappedIo(m_ComPortHandle); RegisterEvents(); }