Esempio n. 1
0
        public ShelfBuilder([NotNull] ServiceDescription description, [NotNull] HostChannel channel)
            : base(description)
        {
            if (channel == null)
                throw new ArgumentNullException("channel");

            _channel = channel;
            _log = Logger.Get("Topshelf.Shelf." + description.Name);
        }
Esempio n. 2
0
        public ShelfBuilder([NotNull] ServiceDescription description, [NotNull] HostChannel channel)
            : base(description)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            _channel = channel;
            _log     = Logger.Get("Topshelf.Shelf." + description.Name);
        }
Esempio n. 3
0
 public void Dispose()
 {
     // Close the channel if it is still open
     if (HostChannel != null)
     {
         if (HostChannel.State == CommunicationState.Opened)
         {
             HostChannel.Channel.Disconnect(ServiceInstanceID, Guid);
             HostChannel.Close();
         }
         else if (HostChannel.State != CommunicationState.Closed)
         {
             HostChannel.Abort();
         }
     }
 }
Esempio n. 4
0
        public static void PushDataToHost(HostChannel channel, PayloadRoot payload)
        {
            switch (payload.Version.FormatFirstCapitalized())
            {
            case nameof(HostTransaction.Eai):
                ContactBuilder(new EaiLauncher(), payload, channel);
                break;

            case nameof(HostTransaction.Smes):
                ContactBuilder(new MesLauncher(), payload, channel);
                break;

            default:
                ContactBuilder(new MqttLauncher(), payload, channel);
                break;
            }
        }
Esempio n. 5
0
        public override async Task SendAsync(PayloadRoot payload, HostChannel channel)
        {
            if (channel == HostChannel.Undefined || payload.Row.Count == 0)
            {
                return;
            }

            string clientId = null, topic = null;

            switch (channel)
            {
            case HostChannel.Status:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Status);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Status).ToLower()}";
                break;

            case HostChannel.Parameter:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Parameter);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Parameter).ToLower()}";
                break;

            case HostChannel.Production:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Production);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Production).ToLower()}";
                break;
            }

            payload.Row.ForEach(c =>
            {
                if (YamlBase.Propertie.Debug)
                {
                    Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm ss}] ModbusTCP => NO.{payload.MachineNo} - {c.AttribNo}:{c.AttribValue}");
                }
            });

            try
            {
                FoundationProvider box = new();

                IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
                IConfigurationRoot    config  = builder.Build();

                IMqttClient client = new MqttFactory().CreateMqttClient();

                await client.ConnectAsync(new MqttClientOptionsBuilder()
                                          .WithTcpServer(box.FoundationBasic.Server.Address.Split('/')[2].Split(':')[0], box.FoundationBasic.Server.MqttPort)
                                          .WithCredentials(config.GetValue <string>("Server:Account"), config.GetValue <string>("Server:Password"))
                                          .WithClientId(clientId)
                                          .Build());

                await client.PublishAsync(new MqttApplicationMessageBuilder()
                                          .WithTopic(topic)
                                          .WithPayload(JsonConvert.SerializeObject(payload))
                                          .WithExactlyOnceQoS()
                                          .WithRetainFlag()
                                          .Build());

                await client.DisconnectAsync();

                client.Dispose();
            }
            catch (Exception e)
            {
                LogBuilder.WriteLog(LogEventLevel.Error, "MQTT Server => " + e.Message);
            }
        }
Esempio n. 6
0
 private static void PushHost(BaseStationFactory factory, PayloadRoot root, HostChannel channel) => factory.SendAsync(root, channel);
 public virtual void CloseOperation()
 {
     HostChannel.UnregisterOperation(this);
 }
Esempio n. 8
0
        public override async Task SendAsync(IConfigurationRoot root)
        {
            ModbusTcpManager.RebootModbusTcp = false;

            int iFrequency = 0;

            YamlBase.Modules.Where(c => c.Launcher == nameof(Communication.ModbusTcp)).Select(c => new
            {
                c.Frequency
            }).ToList().ForEach(c =>
            {
                iFrequency = c.Frequency;
            });

            List <MachineShell> MachineBoxes = new();

            root.GetSection(nameof(ModbusTcpTitle.MachineBox)).GetChildren().Select(c => new
            {
                machineNo  = c.GetValue <string>(nameof(ModbusTcpRoot.MachineNo)),
                production = c.GetValue <bool>(nameof(ModbusTcpRoot.Production)),
                disabled   = c.GetValue <bool>(nameof(ModbusTcpRoot.Disabled)),
                vesion     = c.GetValue <string>(nameof(ModbusTcpRoot.Version)),
                address    = c.GetValue <string>(nameof(ModbusTcpRoot.Address)),
                port       = c.GetValue <int>(nameof(ModbusTcpRoot.Port)),
                map        = c.GetSection(nameof(ModbusTcpRoot.Map)).GetChildren().Select(c => new
                {
                    disabled     = c.GetValue <bool>(nameof(ElementBox.Disabled)),
                    channel      = c.GetValue <string>(nameof(ElementBox.Channel)),
                    functionCode = c.GetValue <int>(nameof(ElementBox.FunctionCode)),
                    slaveAddress = c.GetValue <byte>(nameof(ElementBox.SlaveAddress)),
                    startAddress = c.GetValue <ushort>(nameof(ElementBox.StartAddress)),
                    Points       = c.GetSection(nameof(ElementBox.NumberOfPoints)).GetChildren().Select(c => new
                    {
                        pointNo    = c.GetValue <int>(nameof(Numberofpoint.PointNo)),
                        attribName = c.GetValue <string>(nameof(Numberofpoint.AttribName))
                    }).ToList()
                }).ToList()
            }).ToList().ForEach(c =>
            {
                if (c.disabled)
                {
                    return;
                }

                List <MessageBox> boxes = new();

                c.map.ForEach(c =>
                {
                    if (c.disabled)
                    {
                        return;
                    }

                    HostChannel Channel = c.channel switch
                    {
                        nameof(HostChannel.Status) => HostChannel.Status,
                        nameof(HostChannel.Parameter) => HostChannel.Parameter,
                        nameof(HostChannel.Production) => HostChannel.Production,
                        _ => HostChannel.Undefined
                    };

                    if (Channel == HostChannel.Undefined)
                    {
                        return;
                    }

                    List <PickPoint> points = new();

                    c.Points.ForEach(c =>
                    {
                        points.Add(new()
                        {
                            PointNo    = c.pointNo,
                            AttribName = c.attribName
                        });
                    });

                    boxes.Add(new()
                    {
                        Channel      = Channel,
                        FunctionCode = c.functionCode,
                        SlaveAddress = c.slaveAddress,
                        StartAddress = c.startAddress,
                        PickPoints   = points
                    });
                });

                MachineBoxes.Add(new()
                {
                    MachineNo    = c.machineNo,
                    Production   = c.production,
                    Vesion       = c.vesion,
                    Address      = c.address,
                    Port         = c.port,
                    MessageBoxes = boxes
                });
            });

            void Working(object obj)
            {
                MachineBoxes.ForEach(async c =>
                {
                    await Task.Run(() =>
                    {
                        int iPort         = c.Port;
                        string sMachineNo = c.MachineNo, sAddress = c.Address;

                        lock (MachineSwitch) if (!MachineSwitch.ContainsKey(sMachineNo))
                            {
                                MachineSwitch.Add(sMachineNo, true);
                            }

                        c.MessageBoxes.ForEach(async c =>
                        {
                            try
                            {
                                if (c.PickPoints.Count == 0)
                                {
                                    return;
                                }

                                using TcpClient client      = new TcpClient(sAddress, iPort);
                                using ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                                ushort[] result             = await master.ReadHoldingRegistersAsync(c.SlaveAddress, c.StartAddress, Convert.ToUInt16(c.PickPoints.Count));

                                if (result == null || result.Length == 0)
                                {
                                    return;
                                }

                                MachineSwitch[sMachineNo] = true;

                                c.PickPoints.ForEach(c =>
                                {
                                    string sKey = sMachineNo + "#" + c.AttribName;

                                    lock (RowBox)
                                    {
                                        if (!RowBox.ContainsKey(sKey))
                                        {
                                            RowBox.Add(sKey, result[c.PointNo]);
                                        }
                                        else
                                        {
                                            RowBox[sKey] = result[c.PointNo];
                                        }
                                    }
                                });
                            }
                            catch (Exception e)
                            {
                                if (MachineSwitch[sMachineNo] == true)
                                {
                                    //webapi <==

                                    Console.WriteLine($" No.{sMachineNo} => {e.Message}");
                                }

                                MachineSwitch[sMachineNo] = false;
                            }
                        });
                    });
                });
            }

            await Task.Run(() =>
            {
                try
                {
                    Callback += new TimerCallback(Working);
                    Callback += new TimerCallback(RocketLaunch);
                    Timer     = new Timer(Callback, null, Timeout.Infinite, iFrequency);
                    Timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(iFrequency));
                }
                catch (Exception e)
                {
                    Console.WriteLine("sMMP => " + e.Message + "\n" + e.StackTrace);
                }
            });

            void RocketLaunch(object obj)
            {
                MachineBoxes.ToList().ForEach(async c =>
                {
                    await Task.Run(() =>
                    {
                        bool bProduction  = c.Production;
                        string sMachineNo = c.MachineNo, sVersion = c.Vesion;

                        List <Parameter> parameters = new();

                        c.MessageBoxes.ForEach(c =>
                        {
                            c.PickPoints.ForEach(c =>
                            {
                                string sKey = sMachineNo + "#" + c.AttribName;

                                if (RowBox.ContainsKey(sKey))
                                {
                                    lock (HistoryBox)
                                    {
                                        if (!HistoryBox.ContainsKey(sKey))
                                        {
                                            HistoryBox.Add(sKey, RowBox[sKey]);
                                        }
                                        else
                                        {
                                            if (RowBox[sKey] != HistoryBox[sKey])
                                            {
                                                parameters.Add(new()
                                                {
                                                    AttribNo    = c.AttribName,
                                                    AttribValue = RowBox[sKey]
                                                });

                                                HistoryBox[sKey] = RowBox[sKey];
                                            }
                                        }
                                    }
                                }
                            });

                            GlobalVariables globally = new();

                            GlobalApproach.PushDataToHost(c.Channel, new()
                            {
                                Version        = sVersion,
                                Production     = bProduction,
                                MachineNo      = sMachineNo,
                                ReportDateTime = globally.NowTime,
                                Row            = parameters
                            });
                        });
                    });
                });
            }
        }
Esempio n. 9
0
        public override async Task SendAsync(PayloadRoot root, HostChannel channel)
        {
            try
            {
                if (channel == HostChannel.Undefined || root.Row.Count == 0)
                {
                    return;
                }

                FoundationProvider provider  = new();
                GlobalVariables    variables = new();

                XElement xHost = new("host");
                xHost.Add(new XAttribute("prod", provider.FoundationBasic.Eai.Host.Name));
                xHost.Add(new XAttribute("ver", provider.FoundationBasic.Eai.Host.Version));
                xHost.Add(new XAttribute("ip", GeneralTools.GetLocalIP()));
                xHost.Add(new XAttribute("id", provider.FoundationBasic.Eai.Host.Id));
                xHost.Add(new XAttribute("acct", provider.FoundationBasic.Eai.Host.Account));
                xHost.Add(new XAttribute("lang", provider.FoundationBasic.Eai.Host.Language));
                xHost.Add(new XAttribute("timestamp", DateTime.Now.ToString(("yyyyMMddHHmmssfff"))));

                XElement service = new("service");
                service.Add(new XAttribute("prod", provider.FoundationBasic.Eai.Service.Name));
                service.Add(new XAttribute("name", channel switch
                {
                    HostChannel.Status => "change.machine.status.process",
                    HostChannel.Parameter => "parameter.check.process",
                    HostChannel.Production => "production.edc.process",
                    _ => ""
                }));
                service.Add(new XAttribute("srvver", provider.FoundationBasic.Eai.Service.Srvver));
                service.Add(new XAttribute("ip", provider.FoundationBasic.Eai.Service.Ip));
                service.Add(new XAttribute("id", provider.FoundationBasic.Eai.Service.Id));

                XElement xRoot = new XElement("request");
                xRoot.Add(new XAttribute("key", (xHost.ToString() + service.ToString()).ToMD5()));
                xRoot.Add(new XAttribute("type", "sync"));
                xRoot.Add(xHost);
                xRoot.Add(service);

                XElement xPayload = new("payload");

                XElement xParam = new("param");
                xParam.Add(new XAttribute("key", "std_data"));
                xParam.Add(new XAttribute("type", "xml"));
                xPayload.Add(xParam);

                XElement xDataRequest = new("data_request");
                xParam.Add(xDataRequest);

                XElement xDatainfo = new("datainfo");
                xDataRequest.Add(xDatainfo);

                XElement xParameter = new("parameter");
                xParameter.Add(new XAttribute("key", channel switch
                {
                    HostChannel.Status => "change_machine_status",
                    HostChannel.Parameter => "parameter_check",
                    HostChannel.Production => "production_edc",
                    _ => ""
                }));
Esempio n. 10
0
 public ShelfBuilder(ServiceDescription description, HostChannel channel)
     : base(description)
 {
     _channel = channel;
     _log     = LogManager.GetLogger("Topshelf.Shelf." + description.Name);
 }
Esempio n. 11
0
 public abstract Task SendAsync(PayloadRoot root, HostChannel channel);