예제 #1
0
        public HeatingController(CommandHandler cmd)
        {
            _cmd          = new PluginsCommandHandler(cmd);
            _cmdUnwrapped = cmd;

            var heatersConfigs = IOconfFile.GetHeater().ToList();

            if (!heatersConfigs.Any())
            {
                return;
            }

            var ovens = IOconfFile.GetOven().ToList();

            foreach (var heater in heatersConfigs)
            {
                _heaters.Add(new HeaterElement(
                                 heater,
                                 ovens.SingleOrDefault(x => x.HeatingElement.Name == heater.Name)));
            }

            cmd.AddCommand("emergencyshutdown", EmergencyShutdown);
            cmd.AddSubsystem(this);
            _heaterCmd = new HeaterCommand(_heaters);
            _heaterCmd.Initialize(new PluginsCommandHandler(cmd), new PluginsLogger("heater"));
            _ovenCmd = new OvenCommand(_heaters, !ovens.Any());
            _ovenCmd.Initialize(new PluginsCommandHandler(cmd), new PluginsLogger("oven"));
            _switchboardController = SwitchBoardController.GetOrCreate(cmd);
        }
예제 #2
0
 public ServerUploader(VectorDescription vectorDescription, CommandHandler cmd)
 {
     try
     {
         if (cmd != null)
         {
             cmd.EventFired += SendEvent;
         }
         var duplicates = vectorDescription._items.GroupBy(x => x.Descriptor).Where(x => x.Count() > 1).Select(x => x.Key);
         if (duplicates.Any())
         {
             throw new Exception("Title of datapoint in vector was listed twice: " + string.Join(", ", duplicates));
         }
         var loopName = IOconfFile.GetLoopName();
         _signing = new Signing(loopName);
         vectorDescription.IOconf = IOconfFile.RawFile;
         _vectorDescription       = vectorDescription;
         _plot = PlotConnection.Establish(loopName, _signing.GetPublicKey(), GetSignedVectorDescription(vectorDescription)).GetAwaiter().GetResult();
         new Thread(() => this.LoopForever()).Start();
         _cmd = cmd;
         cmd?.AddCommand("escape", Stop);
     }
     catch (Exception ex)
     {
         OnError("failed initializing uploader", ex);
         throw;
     }
 }
예제 #3
0
        public async static Task <SerialNumberMapper> DetectDevices()
        {
            var logLevel = File.Exists("IO.conf") ? IOconfFile.GetOutputLevel() : CALogLevel.Normal;
            var boards   = await Task.WhenAll(RpiVersion.GetUSBports().Select(name => AttemptToOpenDeviceConnection(name, logLevel)));

            return(new SerialNumberMapper(boards));
        }
 private static void ReloadIOconf(SerialNumberMapper serial)
 {
     IOconfFile.Reload();
     foreach (var board in serial.McuBoards)
     {
         foreach (var ioconfMap in IOconfFile.GetMap())
         {
             if (ioconfMap.SetMCUboard(board))
             {
                 board.BoxName = ioconfMap.BoxName;
             }
         }
     }
 }
        public string Title => "SwitchboardActuation"; //not really displayed as this subsystem does not have data points

        private SwitchBoardController(CommandHandler cmd)
        {
            _cmd   = new PluginsCommandHandler(cmd);
            _ports = IOconfFile.GetEntries <IOconfOut230Vac>().Where(p => p.IsSwitchboardControllerOutput).ToList();
            var boardsTemperatures = _ports.GroupBy(p => p.BoxName).Select(b => b.Select(p => p.GetBoardTemperatureInputConf()).FirstOrDefault());
            var sensorPortsInputs  = IOconfFile.GetEntries <IOconfSwitchboardSensor>().SelectMany(i => i.GetExpandedConf());
            var inputs             = _ports.SelectMany(p => p.GetExpandedInputConf()).Concat(boardsTemperatures).Concat(sensorPortsInputs);

            //we register the subsystem before the reader auto registers, ensuring our Run is called first.
            //reason: if there are no boards connected, _reader.Stopping can be raised synchronously
            //        preventing our sub system from running and causing a deadlock as it WaitForLoopStopped.
            cmd.AddSubsystem(this);
            _reader           = new BaseSensorBox(cmd, "switchboards", string.Empty, "show switchboards inputs", inputs);
            _reader.Stopping += WaitForLoopStopped;
            cmd.AddCommand("escape", Stop);
        }
        public static string GetWelcomeMessage(string purpose, string i2cConfig = null)
        {
            var sb = new StringBuilder();

            sb.AppendLine("This is Open Source code by Copenhagen Atomics");
            sb.AppendLine(purpose);
            sb.AppendLine();
            if (IOconfFile.GetOutputLevel() == CALogLevel.Debug)
            {
                sb.AppendLine("UTC time now: " + DateTime.UtcNow.ToString("ddd MMM dd. HH:mm:ss"));
                sb.AppendLine(GetSoftware());
                sb.AppendLine(GetHardware(i2cConfig));
                sb.AppendLine();
            }
            sb.AppendLine("Press ESC to stop");
            sb.AppendLine();
            return(sb.ToString());
        }
예제 #7
0
        private List <IOconfAlert> GetAlerts(VectorDescription vectorDesc, CommandHandler cmd)
        {
            var alerts            = IOconfFile.GetAlerts().ToList();
            var alertsWithoutItem = alerts.Where(a => !vectorDesc.HasItem(a.Sensor)).ToList();

            foreach (var alert in alertsWithoutItem)
            {
                logger.LogError($"ERROR in {Directory.GetCurrentDirectory()}\\IO.conf:{Environment.NewLine} Alert: {alert.Name} points to missing sensor: {alert.Sensor}");
            }
            if (alertsWithoutItem.Count > 0)
            {
                throw new InvalidOperationException("Misconfigured alerts detected");
            }
            if (alerts.Any(a => a.Command != default) && cmd == null)
            {
                throw new InvalidOperationException("Alert with command is configured, but command handler is not available to trigger it");
            }
            return(alerts);
        }
예제 #8
0
        private void LoopForever()
        {
            _running = true;
            var vectorUploadDelay = IOconfFile.GetVectorUploadDelay();
            var throttle          = new TimeThrottle(vectorUploadDelay);

            while (_running)
            {
                throttle.Wait();
                try
                {
                    var list = DequeueAllEntries(_queue);
                    if (list != null)
                    {
                        PostVectorAsync(GetSignedVectors(list), list.First().timestamp);
                    }

                    var events = DequeueAllEntries(_eventsQueue);
                    if (events != null)
                    {
                        foreach (var @event in events)
                        {
                            PostEventAsync(@event);
                        }
                    }

                    PrintBadPackagesMessage(false);
                }
                catch (Exception ex)
                {
                    if (!Environment.MachineName.StartsWith("DESKTOP"))
                    {
                        CALog.LogErrorAndConsoleLn(LogID.A, "ServerUploader.LoopForever() exception: " + ex.Message, ex);
                    }
                }
            }

            PrintBadPackagesMessage(true);
        }
예제 #9
0
        private async static Task <MCUBoard> Create(string name, int baudrate, bool skipBoardAutoDetection)
        {
            MCUBoard board = null;

            try
            {
                var port = new SerialPort(name);
                board             = new MCUBoard(port);
                port.BaudRate     = 1;
                port.DtrEnable    = true;
                port.RtsEnable    = true;
                port.BaudRate     = baudrate;
                port.PortName     = name;
                port.ReadTimeout  = 2000;
                port.WriteTimeout = 2000;
                port.Open();
                board.pipeReader = PipeReader.Create(port.BaseStream);
                Thread.Sleep(30);                           // it needs to await that the board registers that the COM port has been opened before sending commands (work arounds issue when first opening the connection and sending serial).

                board.TryReadLine = board.TryReadAsciiLine; //this is the default which can be changed in ReadSerial based on the ThirdPartyProtocolDetection
                board.productType = "NA";

                if (skipBoardAutoDetection)
                {
                    board.InitialConnectionSucceeded = true;
                }
                else
                {
                    board.InitialConnectionSucceeded = await board.ReadSerialNumber();
                }

                if (File.Exists("IO.conf"))
                { // note that unlike the discovery at MCUBoard.OpenDeviceConnection that only considers the usb port, in here we can find the boards by the serial number too.
                    foreach (var ioconfMap in IOconfFile.GetMap())
                    {
                        if (ioconfMap.SetMCUboard(board))
                        {
                            board.BoxName        = ioconfMap.BoxName;
                            board.ConfigSettings = ioconfMap.BoardSettings;
                            port.ReadTimeout     = ioconfMap.BoardSettings.MaxMillisecondsWithoutNewValues;
                            await board.UpdateCalibration(board.ConfigSettings);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CALog.LogException(LogID.A, ex);
            }

            if (board != null && !board.InitialConnectionSucceeded)
            {
                board.pipeReader?.Complete();
                board.port.Close();
                Thread.Sleep(100);
            }
            else if (board != null && board.IsEmpty() && board.BoxName == null)
            {//note we don't log this for devices without serial that were mapped by usb (last check above)
                CALog.LogInfoAndConsoleLn(LogID.B, $"some data without serial detected for device at port {name} - {baudrate} / still connected");
            }

            return(board);
        }
 public GenericSensorBox(CommandHandler cmd) : base(cmd, "Generic", string.Empty, "show values for generic sensors", IOconfFile.GetGeneric())
 {
 }