Exemple #1
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            //byte[] bytes = _messageGenerator.GetMessage();
            //string byteString = BitConverter.ToString(bytes);

            SpyMessage spyMessage = new SpyMessage();
            Console.WriteLine("Size: " + Marshal.SizeOf(spyMessage));

            if (IsSerial)
            {
                string[] ports = SerialPort.GetPortNames();

                _serialStream = new SerialStream("COM16", 2400);
                _serialStream.DataReceived += new Action<byte[]>(callBack);
                _serialStream.Start();

            }
            else
            {
                _tcpListener = new TCPListener(7118, false, callBack);
                _tcpListener.Start();
            }
            Console.WriteLine("Listening...");

            Console.ReadLine();
        }
Exemple #2
0
 public bool Open(int channel)
 {
     CheckChannel(channel);
     if (Available(channel))
     {
         if (stream is null)
         {
             try
             {
                 stream = device.Open();
             }
             catch (IOException)
             {
                 throw new HardwareException(DeviceType.Generator, ErrorCode.CommunicationError, "Generator unavailable", "Connect the generator");
             }
             stream.BaudRate     = 57600;
             stream.ReadTimeout  = 500;
             stream.WriteTimeout = 500;
         }
         open[channel] = true;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #3
0
        private static void Main(string[] args)
        {
            var options = new PortOptions();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            SerialPort serialPort = new SerialPort(options.Com, options.BaudRate);

            if (!serialPort.IsOpen)
            {
                serialPort.Open();
            }

            var stream = new SerialStream(serialPort);

            stream.ReadTimeout = 5000;
            ModbusRtuSession session = new ModbusRtuSession(new ModbusProtocolImpl(stream));

            RequestFunc03 func03 = new RequestFunc03();

            func03.firstRegisterAddress = 0;
            func03.numberOfRegisters    = 4;

            var response = session.SendRequest <ResponseFunc03>(1, 3, func03);

            Console.Read();
        }
Exemple #4
0
        private void VirtualMachine_Stopped(object sender, EventArgs e)
        {
            vmRunning = false;
            OnUpdateControls();

            DebuggerWorker.CancelAsync();

            try
            {
                SerialStream.Close();
            }
            catch { }

            try
            {
                if (Gdb != null)
                {
                    Gdb.Dispose();
                }
            }
            finally
            {
                Gdb = null;
            }

            if (restartingVM)
            {
                return;
            }

            if (Bootstrap.Parameters.ContainsKey("start"))
            {
                Application.Exit();
            }
        }
Exemple #5
0
 private void SerialStream_WaitForConnection(IAsyncResult asyncResult)
 {
     try
     {
         SerialStream.EndWaitForConnection(asyncResult);
         SerialStream.BeginRead(buffer, 0, 1, SerialStream_Read, null);
     }
     catch { }
 }
 public HidSharpSerialDeviceImpl(IButtplugLogManager aLogManager, SerialStream aDevice)
     : base(aLogManager)
 {
     _device              = aDevice;
     _device.Closed      += OnClosed;
     _device.ReadTimeout  = 1000;
     _device.WriteTimeout = 1000;
     Address              = _device.Device.DevicePath;
 }
        public AddArduinoView()
        {
            InitializeComponent();

            ComboBox_ports.ItemsSource = SerialStream.GetPorts();

            if (ComboBox_ports.Items.Count > 0)
            {
                ComboBox_ports.SelectedIndex = ComboBox_ports.Items.Count - 1;
            }
        }
 protected SerialStreamIORequest(SerialStream parent, CancellationToken ct)
     : base(TaskCreationOptions.RunContinuationsAsynchronously)
 {
     _parent = parent;
     _cancellationTokenRegistration = ct.Register(s =>
     {
         var request = (SerialStreamIORequest)s;
         request.TrySetCanceled();
         request._parent.HasCancelledTasksToProcess = true;
     }, this);
 }
Exemple #9
0
        public void Open()
        {
            if (isOpen)
            {
                throw new InvalidOperationException("Serial Port - port already open!");
            }
            if (parity < Parity.None || parity > Parity.Space)
            {
                throw new ArgumentOutOfRangeException("parity", Resources.GetResourceString("ArgumentOutOfRange_Enum"));
            }
            if (dataBits < minDataBits || dataBits > maxDataBits)
            {
                throw new ArgumentOutOfRangeException("dataBits",
                                                      Resources.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", minDataBits, maxDataBits));
            }
            if (stopBits < StopBits.One || stopBits > StopBits.OnePointFive)
            {
                throw new ArgumentOutOfRangeException("stopBits", Resources.GetResourceString("ArgumentOutOfRange_Enum"));
            }
            if (baudRate <= 0)
            {
                throw new ArgumentOutOfRangeException("baudRate", Resources.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
            }
            if (portName == null)
            {
                throw new ArgumentNullException("resource", Resources.GetResourceString("ArgumentNull_String"));
            }
            if (handshake < Handshake.None || handshake > Handshake.RequestToSendXOnXOff)
            {
                throw new ArgumentOutOfRangeException("handshake", Resources.GetResourceString("ArgumentOutOfRange_Enum"));
            }
            if (readTimeout < 0 && readTimeout != SerialPort.InfiniteTimeout)
            {
                throw new ArgumentOutOfRangeException("readTimeout", Resources.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
            }
            if (writeTimeout <= 0 && writeTimeout != SerialPort.InfiniteTimeout)
            {
                throw new ArgumentOutOfRangeException("writeTimeout", Resources.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
            }
            if (portName.StartsWith("\\\\"))
            {
                throw new ArgumentException("resource", Resources.GetResourceString("Arg_SecurityException"));
            }

            internalSerialStream = new SerialStream(portName, baudRate, parity, dataBits, stopBits, readTimeout,
                                                    writeTimeout, handshake, dtrEnable, rtsEnable, discardNull, parityReplace);

            internalSerialStream.ErrorEvent      += new SerialEventHandler(CatchErrorEvents);
            internalSerialStream.PinChangedEvent += new SerialEventHandler(CatchPinChangedEvents);
            internalSerialStream.ReceivedEvent   += new SerialEventHandler(CatchReceivedEvents);

            isOpen = true;
        }
        public void Serialize(object value, SerialStream ss, bool rawValue = false)
#endif
        {
            if (rawValue)
            {
                ss.SerializeRaw(default(object));
            }
            else
            {
                ss.Serialize(default(object));
            }
        }
Exemple #11
0
 public void Close()
 {
     if (!isOpen)
     {
         throw new InvalidOperationException("Serial Port - port already closed!");
     }
     if (internalSerialStream != null)
     {
         internalSerialStream.Close();
         internalSerialStream = null;
     }
     isOpen = false;
 }
Exemple #12
0
 private void btnRestartConnection_Click(object sender, EventArgs e)
 {
     try
     {
         serialPort1.Open();
         CommStream             = new SerialStream(serialPort1);
         CommStream.ReadTimeout = 900;
         ShowPortConnected(true);
     }
     catch (Exception err)
     {
         MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public ExtronSwitcher(uint comport)
        {
            if (comport == 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            this.port = new SerialStream("COM" + comport.ToString());

            this.port.SetPortSettings(9600, SerialStream.FlowControl.None,
                                      SerialStream.Parity.None, 8,
                                      SerialStream.StopBits.One);
            this.port.SetTimeouts(0, 0, 500, 0, 500);

            this.RequestInputStatus();
        }
        private void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                this.port.Close();
                this.port = null;

                this.portstatus = null;
            }

            this.disposed = true;
        }
Exemple #15
0
        public async Task <bool> Open()
        {
            _stream = new SerialStream(_port);

            if (_stream.Open())
            {
                _stream.TelegramReceived += TelegramReceivedEventHandler;

                var readIdBase = await SendTelegram(new CommonCommandPacket(CommonCommands.CO_RD_IDBASE));

                if (readIdBase != null)
                {
                    _idBase = readIdBase.Data.Slice(1, 4);
                }


                return(true);
            }

            return(false);
        }
Exemple #16
0
 public override void Open()
 {
     NativeStream = NativeDevice.Open();
     Task.Run(() =>
     {
         while (IsOpen)
         {
             try
             {
                 int temp = NativeStream.ReadByte();
                 if (temp != -1)
                 {
                     ReceivedData.Enqueue((byte)temp);
                     DataReceived?.Invoke(this, new System.EventArgs());
                 }
             }
             catch
             {
             }
         }
     });
 }
Exemple #17
0
 private void onOffToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (serialPort1.IsOpen)
     {
         serialPort1.Close();
         ShowPortConnected(false);
     }
     else
     {
         try
         {
             serialPort1.Open();
             CommStream             = new SerialStream(serialPort1);
             CommStream.ReadTimeout = 900;
             ShowPortConnected(true);
         }
         catch (Exception err)
         {
             MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemple #18
0
        private void SerialStream_Read(IAsyncResult asyncResult)
        {
            int count = SerialStream.EndRead(asyncResult);

            if (count != 1)
            {
                try
                {
                    SerialStream.Close();
                    Gdb.Dispose();
                }
                catch { }

                SerialStream = new NamedPipeServerStream("System", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                SerialStream.BeginWaitForConnection(SerialStream_WaitForConnection, null);

                return;
            }

            SerialStream_ReadByte(buffer[0]);

            SerialStream.BeginRead(buffer, 0, 1, SerialStream_Read, null);
        }
        public void RunEmulator()
        {
            ExecutionMutex.WaitOne();
            bool success = true;
            DoEmulator = true;
            DateTime lastTime = DateTime.Now;
            EndianConverter32Bit e32 = new EndianConverter32Bit(EndianConverter.BigEndian32Bit);

            try
            {
                Services.OpenLogFile(LogFileName);

                LoadConverse();
                if (UsePortReader)
                    StartPortReader();
                else
                {
                    Stream = new SerialStream(GenThreadManager, Services, PortName, BaudRate, Parity, DataBits, StopBits, Handshake, 20000);
                    Stream.Open();
                }

                if (EmulatorType == DeviceEmulator.EmulatorType.CMS)
                {
                    // bool started = false;
                    Inverter inv = new Inverter(100.0, 10.0, 1.0, 10.0, 10.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery1"))
                        {
                            ByteVar varControl = (ByteVar)Converse.GetSessionVariable("Control");
                            ByteVar varFunction = (ByteVar)Converse.GetSessionVariable("Function");
                            ByteVar varSize = (ByteVar)Converse.GetSessionVariable("Size");
                            ByteVar varData = (ByteVar)Converse.GetSessionVariable("Data");
                            varData.Resize(varSize.GetByte());
                            Converse.DoConversation("ReadQuery2");

                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 4) // Initialise
                                continue;
                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 0) // Get Serial
                            {
                                Converse.DoConversation("SendSerialNo");
                                continue;
                            }
                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 1) // Get Serial
                            {
                                Converse.DoConversation("AckAddress");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 3) // Get details
                            {
                                Converse.DoConversation("SendDetails");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 0) // Get format
                            {
                                Converse.DoConversation("SendFormat");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 2) // Eun Device
                            {
                                inv.UpdateEnergy(Services);

                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Temperature", null);
                                var.SetBytes(250, 0);

                                var = (ByteVar)Converse.GetSessionVariable("EnergyToday", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.EToday), 0);

                                var = (ByteVar)Converse.GetSessionVariable("VoltsPV", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);

                                var = (ByteVar)Converse.GetSessionVariable("CurrentAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("VoltsAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("Frequency", null);
                                var.SetBytes(5000, 0);

                                var = (ByteVar)Converse.GetSessionVariable("PowerAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.PowerAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("ImpedanceAC", null);
                                var.SetBytes(0, 0);

                                var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                byte[] intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.ETotal));
                                byte[] ext = e32.InternalToExternal(intern);
                                var.SetBytes(ref ext, 0, 4);

                                var = (ByteVar)Converse.GetSessionVariable("Hours", null);
                                intern = System.BitConverter.GetBytes(2500);
                                ext = e32.InternalToExternal(intern);
                                var.SetBytes(ref ext, 0, 4);

                                var = (ByteVar)Converse.GetSessionVariable("Mode", null);
                                var.SetBytes(0, 0);

                                var = (ByteVar)Converse.GetSessionVariable("ErrorMode", null);
                                var.SetBytes(0, 0);

                                Converse.DoConversation("RunDevice");
                                continue;
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.GenericReader)
                {
                    while (DoEmulator)
                    {

                        Converse.DoConversation("Read");
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.Fronius)
                {
                    // bool started = false;

                    Inverter inv = new Inverter(1.0, 1.0, 1.0, 1.0, 1.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery"))
                        {
                            byte[] size = Converse.GetSessionVariable("Size", null).GetBytes();
                            byte[] option = Converse.GetSessionVariable("Option", null).GetBytes();
                            byte[] number = Converse.GetSessionVariable("Number", null).GetBytes();
                            byte[] cmd = Converse.GetSessionVariable("Command", null).GetBytes();
                            if (cmd[0] == 1)
                            {
                                Converse.DoConversation("Identity");
                            }
                            else if (cmd[0] == 2)
                            {
                                Converse.DoConversation("Model");
                            }
                            else if (cmd[0] == 16)
                            {
                                inv.UpdateEnergy(Services);
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("PowerAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.PowerAC), 0);
                                Converse.DoConversation("Power");
                            }
                            else if (cmd[0] == 17)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.ETotal), 0);
                                Converse.DoConversation("EnergyTotal");
                            }
                            else if (cmd[0] == 18)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("EnergyToday", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.EToday), 0);
                                Converse.DoConversation("EnergyToday");
                            }
                            else if (cmd[0] == 20)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("CurrentAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);
                                Converse.DoConversation("CurrentAC");
                            }
                            else if (cmd[0] == 21)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("VoltsAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);
                                Converse.DoConversation("VoltsAC");
                            }
                            else if (cmd[0] == 22)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Frequency", null);
                                var.SetBytes(50, 0);
                                Converse.DoConversation("Frequency");
                            }
                            else if (cmd[0] == 23)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("CurrentPV", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.CurrentPV), 0);
                                Converse.DoConversation("CurrentPV");
                            }
                            else if (cmd[0] == 24)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("VoltsPV", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);
                                Converse.DoConversation("VoltsPV");
                            }
                            else if (cmd[0] == 42)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Hours", null);
                                var.SetBytes(2000, 0);
                                Converse.DoConversation("TimeTotal");
                            }
                            else if (cmd[0] == 224)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Temperature", null);
                                var.SetBytes(55, 0);
                                Converse.DoConversation("Temperature");
                            }
                            else if (cmd[0] == 15)
                            {
                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Mode", null);
                                var.SetBytes(0, 0);
                                Converse.DoConversation("Status");
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.ModbusGrowatt)
                {
                    // bool started = false;

                    Inverter inv = new Inverter(10.0, 10.0, 10.0, 10.0, 10.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery"))
                        {
                            byte[] cmd = Converse.GetSessionVariable("Command", null).GetBytes();
                            byte[] start = Converse.GetSessionVariable("StartRegister", null).GetBytes();
                            if (cmd[0] == 3)
                            {
                                if (start[1] == 23)  // Big Endian input stream
                                {
                                    Converse.DoConversation("SerialNo");
                                }
                            }
                            else if (cmd[0] == 4)
                            {
                                if (start[1] == 0)
                                {
                                    inv.UpdateEnergy(Services);
                                    ByteVar var = (ByteVar)Converse.GetSessionVariable("EnergyToday", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.EToday), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                    byte[] intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.ETotal));
                                    byte[] ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerAC", null);
                                    intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.PowerAC));
                                    ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("Freq", null);
                                    var.SetBytes(5000, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltageAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerAC1", null);
                                    intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.PowerAC));
                                    ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerPV", null);
                                    intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.PowerPV));
                                    ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerPV1", null);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltagePV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentPV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentPV), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("DUMMY1", null);
                                    var.Initialise();
                                    var = (ByteVar)Converse.GetSessionVariable("DUMMY2", null);
                                    var.Initialise();
                                    var = (ByteVar)Converse.GetSessionVariable("DUMMY3", null);
                                    var.Initialise();
                                    Converse.DoConversation("Reading");
                                }
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.ModbusSunnyroo)
                {
                    // bool started = false;

                    Inverter inv = new Inverter(1.0, 1.0, 0.1, 1.0, 10.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery"))
                        {
                            byte[] cmd = Converse.GetSessionVariable("Command", null).GetBytes();
                            byte[] start = Converse.GetSessionVariable("StartRegister", null).GetBytes();
                            if (cmd[0] == 3)
                            {
                                if (start[1] == 177)
                                {
                                    Converse.DoConversation("Identity");
                                }
                                else if (start[1] == 32)
                                {
                                    inv.UpdateEnergy(Services);
                                    ByteVar var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                    byte[] intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.ETotal));
                                    byte[] ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.PowerAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("Freq", null);
                                    var.SetBytes(5000, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltageAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);

                                    var = (ByteVar)Converse.GetSessionVariable("VoltagePV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentPV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentPV), 0);

                                    Converse.DoConversation("Reading");
                                }
                                else if (start[1] == 0)
                                {
                                    Converse.DoConversation("Status");
                                }
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.ModbusKLNE)
                {
                    // bool started = false;
                    Inverter inv = new Inverter(10.0, 10.0, 10.0, 10.0, 10.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery"))
                        {
                            byte[] cmd = Converse.GetSessionVariable("Command").GetBytes();
                            byte[] start = Converse.GetSessionVariable("StartRegister").GetBytes();

                            if (cmd[0] == 4)
                            {
                                if (start[1] == 0)
                                {
                                    Converse.DoConversation("Identity");
                                }
                                if (start[1] == 10)
                                {
                                    inv.UpdateEnergy(Services);
                                    //$VoltsPV1(BYTE[2]) $VoltsPV2(BYTE[2]) $CurrentPV1(BYTE[2]) $CurrentPV2(BYTE[2]) $VoltsAC1(BYTE[2]) $VoltsAC2(BYTE[2]) $VoltsAC3(BYTE[2])
                                    //$CurrentAC1(BYTE[2]) $CurrentAC2(BYTE[2]) $CurrentAC3(BYTE[2]) $Frequency(BYTE[2]) $PowerAC(BYTE[4]) $EnergyToday(BYTE[2]) $EnergyTotal(BYTE[4])
                                    //00 00 $TimeTotal(BYTE[4]) 00 00 $Temperature(BYTE[2]) 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 $ErrorCode(BYTE[2])
                                    ByteVar var = (ByteVar)Converse.GetSessionVariable("VoltsPV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltsPV2", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentPV1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentPV), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentPV2", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltsAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltsAC2", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("VoltsAC3", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentAC1", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentAC2", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("CurrentAC3", null);
                                    var.SetBytes(0, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("Frequency", null);
                                    var.SetBytes(500, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("PowerAC", null);
                                    byte[] intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.PowerAC));
                                    byte[] ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("EnergyToday", null);
                                    var.SetBytes(System.Convert.ToUInt16(inv.EToday), 0);
                                    var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                    intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.ETotal));
                                    ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("TimeTotal", null);
                                    intern = System.BitConverter.GetBytes(25000);
                                    ext = e32.InternalToExternal(intern);
                                    var.SetBytes(ref ext, 0, 4);
                                    var = (ByteVar)Converse.GetSessionVariable("Temperature", null);
                                    var.SetBytes(250, 0);
                                    var = (ByteVar)Converse.GetSessionVariable("ErrorCode", null);
                                    var.SetBytes(0, 0);

                                    Converse.DoConversation("Reading");
                                }
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.KLNE)
                {
                    // bool started = false;
                    Inverter inv = new Inverter(10.0, 10.0, 1.0, 10.0, 10.0);

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadQuery1"))
                        {
                            ByteVar varControl = (ByteVar)Converse.GetSessionVariable("Control");
                            ByteVar varFunction = (ByteVar)Converse.GetSessionVariable("Function");
                            ByteVar varSize = (ByteVar)Converse.GetSessionVariable("Size");
                            ByteVar varData = (ByteVar)Converse.GetSessionVariable("Data");
                            varData.Resize(varSize.GetByte());
                            Converse.DoConversation("ReadQuery2");

                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 3) // Initialise
                                continue;
                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 0) // Get Serial
                            {
                                Converse.DoConversation("SendSerialNo");
                                continue;
                            }
                            if (varControl.GetByte() == 0 && varFunction.GetByte() == 1) // Get Serial
                            {
                                Converse.DoConversation("AckAddress");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 3) // Get details
                            {
                                Converse.DoConversation("SendDetails");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 0) // Get format
                            {
                                Converse.DoConversation("SendFormat");
                                continue;
                            }
                            if (varControl.GetByte() == 1 && varFunction.GetByte() == 2) // Get data
                            {
                                inv.UpdateEnergy(Services);

                                ByteVar var = (ByteVar)Converse.GetSessionVariable("Temperature", null);
                                var.SetBytes(250, 0);

                                var = (ByteVar)Converse.GetSessionVariable("EnergyToday", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.EToday), 0);

                                var = (ByteVar)Converse.GetSessionVariable("VoltsPV", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltagePV), 0);

                                var = (ByteVar)Converse.GetSessionVariable("CurrentAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.CurrentAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("VoltsAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.VoltageAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("Frequency", null);
                                var.SetBytes(5000, 0);

                                var = (ByteVar)Converse.GetSessionVariable("PowerAC", null);
                                var.SetBytes(System.Convert.ToUInt16(inv.PowerAC), 0);

                                var = (ByteVar)Converse.GetSessionVariable("EnergyTotal", null);
                                byte[] intern = System.BitConverter.GetBytes(System.Convert.ToUInt32(inv.ETotal));
                                byte[] ext = e32.InternalToExternal(intern);
                                var.SetBytes(ref ext, 0, 4);

                                var = (ByteVar)Converse.GetSessionVariable("Hours", null);
                                intern = System.BitConverter.GetBytes(2500);
                                ext = e32.InternalToExternal(intern);
                                var.SetBytes(ref ext, 0, 4);

                                var = (ByteVar)Converse.GetSessionVariable("Mode", null);
                                var.SetBytes(0, 0);

                                Converse.DoConversation("SendData");
                                continue;
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.ModbusXantrex)
                {
                    // bool started = false;
                    Inverter inv = new Inverter(10.0, 10.0, 10.0, 10.0, 10.0);
                    int energyId = 0;

                    while (DoEmulator)
                    {
                        if (Converse.DoConversation("ReadCommand"))
                        {
                            byte[] cmd = Converse.GetSessionVariable("Command").GetBytes();

                            if (cmd[0] == 3)
                            {
                                if (Converse.DoConversation("RegisterRequest"))
                                {
                                    byte[] start = Converse.GetSessionVariable("StartRegister").GetBytes();
                                    String cmdStr = SystemServices.BytesToHex(ref start);
                                    if (cmdStr == "0x0000")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("Model");
                                        var.SetBytes("Fireball XL5", (byte)0);
                                        var = (ByteVar)Converse.GetSessionVariable("SerialNo");
                                        var.SetBytes("XL5-007", (byte)0);
                                        Converse.DoConversation("Identity");
                                    }
                                    else if (cmdStr == "0x0082")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("ErrorValue");
                                        byte[] val = SystemServices.HexToBytes("0x0102030405060708");
                                        var.SetBytes(ref val, 0, 8);
                                        var = (ByteVar)Converse.GetSessionVariable("ErrorDesc");
                                        var.SetBytes("The Big Bad Error - BOO", (byte)0);
                                        Converse.DoConversation("ErrorDetail");
                                    }
                                    else if (cmdStr == "0x00CF")
                                    {
                                        inv.UpdateEnergy(Services);
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("Status");
                                        var.SetBytes(System.Convert.ToUInt16(0), 0);
                                        Converse.DoConversation("Status");
                                    }
                                    else if (cmdStr == "0x0201")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("VoltsPV1");
                                        var.SetBytes(System.Convert.ToUInt32(inv.VoltagePV), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("CurrentPV1");
                                        var.SetBytes(System.Convert.ToUInt32(inv.CurrentPV), 0);
                                        Converse.DoConversation("InverterDC");
                                    }
                                    else if (cmdStr == "0x0701")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("VoltsAC1");
                                        var.SetBytes(System.Convert.ToUInt32(inv.VoltageAC), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("CurrentAC1");
                                        var.SetBytes(System.Convert.ToUInt32(inv.CurrentAC), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("Frequency");
                                        var.SetBytes(500, 0);
                                        var = (ByteVar)Converse.GetSessionVariable("PowerAC");
                                        var.SetBytes(System.Convert.ToUInt32(inv.PowerAC), 0);
                                        Converse.DoConversation("InverterAC");
                                    }
                                    else if (cmdStr == "0x0803")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("HistoryId");
                                        var.SetBytes(System.Convert.ToUInt16(0), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("Energy");
                                        var.SetBytes(System.Convert.ToUInt32(energyId == 4 ? inv.EToday : inv.ETotal), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("PeakPower");
                                        var.SetBytes(System.Convert.ToUInt32(inv.PowerAC), 0);
                                        var = (ByteVar)Converse.GetSessionVariable("HarvestTime");
                                        var.SetBytes(System.Convert.ToUInt32(10.0), 0);
                                        Converse.DoConversation("EnergyHistory");
                                    }
                                    else if (cmdStr == "0x0900")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("Temperature");
                                        var.SetBytes(System.Convert.ToUInt16(250), 0);
                                        Converse.DoConversation("Temperature");
                                    }
                                    else if (cmdStr == "0x0080")
                                    {
                                        ByteVar var = (ByteVar)Converse.GetSessionVariable("ErrorCount");
                                        var.SetBytes(System.Convert.ToUInt16(1), 0);
                                        Converse.DoConversation("ErrorCount");
                                    }
                                }
                            }
                            else if (cmd[0] == 16) // 0x10
                            {
                                if (Converse.DoConversation("SetRegisters_1"))
                                {
                                    // retrieve the datasize to follow and resize the receive buffer to suit
                                    ByteVar sizeVar = (ByteVar)Converse.GetSessionVariable("DataSize");
                                    ByteVar dataVar = (ByteVar)Converse.GetSessionVariable("Data");
                                    dataVar.Resize(sizeVar.GetByte());

                                    // retrieve the rest of the message
                                    if (Converse.DoConversation("SetRegisters_2"))
                                    {
                                        byte[] start = Converse.GetSessionVariable("StartRegister").GetBytes();
                                        String cmdStr = SystemServices.BytesToHex(ref start);
                                        if (cmdStr == "0x0800") // Energy History Initiate
                                        {
                                            energyId = dataVar.GetUInt16();
                                            Converse.DoConversation("SetRegistersConfirm");
                                        }
                                        if (cmdStr == "0x0081") // Initialise Error Index
                                        {
                                            Converse.DoConversation("SetRegistersConfirm");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.XantrexASCII)
                {
                    // bool started = false;
                    Inverter inv = new Inverter(10.0, 10.0, 10.0, 10.0, 10.0);
                    int errCount = 0;

                    while (DoEmulator)
                    {
                        ByteVar response = ((ByteVar)Converse.GetSessionVariable("Response"));
                        if (Converse.DoConversation("ReadRequest"))
                        {
                            String cmd = ((DynamicByteVar)Converse.GetSessionVariable("Request")).ToString();

                            if (cmd == "IDN?")
                            {
                                String val = "M:Xantrex 1.0 X:1000 S:12345612";
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "POUT?")
                            {
                                String val = inv.PowerAC.ToString();
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "MEASTEMP?")
                            {
                                String val = "C:27.4 F:78.5";
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "MEASIN?")
                            {
                                String val = "V:" + inv.VoltagePV + " I:"
                                    + inv.CurrentPV + " P:" + inv.PowerPV;
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "MEASOUT?")
                            {
                                String val = "V:" + inv.VoltageAC + " I:"
                                    + inv.CurrentAC + " P:" + inv.PowerAC + " F:50.1";
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "KWHTODAY?")
                            {
                                String val = inv.EToday.ToString("F3");
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                            }
                            else if (cmd == "KWHLIFE?")
                            {
                                String val = inv.ETotal.ToString("F3");
                                response.Resize((UInt16)val.Length);
                                response.SetBytes(val);
                                Converse.DoConversation("SendResponse");
                                inv.UpdateEnergy(Services);
                            }
                            else if (cmd == "FAULTACTIVE?")
                            {
                                if (errCount < 5)
                                {
                                    String val = "0x220D22";
                                    byte[] bytes = SystemServices.HexToBytes(val);
                                    response.Resize((UInt16)bytes.Length);
                                    response.SetBytes(ref bytes, 0, bytes.Length);
                                    Converse.DoConversation("SendResponse");
                                    errCount++;
                                }
                                else
                                {
                                    String val = "0x220D3030312C204552520D22";  // "cr001, ERRcr"cr
                                    byte[] bytes = SystemServices.HexToBytes(val);
                                    response.Resize((UInt16)bytes.Length);
                                    response.SetBytes(ref bytes, 0, bytes.Length);
                                    Converse.DoConversation("SendResponse");
                                    if (errCount == 5)  // send this twice
                                        errCount++;
                                    else
                                        errCount = 0;
                                }
                            }
                        }
                    }
                }
                else if (EmulatorType == DeviceEmulator.EmulatorType.CurrentCostEnviR)
                {
                    XElement time = liveElement.Element("time");
                    XElement sensor = liveElement.Element("sensor");
                    XElement tmpr = liveElement.Element("tmpr");
                    XElement ch = liveElement.Element("ch1");
                    XElement watts1 = ch.Element("watts");
                    ch = liveElement.Element("ch2");
                    XElement watts2 = ch.Element("watts");
                    ch = liveElement.Element("ch3");
                    XElement watts3 = ch.Element("watts");
                    do
                    {
                        time.Value = DateTime.Now.ToString("HH:mm:ss");
                        sensor.Value = "0";
                        tmpr.Value = Math.Round(Tmpr, 1).ToString();
                        watts1.Value = Watts1_0.ToString();
                        watts2.Value = Watts2_0.ToString();
                        watts3.Value = Watts3_0.ToString();
                        String xmlText = liveElement.ToString();
                        byte[] bytes = SystemServices.StringToBytes(xmlText);
                        success = Stream.Write(bytes, 0, bytes.Length);

                        sensor.Value = "1";
                        watts1.Value = Watts1_1.ToString();
                        watts2.Value = Watts2_1.ToString();
                        watts3.Value = Watts3_1.ToString();

                        xmlText = liveElement.ToString();
                        bytes = SystemServices.StringToBytes(xmlText);
                        success = Stream.Write(bytes, 0, bytes.Length);

                        if (success)
                        {
                            Watts1_0 += (int)(Watts1_0 * 0.01);
                            Watts2_0 += (int)(Watts1_0 * 0.02);
                            Watts3_0 += (int)(Watts1_0 * 0.015);
                            Watts1_1 += (int)(Watts1_1 * 0.015);
                            Watts2_1 += (int)(Watts1_1 * 0.025);
                            Watts3_1 += (int)(Watts1_1 * 0.01);
                            Tmpr *= 1.01F;

                            lastTime = lastTime.AddSeconds(6.0);
                            DateTime curTime = DateTime.Now;
                            if (lastTime > curTime)
                                Thread.Sleep(lastTime - curTime);
                            else
                                lastTime = DateTime.Now;
                        }
                    }
                    while (success && DoEmulator);
                }

                if (UsePortReader)
                    StopPortReader();
                else
                    Stream.Close();

                Services.CloseLogFile();
            }
            catch (Exception e)
            {
                Services.LogMessage("RunEmulator", "Exception: " + e.Message, LogEntryType.ErrorMessage);
            }
            finally
            {
                ExecutionMutex.ReleaseMutex();
            }
        }
        private void butSendHist_Click(object sender, RoutedEventArgs e)
        {
            ExecutionMutex.WaitOne();
            Services.OpenLogFile(LogFileName);
            Stream = new SerialStream(GenThreadManager, Services, PortName, BaudRate, Parity, DataBits, StopBits, Handshake, 20000);
            Stream.Open();

            SendOneHistory();

            Stream.Close();
            Services.CloseLogFile();
            ExecutionMutex.ReleaseMutex();
        }
        public void StopPortReader()
        {
            if (ReaderStarted)
            {
                Stream.Close();
                Converse.SetDeviceStream(null);
                Stream = null;

                ReaderStarted = false;
            }
        }
Exemple #22
0
        public Form1()
        {
            InitializeComponent();

            ReceivedData = new byte[21];

            autoRefresh = false;

            measurementStacks = new Stack <MeasurementModel> [24];

            grpAll = new List <GroupBox>();
            txtAll = new List <TextBox>();

            groupBoxes      = new GroupBox[] { groupBox1, groupBox2, groupBox3, groupBox4, groupBox5, groupBox6, groupBox7, groupBox8, groupBox9, groupBox10, groupBox11, groupBox12, groupBox13, groupBox14, groupBox15, groupBox16, groupBox17, groupBox18, groupBox19, groupBox20, groupBox21, groupBox22, groupBox23, groupBox24 };
            tempDisplays    = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16, textBox17, textBox18, textBox19, textBox20, textBox21, textBox22, textBox23, textBox24 };
            numMins         = new NumericUpDown[] { numMin1, numMin2, numMin3, numMin4, numMin5, numMin6, numMin7, numMin8, numMin9, numMin10, numMin11, numMin12, numMin13, numMin14, numMin15, numMin16, numMin17, numMin18, numMin19, numMin20, numMin21, numMin22, numMin23, numMin24 };
            numMaxs         = new NumericUpDown[] { numMax1, numMax2, numMax3, numMax4, numMax5, numMax6, numMax7, numMax8, numMax9, numMax10, numMax11, numMax12, numMax13, numMax14, numMax15, numMax16, numMax17, numMax18, numMax19, numMax20, numMax21, numMax22, numMax23, numMax24 };
            numMarkers      = new NumericUpDown[] { numMarker1, numMarker2, numMarker3, numMarker4, numMarker5, numMarker6, numMarker7, numMarker8, numMarker9, numMarker10, numMarker11, numMarker12, numMarker13, numMarker14, numMarker15, numMarker16, numMarker17, numMarker18, numMarker19, numMarker20, numMarker21, numMarker22, numMarker23, numMarker24 };
            dateTimePickers = new DateTimePicker[] { dateTimePicker1, dateTimePicker2, dateTimePicker3, dateTimePicker4, dateTimePicker5, dateTimePicker6, dateTimePicker7, dateTimePicker8, dateTimePicker9, dateTimePicker10, dateTimePicker11, dateTimePicker12, dateTimePicker13, dateTimePicker14, dateTimePicker15, dateTimePicker16, dateTimePicker17, dateTimePicker18, dateTimePicker19, dateTimePicker20, dateTimePicker21, dateTimePicker22, dateTimePicker23, dateTimePicker24 };
            numStartHours   = new NumericUpDown[] { numStartHour1, numStartHour2, numStartHour3, numStartHour4, numStartHour5, numStartHour6, numStartHour7, numStartHour8, numStartHour9, numStartHour10, numStartHour11, numStartHour12, numStartHour13, numStartHour14, numStartHour15, numStartHour16, numStartHour17, numStartHour18, numStartHour19, numStartHour20, numStartHour21, numStartHour22, numStartHour23, numStartHour24 };
            numHourCounts   = new NumericUpDown[] { numHourCount1, numHourCount2, numHourCount3, numHourCount4, numHourCount5, numHourCount6, numHourCount7, numHourCount8, numHourCount9, numHourCount10, numHourCount11, numHourCount12, numHourCount13, numHourCount14, numHourCount15, numHourCount16, numHourCount17, numHourCount18, numHourCount19, numHourCount20, numHourCount21, numHourCount22, numHourCount23, numHourCount24 };
            lblGraphs       = new Label[] { lblGraph1, lblGraph2, lblGraph3 };
            btnShowGraphics = new Button[] { btnShowGraphic1, btnShowGraphic2, btnShowGraphic3 };

            // Font
            PrivateFontCollection pfc = new PrivateFontCollection();

            pfc.AddFontFile(@".\digital-7.ttf");
            fontFamily = new FontFamily("digital-7", pfc);
            font       = new Font(fontFamily, 36);
            for (int i = 0; i < tempDisplays.Length; i++)
            {
                tempDisplays[i].Font = font;
            }

            DisplayData();

            // Open port at startup
            try
            {
                PortSettingsModel portSettingsModel = SqliteDataAccess.LoadPortSettings();
                if (portSettingsModel != null)
                {
                    serialPort1.PortName = portSettingsModel.Port;
                    serialPort1.BaudRate = portSettingsModel.BaudRate;
                    serialPort1.DataBits = portSettingsModel.DataBits;
                    serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), portSettingsModel.StopBits); // StopBits.One
                    serialPort1.Parity   = (Parity)Enum.Parse(typeof(Parity), portSettingsModel.ParityBits);   // Parity.None

                    serialPort1.Open();
                    CommStream             = new SerialStream(serialPort1);
                    CommStream.ReadTimeout = 900;
                }
            }
            catch { }

            /*
             * catch (Exception err)
             * {
             *  MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             * }
             */
            ShowPortConnected(serialPort1.IsOpen); // If port is open, show port connected; else show port disconnected.
        }
 public SerialStreamWriteRequest(SerialStream parent, CancellationToken ct, ReadOnlyMemory <byte> buffer)
     : base(parent, ct)
 {
     Buffer = buffer;
 }
        public object Deserialize(SerialStream ss, Type type, bool rawValue = false)
#endif
        => rawValue?ss.DeserializeRawObject(type) : ss.DeserializeObject(type);
 public TObject Deserialize <TObject>(SerialStream serializer, bool rawValue = false)
 => rawValue?serializer.DeserializeRawObject <TObject>() : serializer.DeserializeObject <TObject>();
Exemple #26
0
        private static void HidSharpMethod()
        {
            Console.WriteLine("HIDSharp looking for a USB Serial devices...");

            List <SerialDevice> devices = DeviceList.Local.GetSerialDevices().ToList();

            if (!devices.Any())
            {
                Console.WriteLine("No Devices Found");
                return;
            }

            foreach (SerialDevice device in devices)
            {
                Console.WriteLine($"Found {device}");

                if (device.DevicePath.Contains("GBA ST2"))
                {
                    Console.WriteLine($"Found Match! { device.GetFriendlyName()}");
                    if (billAcceptor == null)
                    {
                        billAcceptor = device;
                        break;
                    }
                }
            }

            if (billAcceptor == null)
            {
                Console.WriteLine("Bill Acceptor not found!");
                return;
            }

            StringBuilder builder;
            SerialStream  stream = billAcceptor.Open();

            using (stream)
            {
                while (!CancelationToken)
                {
                    byte[] buffer = new byte[8];
                    int    count  = 0;

                    try
                    {
                        count = stream.Read(buffer, 0, buffer.Length);
                    }
                    catch (TimeoutException e)
                    {
                        Console.WriteLine("Timeout - new session started");
                        continue;
                    }

                    if (count > 0)
                    {
                        string converted = Convert.ToBase64String(buffer);
                        Console.WriteLine($"Evaluating: {converted}");

                        switch (converted)
                        {
                        case "B/lPAj0BAZA=":
                        case "B/lPAj0EA5U=":
                        case "B/lPAj0EBJY=":
                        case "B/lPAj0BAI8=":
                            Console.WriteLine("10 kn entered");
                            break;

                        default:
                            ReactToUnknownBill();
                            break;
                        }

                        count = 0;
                    }
                }
            }

            Console.WriteLine("Closing session");
        }
 public void Open(FileAccess access, FileShare sharing)
 {
     _BaseStream = new SerialStream(_Port, _BaudRate, access, sharing);
 }
 public void Close()
 {
     if (_BaseStream != null)
     {
         _BaseStream.Close();
         _BaseStream = null;
     }
 }
Exemple #29
0
 public override void Close()
 {
     NativeStream.Close();
     NativeStream = null;
 }
 public void Serialize(object?value, SerialStream ss, bool rawValue = false)
Exemple #31
0
 static public bool isSerialTimeOut()
 {
     return(SerialStream.isTimingOut());
 }
        public void Grouping()
        {
            var products = new List <Product>
            {
                new Product {
                    Name = "PC", Price = 450.00f, Category = ProductCategory.Computers
                },
                new Product {
                    Name = "Monitor", Price = 180.99f, Category = ProductCategory.Computers
                },
                new Product {
                    Name = "Printer", Price = 180.99f, Category = ProductCategory.Computers
                },
                new Product {
                    Name = "Car", Price = 12749.00f, Category = ProductCategory.Vehicles
                },
            };

            var productsGroupedByCategory = products.GroupBy(p => p.Category);

            var productsGroupedByCategoryThenByPrice = from product in products
                                                       group product by product.Category into categoryGroup
                                                       from categoryProduct in
                                                       from product in categoryGroup
                                                       group product by product.Price
                                                       group categoryProduct by categoryGroup.Key;

            var ss = new SerialStream();

            ss.Serialize(productsGroupedByCategory.First());
            ss.Serialize(productsGroupedByCategory);
            ss.Serialize(productsGroupedByCategoryThenByPrice);

            var bytes = ss.ToByteArray();

            ss = new SerialStream(bytes);

            var deserializedProductsGroupedByFirstCategory = ss.DeserializeIGrouping <ProductCategory, Product>();

            TestIGrouping(productsGroupedByCategory.First(), deserializedProductsGroupedByFirstCategory);

            var deserializedProductsGroupedByCategory = ss.DeserializeIEnumerable <IGrouping <ProductCategory, Product> >();

            TestIEnumerableIGrouping(productsGroupedByCategory, deserializedProductsGroupedByCategory);

            var deserializedProductsGroupedByCategoryThenByPrice = ss.DeserializeIEnumerable <IGrouping <ProductCategory, IGrouping <float, Product> > >();

            TestIEnumerableIGroupingIGrouping(productsGroupedByCategoryThenByPrice, deserializedProductsGroupedByCategoryThenByPrice);

            void TestIEnumerableIGroupingIGrouping <TFirstKey, TSecondKey, TElement>(IEnumerable <IGrouping <TFirstKey, IGrouping <TSecondKey, TElement> > > first, IEnumerable <IGrouping <TFirstKey, IGrouping <TSecondKey, TElement> > > second)
            {
                TestIEnumerableIGrouping(first, second);

                for (var i = 0; i < first.Count(); i++)
                {
                    TestIEnumerableIGrouping(first.ElementAt(i), second.ElementAt(i));
                }
            }

            void TestIEnumerableIGrouping <TKey, TElement>(IEnumerable <IGrouping <TKey, TElement> > first, IEnumerable <IGrouping <TKey, TElement> > second)
            {
                var firstCount = first.Count();

                Assert.AreEqual(firstCount, second.Count());

                for (var i = 0; i < firstCount; i++)
                {
                    var firstElementAti  = first.ElementAt(i);
                    var secondElementAti = second.ElementAt(i);

                    Assert.AreEqual(firstElementAti.Key, secondElementAti.Key);

                    if (typeof(TElement).Name != typeof(IGrouping <,>).Name)
                    {
                        TestIGrouping(firstElementAti, secondElementAti);
                    }
                }
            }

            void TestIGrouping <TKey, TElement>(IGrouping <TKey, TElement> first, IGrouping <TKey, TElement> second)
            {
                var firstCount = first.Count();

                Assert.AreEqual(first.Key, second.Key);
                Assert.AreEqual(firstCount, second.Count());

                for (var i = 0; i < firstCount; i++)
                {
                    Assert.IsTrue(first.ElementAt(i).Equals(second.ElementAt(i)));
                }
            }
        }
 public object?Deserialize(SerialStream ss, Type type, bool rawValue = false)
Exemple #34
0
 // Update is called once per frame
 void Update()
 {
     updateInputs(SerialStream.getLine());
     printDebug(getRotations().ToString());
 }
Exemple #35
0
 void CloseAll()
 {
     stream.Close();
     stream = null;
 }
Exemple #36
0
 /// <summary>Creates a new Virtual Serial port driver instance</summary>
 /// <param name="DeviceID">Port Number of the virtual serial port in the HAL</param>
 public VPortDriver(int DeviceID)
 {
     SerialPort.Serial portnum = (SerialPort.Serial)(DeviceID);
     this.Port = new SerialStream(new ComPort(portnum, 0, false), Timeout.Infinite, Timeout.Infinite);
 }
            private int m_bytesInRead;             // The number of bytes currently in the read buffer

            /// <summary>
            /// Creates a new SDIOController for a Promi SD Bluetooth chip attached
            /// to the specified serial port.
            /// </summary>
            /// <param name="com">
            /// COM number of the serial port
            /// </param>
            /// <param name="baud">
            /// Baud rate for the serial port
            /// </param>
            internal SDIOController(SerialPort port)
            {
                m_stream = new SerialStream(port);

                m_responseQueue = new ArrayList();
                m_readBuffer = new byte[c_DefaultBuffLen];
                m_bytesInRead = 0;

                OpTimedOut = false;
            }
        public void StartPortReader()
        {
            Stream = new SerialStream(GenThreadManager, Services, PortName, BaudRate, Parity, DataBits, StopBits, Handshake, 20000);
            Converse.SetDeviceStream(Stream);
            Stream.Open();
            Stream.StartBuffer();

            ReaderStarted = true;
        }