/// <summary>
 /// 初始化与被测表通信初始化
 /// </summary>
 /// <param name="port">通信端口</param>
 /// <param name="baudRate">波特率</param>
 /// <param name="dataBits">数据位</param>
 /// <param name="parity">校验方式</param>
 public MeterCommunicationCommandParameter(CommunicationPort port, int baudRate, int dataBits, Parity parity)
 {
     ComPort  = port;
     BaudRate = baudRate;
     DataBits = dataBits;
     Parity   = parity;
 }
예제 #2
0
 private void ConnectButton_Click(object sender, EventArgs e)
 {
     try{
         if (ConnectButton.Text == "Connect")
         {
             CommunicationPort.PortName = SerialPortComboBox.SelectedItem as string;
             CommunicationPort.BaudRate = 57600;
             CommunicationPort.Open();
             log.Info("Open Com Port: " + CommunicationPort.PortName + " with baudrate " + CommunicationPort.BaudRate.ToString());
             ConnectButton.Text = "Disconnect";
         }
         else
         {
             if (CommunicationPort.IsOpen)
             {
                 CommunicationPort.Close();
             }
             ConnectButton.Text = "Connect";
         }
     }
     catch (Exception ex)
     {
         log.Error("Could not connect!", ex);
     }
 }
예제 #3
0
        private void BatteryValueTrackBar_ValueChanged(object sender, EventArgs e)
        {
            if (!CommunicationPort.IsOpen)
            {
                return;
            }
            MavLink.Mavlink       m = new MavLink.Mavlink();
            MavLink.MavlinkPacket p = new MavLink.MavlinkPacket();

            var tmp = new MavLink.Msg_sys_status();

            tmp.current_battery = 100;
            tmp.voltage_battery = (ushort)(BatteryValueTrackBar.Value * 100);

            p.ComponentId    = (int)MavLink.MAV_COMPONENT.MAV_COMP_ID_SYSTEM_CONTROL;
            p.SystemId       = 1;
            p.SequenceNumber = (byte)seq++;
            p.TimeStamp      = DateTime.Now;
            p.Message        = tmp;

            byte[] buffer = m.Send(p);

            //tmp.Serialize(buffer, ref offset);
            log.Info("Send Message");
            log.Info(buffer);
            log.Info("Offset: " + buffer.Length.ToString());
            CommunicationPort.Write(buffer, 0, buffer.Length);
            CommunicationPort.Write("\r\n");
        }
예제 #4
0
        public void Close()
        {
            lock (CommunicationPortLock)
            {
                //Make sure the port is not already closed.
                if (!CommunicationPort.IsConnected)
                {
                    return;
                }

                //Make sure we are not currently updating the state and
                //stop the timer so we don't try to update the state after we close the port.
                while (RefreshInProgress)
                {
                    ManualResetEvent manualEvent = new ManualResetEvent(false);
                    manualEvent.WaitOne(100);
                    manualEvent.Dispose();
                }
                StopUpdateTimer();

                //Close the serial port.
                Log(LogLevel.Information, "Closing communicaton port");
                CommunicationPort.Close();

                //Make sure the current state is cleared.
                CurrentState.Reset();
                OnStateChanged();
            }
        }
예제 #5
0
 private void Dispose(bool disposing)
 {
     if (!IsDisposed)
     {
         if (disposing && !IsDisposed)
         {
             Close();
             CommunicationPort.Dispose();
             CommunicationPort = null;
         }
         IsDisposed = true;
     }
 }
예제 #6
0
      /// <summary>
      /// Initializes a new instance of the <see cref="ComManager"/> class.
      /// </summary>
      /// <param name="ports">The ports.</param>
      private ComManager(List<PortData> ports)
      {
         var portsToControl = ports.Where(p => p.IsActive);
         this.servicePorts = new List<CommunicationPort>();
         foreach (var port in portsToControl)
         {
            var sp = new CommunicationPort()
               {
                  ComPortName = port.PortName,
                  ComTimeOut = TimeSpan.FromSeconds(20),
                  MeterType = MeterType.Edl
               };

            this.servicePorts.Add(sp);
         }
      }
예제 #7
0
        /// <summary>
        /// 组端口名的帧(Enum里的跟实际发的端口名帧不一样,需要转换)
        /// </summary>
        /// <param name="comPort">Enum端口成员</param>
        /// <returns>转换后组帧的数据</returns>
        private string GetComPortFrame(CommunicationPort comPort)
        {
            switch (comPort)
            {
            case CommunicationPort.RS232:
            {
                return("232");
            }

            case CommunicationPort.RS485_1:
            {
                return("485_1");
            }

            case CommunicationPort.RS485_2:
            {
                return("485_2");
            }

            case CommunicationPort.Optical:
            {
                return("GK");
            }

            case CommunicationPort.Infrared:
            {
                return("HW");
            }

            case CommunicationPort.PLC:
            {
                return("PLC");
            }

            default:
            {
                return("485_1");
            }
            }
        }
예제 #8
0
        private void valueTrackBar1_ValueChanged(object sender, EventArgs e)
        {
            if (!CommunicationPort.IsOpen)
            {
                return;
            }
            MavLink.Mavlink       m = new MavLink.Mavlink();
            MavLink.MavlinkPacket p = new MavLink.MavlinkPacket();

            var tmp = new MavLink.Msg_gps_raw_int();

            if (GpsFixCheckBox.CheckState == CheckState.Unchecked)
            {
                tmp.fix_type = 0;
            }
            else if (GpsFixCheckBox.CheckState == CheckState.Indeterminate)
            {
                tmp.fix_type = 2;
            }
            else
            {
                tmp.fix_type = 3;
            }
            tmp.satellites_visible = (byte)valueTrackBar1.Value;

            p.ComponentId    = (int)MavLink.MAV_COMPONENT.MAV_COMP_ID_GPS;
            p.SystemId       = 1;
            p.SequenceNumber = (byte)seq++;
            p.TimeStamp      = DateTime.Now;
            p.Message        = tmp;

            byte[] buffer = m.Send(p);

            //tmp.Serialize(buffer, ref offset);
            log.Info("Send Message");
            log.Info(buffer);
            log.Info("Offset: " + buffer.Length.ToString());
            CommunicationPort.Write(buffer, 0, buffer.Length);
            CommunicationPort.Write("\r\n");
        }
예제 #9
0
        private Response SendCommand(Command command)
        {
            if (!Open())
            {
                return(null);
            }
            try
            {
                List <byte> bytes = new List <byte>()
                {
                    command.CommandNumber
                };
                bytes.AddRange(command.Data);

                lock (CommunicationPortLock)
                {
                    Log(LogLevel.Information, "Sending Command: 0x{0}", BytesToString(bytes));
                    CommunicationPort.Write(bytes);
                    Log(LogLevel.Information, "Sent");

                    if (command.ResponseLength == 0)
                    {
                        Log(LogLevel.Information, "Command expects no response.");
                        return(new EmptyResponse());
                    }

                    byte[] buffer = CommunicationPort.Read(command.ResponseLength).ToArray();
                    Log(LogLevel.Information, "Response received: 0x{0}", BytesToString(buffer));
                    return(command.BuildResponse(buffer));
                }
            }
            catch (InvalidOperationException)
            {
                StopUpdateTimer();
                RefreshInProgress = false;
                Close();
                return(null);
            }
        }
예제 #10
0
        public bool Open()
        {
            if (CommunicationPort.IsConnected)
            {
                return(true);
            }

            lock (CommunicationPortLock)
            {
                Log(LogLevel.Information, "Opening communicaton port: {0}", ComPort);
                bool success = CommunicationPort.Open(ComPort);
                if (success)
                {
                    OnStateChanged();

                    GetGlobalConfiguration();
                    GetIgnitionConfiguration();
                    StartUpdateTimer();
                }
                return(success);
            }
        }
예제 #11
0
 protected OutputPacketHeader(CommunicationPort port, CommunicationChannel channel = DefaultChannel)
 {
     Port    = port;
     Channel = channel;
 }
예제 #12
0
        public async Task<bool> ProcessDevice(SmlComServiceClient svc, Guid guid, CommunicationPort port, CancellationToken token)
        {
            // cancellation setup
            this.cts?.Cancel();
            var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
            this.cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, token);
            token = cts.Token;

            var sw = Stopwatch.StartNew();
            try
            {
                if (!this.IsOccupiedByDevice)
                {
                    Log.Warning($"Station {this.Number} is not assigned by a device (MAC address missing)");
                    // only use active stations where a device is assigned (by scanning or user action)
                    return false;
                }

                var dr = new DeviceRepository();
                
                this.Device = dr.GetOne(this.Device.ServerId);

                this.SetStatusMessageAndProgress("Processing started...", 5);
                this.Status = StationStatus.Processing;
                
                var rnd = new Random();

                var policy = Policy
                        .Handle<Exception>()
                        .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2) });

                var portlist = await svc.GetPortListAsync();
                if (!portlist.FirstOrDefault(p => p.ComPortName == this.ComAddress).IsInitialized)
                {
                    throw new InvalidOperationException("Service Comport is not initialized!");
                }

                foreach (var param in this.Device.ParameterList)
                {
                    await Task.Delay(100, token);
                    if (!param.IsActive)
                    {
                        continue;
                    }

                    // execute communication with retry policy...
                    await policy.ExecuteAsync(async () =>
                    {
                        this.SetStatusMessageAndProgress($"Writing at {port.ComPortName} parameter {param.TagId} with value {param.TargetValue}...", this.Progress);
                        switch (param.TagId)
                        {
                            case ParameterTagId.ServerId:
                                var serverId = param.TargetValue.FromHexString();
                                await svc.WriteServerIdAsync(guid, port, serverId);

                                var serverIdParam = await svc.ReadServerIdAsync(guid, port);
                                param.RealValue = serverIdParam.Data.AsHexString("-");
                                break;
                            case ParameterTagId.ManufacturerSerialNumber:
                                await svc.WriteManufacturerSerialNumberAsync(guid, port, param.TargetValue);

                                var serialNoParam = await svc.ReadManufacturerSerialNoAsync(guid, port);
                                var serialNoBytes = serialNoParam.Data;
                                param.RealValue = Encoding.UTF8.GetString(serialNoBytes);
                                break;
                            case ParameterTagId.GenerateKeys:
                                await svc.WriteCreateKeysAsync(guid, port);

                                param.RealValue = "True";
                                param.IsWritten = true;
                                break;
                            case ParameterTagId.PublicKey:
                                param.RealValue = (await svc.ReadPublicKeyAsync(guid, port)).Data.AsHexString("-");
                                break;
                            case ParameterTagId.PinCodeActive:
                                var isPinActive = bool.Parse(param.TargetValue);
                                await svc.WriteIsPinProtectionActiveAsync(guid, port, isPinActive);

                                param.RealValue = (await svc.ReadIsPinProtectionActiveAsync(guid, port)).Data.ToString();
                                break;
                            case ParameterTagId.InitialKeyM:
                                await svc.WriteInitialSymKeyAsync(guid, port, param.TargetValue.FromHexString());
                                param.RealValue = (await svc.ReadInitialSymKeyAsync(guid, port)).Data.AsHexString("-");
                                break;
                            case ParameterTagId.PinCode:
                                await svc.WritePinAsync(guid, port, param.TargetValue);

                                param.RealValue = param.TargetValue;
                                param.IsWritten = true;
                                break;
                            case ParameterTagId.MeasurementMode:
                                await svc.WriteMeasurementModeAsync(guid, port, param.TargetValue);

                                param.RealValue = $"MM{(await svc.ReadMeasurementModeAsync(guid, port)).Data}";
                                break;
                            case ParameterTagId.GridOption:
                                var isGridOption = bool.Parse(param.TargetValue);
                                await svc.WriteEnableGridOptionAsync(guid, port, isGridOption);

                                param.RealValue = (await svc.ReadEnableGridOptionAsync(guid, port)).Data.ToString();
                                break;
                            case ParameterTagId.TarifOptionActive:
                                var isTariffActive = bool.Parse(param.TargetValue);
                                await svc.WriteEnableTariffFunctionAsync(guid, port, isTariffActive);

                                param.RealValue = (await svc.ReadEnableTariffFunctionAsync(guid, port)).Data.ToString();
                                break;
                            case ParameterTagId.InverseTariffControl:
                                var isInverse = bool.Parse(param.TargetValue);
                                await svc.WriteIsTerminalControlReverseAsync(guid, port, isInverse);

                                param.RealValue = (await svc.ReadIsTerminalControlReverseAsync(guid, port)).Data.ToString();
                                break;
                            case ParameterTagId.BaudRateConfigurable:
                                var isBaudrateConfigurable = bool.Parse(param.TargetValue);
                                await svc.WriteEnableBaudRateSettingAsync(guid, port, isBaudrateConfigurable);

                                param.RealValue = (await svc.ReadEnableBaudRateSettingAsync(guid, port)).Data.ToString();
                                break;
                            case ParameterTagId.BaudRate:
                                break;
                            case ParameterTagId.Type:
                                param.RealValue = param.TargetValue;
                                param.IsWritten = true;
                                break;
                            case ParameterTagId.Eigentumsnummer:
                                param.RealValue = param.TargetValue;
                                param.IsWritten = true;
                                break;
                            default:
                                throw new InvalidEnumArgumentException();
                        }
                        this.SetStatusMessageAndProgress($"{port.ComPortName} parameter {param.TagId} with value {param.TargetValue} write OK...", this.Progress += 5);
                    });
                }

                this.Device.SetAllParametersWritten(true);

                sw.Stop();
                Log.Warning("Device completed in {@sw}!", sw.Elapsed);

                // update database
                this.Device.ProducedAt = DateTime.Now;
                // dr.Update(device);

                this.LastProducedDeviceServerId = this.Device.ServerId;
                this.SetStatusMessageAndProgress("Processed", 100);
                this.Status = StationStatus.ProcessingCompleted;
                await Task.Delay(TimeSpan.FromSeconds(1), token);

                return true;
            }
            catch (OperationCanceledException)
            {
                Log.Warning("Station {s} cancelled", this.Number);
                this.SetStatusMessageAndProgress($"Cancelled", 0);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Station {s} failed", this.Number);
                this.SetStatusMessageAndProgress($"Error: {ex.Message}", 0);
                this.Status = StationStatus.Error;
            }

            return false;
        }
예제 #13
0
 void CommunicationPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     byte[] buffer = new byte[CommunicationPort.BytesToRead];
     CommunicationPort.Read(buffer, 0, CommunicationPort.BytesToRead);
     Invoke(new UpdateDataTextBoxDeleagte(UpdateDataTextBox), buffer);
 }