Пример #1
0
 public RobotAction(CmmClient client)
 {
     _client    = client;
     _plcClient = PlcClient.Instance;
     _plcClient.DisconnectEvent += _plcClient_DisconnectEvent;
     _heartbeat = true;
 }
Пример #2
0
        private async void UpdateSwitch_Click(object sender, RoutedEventArgs e)
        {
            PlcClient c = this.FirstPlcClient;

            if (c == null)
            {
                this.LogMessage("目前没有 PLC 连接。");
                return;
            }

            this.LogMessage("Sending UpdateSwitchRequest");
            this.SendingDocument.Blocks.Clear();
            this.ReceivingDocument.Blocks.Clear();
            try
            {
                Switch response = await c.UpdateSwitchAsync(
                    new UpdateSwitchRequest
                {
                    Switch = new Switch
                    {
                        HeaterAutoOn = true,
                    },
                    UpdateMask = FieldMask.FromString <Switch>("heater_auto_on"),
                },
                    deadline : DateTime.Now.AddSeconds(30))
                                  .ConfigureAwait(true);

                this.LogMessage("Received UpdateSwitchResponse " + response.ToString());
            }
            catch (RpcException ex)
            {
                this.LogMessage("Failed to receive UpdateSwitchResponse " + ex.ToString());
            }
        }
Пример #3
0
        private async void GetMetric_Click(object sender, RoutedEventArgs e)
        {
            PlcClient c = this.FirstPlcClient;

            if (c == null)
            {
                this.LogMessage("目前没有 PLC 连接。");
                return;
            }

            this.LogMessage("Sending GetMetricRequest");
            this.SendingDocument.Blocks.Clear();
            this.ReceivingDocument.Blocks.Clear();
            try
            {
                Metric response = await c.GetMetricAsync(
                    new GetMetricRequest(),
                    deadline : DateTime.Now.AddSeconds(30))
                                  .ConfigureAwait(true);

                this.LogMessage("Received GetMetricResponse " + response.ToString());
            }
            catch (RpcException ex)
            {
                this.LogMessage("Failed to receive GetMetricResponse " + ex.ToString());
            }
        }
Пример #4
0
 //private AutoResetEvent arEvt = new AutoResetEvent(false);
 public WritePartIDForm()
 {
     InitializeComponent();
     writeok    = false;
     _plcClient = PlcClient.Instance;
     _plcClient.DisconnectEvent += _plcClient_DisconnectEvent;
     _plcHbDis = false;
     _isCancel = false;
 }
Пример #5
0
        private static async Task Main()
        {
            using ILoggerFactory loggerFactory = LoggerFactory.Create(b => b
                                                                      .AddConsole(opt =>
            {
                opt.LogToStandardErrorThreshold = LogLevel.Debug;
                opt.IncludeScopes = true;
            })
                                                                      .SetMinimumLevel(LogLevel.Debug));
            ILogger <Program> logger = loggerFactory.CreateLogger <Program>();

            var listener = TcpListener.Create(8888);

            listener.Start(20);
            logger.LogInformation("TCP Server is listening on port 8888");

#if DEBUG
            var t1 = new Thread(async() => await StartPlcAsync(logger, "127.0.0.1", 8888).ConfigureAwait(false));
            t1.Start();
            var t2 = new Thread(async() => await StartPlcAsync(logger, "127.0.0.1", 8888).ConfigureAwait(false));
            t2.Start();
#endif

            while (true)
            {
                TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);

                logger.LogInformation("TCP client connected: {0}", client.Client.RemoteEndPoint);

                using var plcClient = new PlcClient(loggerFactory.CreateLogger <PlcClient>(), client);
                await plcClient.StartAsync().ConfigureAwait(false);

                var request = new TestRequest()
                {
                    A = 42,
                    B = 3.1415926F,
                    C = "Hello World!",
                    D = Timestamp.FromDateTimeOffset(DateTimeOffset.Parse("2019-10-29T21:42:13.00000+8:00", CultureInfo.InvariantCulture)),
                };
                logger.LogInformation("Request sending: {0}", request);

                try
                {
                    TestResponse response = await plcClient.TestAsync(request, deadline : DateTime.Now.AddMilliseconds(3000)).ConfigureAwait(false);

                    logger.LogInformation("Response received: {0}", response);
                }
                catch (RpcException e)
                {
                    logger.LogError(e, "Failed to send/receive test");
                }
            }
        }
Пример #6
0
        private async void BackgroundTaskEntryPoint()
        {
            while (!this.cancellationTokenSource.IsCancellationRequested)
            {
                PlcClient client = null;
                try
                {
                    client = await this.plcServer.AcceptAsync().ConfigureAwait(false);

                    this.logger.LogInformation("TCP connection established from {0}", client.RemoteEndPoint);
                }
                catch (SocketException e)
                {
                    this.logger.LogError(e, "Failed to TCP accept PLC.");
                    continue;
                }
                catch (ObjectDisposedException)
                {
                    // Ignore it.
                    break;
                }

                ConnectResponse response;
                try
                {
                    response = await client
                               .ConnectAsync(new ConnectRequest(), DateTime.UtcNow.AddSeconds(10))
                               .ConfigureAwait(false);

                    this.logger.LogInformation(
                        "ConnectResponse received from newly PLC {0}: {1}",
                        client.RemoteEndPoint,
                        response);
                }
                catch (RpcException e)
                {
                    this.logger.LogWarning(
                        e,
                        "Failed to send ConnectRequest to newly PLC {0}, hang up.",
                        client.RemoteEndPoint);
                    await client.Close().ConfigureAwait(false);

                    client.Dispose();
                    continue;
                }

                client.OnClosed += (sender, args) =>
                {
                    this.logger.LogInformation(
                        "Client(MAC={0}, EndPoint={1}) disconnected.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                    this.PlcDictionary.TryRemove(response.Id, out PlcClient _);
                };

                if (this.PlcDictionary.TryAdd(response.Id, client))
                {
                    this.logger.LogInformation(
                        "Client(MAC={0}, EndPoint={1}) connected.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                }
                else
                {
                    this.logger.LogWarning(
                        "Failed to add the client(MAC={0}, EndPoint={1}) into dictionary.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                    await client.Close().ConfigureAwait(false);

                    client.Dispose();
                }
            }
        }
Пример #7
0
        private async void BackgroundTaskEntryPoint()
        {
            while (!this.cancellationTokenSource.IsCancellationRequested)
            {
                PlcClient client = await this.plcServer.AcceptAsync().ConfigureAwait(false);

                client.OnClosed += (sender, _) =>
                {
                    var c = (PlcClient)sender;
                    lock (this.lockObject)
                    {
                        this.clients.Remove(c);
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        this.LogMessage(string.Format(
                                            CultureInfo.CurrentCulture,
                                            "PLC {0} 已断开连接。",
                                            c.RemoteEndPoint));
                    });
                };

                lock (this.lockObject)
                {
                    if (this.clients.Count == 0)
                    {
                        client.OnDebugSending += (sender, bytes) =>
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                this.SendingDocument.Blocks.Clear();
                                this.SendingDocument.Blocks.Add(new Paragraph(new Run(HexUtils.Dump(
                                                                                          bytes, bytesPerLine: 4, showHeader: false))));
                            });
                        };
                        client.OnDebugReceiving += (sender, bytes) =>
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                this.ReceivingDocument.Blocks.Clear();
                                this.ReceivingDocument.Blocks.Add(new Paragraph(new Run(HexUtils.Dump(
                                                                                            bytes, bytesPerLine: 4, showHeader: false))));
                            });
                        };

                        this.clients.Add(client);
                    }
                    else
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            this.LogMessage("测试程序只允许一台 PLC 连接。");
                        });
                        client.Close().ConfigureAwait(false).GetAwaiter().GetResult();
                    }
                }

                this.Dispatcher.Invoke(() =>
                {
                    this.LogMessage(string.Format(
                                        CultureInfo.CurrentCulture,
                                        "PLC {0} 已连接,点击按钮向 PLC 发送消息,鼠标悬停在按钮上有相关说明。",
                                        client.RemoteEndPoint));
                });
            }
        }
Пример #8
0
 private void WritePartIDForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     _plcClient.DisconnectEvent -= _plcClient_DisconnectEvent;
     _plcClient = null;
 }