Exemplo n.º 1
0
        private async Task <SunriseSunsetResults?> GetSunriseSunsetData(CancellationToken stoppingToken)
        {
            SunriseSunsetResults res = null;
            string data    = null;
            string tday    = DateTime.Now.ToString("yyyy-MM-dd");
            string request = string.Format($"https://api.sunrise-sunset.org/json?lat={appSettings.latitude}&lng={appSettings.longitude}&date={tday}&formatted=0");

            _logger.LogInformation(request);

            HttpClient client = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(30)
            };

            //string data = await client.GetStringAsync("https://api.sunrise-sunset.org/json?lat=-26.145457&lng=27.969062&date=today&formatted=0");
            try
            {
                //data = await client.GetStringAsync(appSettings.sunrisesunseturl);
                //data = await client.GetStringAsync("https://api.sunrise-sunset.org/json?lat=-26.145457&lng=27.969062&date=today&formatted=0");
                data = await client.GetStringAsync(request);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception getting sunrise/sunset data: {0}", e.ToString());
            }

            if (data != null)
            {
                try
                {
                    res = JsonConvert.DeserializeObject <SunriseSunsetResults>(data);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception in json conversion: {0}", e.ToString());
                    System.Diagnostics.Debug.WriteLine("Exception in json conversion: {0}", e.ToString());
                }
            }

            return(res);
        }
Exemplo n.º 2
0
        private static async Task Run(string port, IConsole console, bool untilsunset = false, int?cycles = 60, string?logfile = null)
        //    static async void Run(string port, IConsole console, int? cycles = 60, string? logfile = null)
        {
            //bool untilsunset = true;

            System.IO.StreamWriter?file = null;
            //System.IO.FileStream? fs = null;
            const int period          = 5000;
            int       noresponsecount = 0;

            double        energy   = 0.0;
            double        dcenergy = 0.0;
            StatusMessage?previous = null;

            if (statusMessages == null)
            {
                statusMessages = new List <StatusMessage>();
            }

            if (logfile != null)
            {
                Console.WriteLine("using file name {0}", logfile);

                try
                {
                    //fs = File.OpenWrite(logfile);
                    file = new System.IO.StreamWriter(logfile, true);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error opening log file: " + e.ToString());
                    Console.WriteLine("Error opening log file: " + e.ToString());
                }
            }

            if (untilsunset)
            {
                DateTime             endtime;
                SunriseSunsetResults srss = await GetSunriseSunsetData();

                if (srss == null || (srss.results.sunset < DateTime.Now))
                {
                    endtime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 0, 0);
                }
                else
                {
                    endtime = srss.results.sunset;
                }

                Console.WriteLine("Using end time {0:HH:mm}", endtime);

                cycles = (int)((endtime - DateTime.Now).TotalSeconds / (period / 1000));
            }

            Console.WriteLine("Opening port {0} and running {1} cycles", port, cycles);
            if (file != null)
            {
                Console.WriteLine("Using file {0}", logfile);
            }

            Console.WriteLine(appSettings.serialport);
            appSettings.serialport = port;


            //ListPorts();

            // Create a new SerialPort on port COM7
            _serialPort = new SerialPort(port, 9600)
            {
                // Set the read/write timeouts
                ReadTimeout  = 1500,
                WriteTimeout = 1500,
                StopBits     = StopBits.One
            };
            _serialPort.Open();

            _serialPort.DataReceived += _serialPort_DataReceived;

            Console.WriteLine("Writing to serial port");

            byte[] buf   = StatusMessage.BuildRequest(appSettings.radio, appSettings.inverters[0]);
            byte[] inbuf = null;
            //ReadPort();

            StatusMessage sm = null;
            StringBuilder sb = new StringBuilder();

            for (int cnt = 0; cnt < cycles; cnt++)
            {
                if (_serialPort != null)
                {
                    statusMessages.Add(sm = new StatusMessage()
                    {
                        StatusTime = DateTime.Now
                    });
                    _serialPort.Write(buf, 0, 15);;
                }
                Thread.Sleep(period);
                //Console.Write("\r\n");
                if ((sm != null) && sm.ReceiveComplete)
                {
                    noresponsecount = 0; // reset the non-response count

                    inbuf = sm.Rawdata;
                    foreach (byte b in inbuf)
                    {
                        sb.Append(b.ToString("X2"));
                    }

                    if (previous != null)
                    {
                        double secs = (sm.StatusTime - previous.StatusTime).TotalSeconds;
                        energy   += secs * 0.5 * (previous.ACVoltage * previous.ACCurrent + sm.ACVoltage * sm.ACCurrent);
                        dcenergy += secs * 0.5 * (previous.DCVoltage * previous.DCCurrent + sm.DCVoltage * sm.DCCurrent);
                    }

                    string s = string.Format(
                        "{0:HH:mm:ss}\t{1}\t{2}\t{3:0.00}\t{4:0.00}\t{5}\t{6}\t{7:0.00}\t{8:0.00}",
                        sm.StatusTime,
                        //sb.ToString(),
                        sm.DCVoltage,
                        sm.DCCurrent,
                        sm.DCVoltage * sm.DCCurrent,
                        dcenergy / 3600.0,
                        sm.ACVoltage,
                        sm.ACCurrent,
                        sm.ACVoltage * sm.ACCurrent,
                        energy / 3600.0
                        );

                    Console.WriteLine(s);
                    if (file != null)
                    {
                        await file.WriteLineAsync(s);

                        await file.FlushAsync();
                    }

                    previous = sm;

                    sb.Clear();
                }
                else  // we didn't get a response or the message was incomplete
                {
                    ++noresponsecount;  // increment the non-response count
                    if (noresponsecount > 4)
                    {
                        _serialPort.Close();
                        await Task.Delay(1000);

                        _serialPort.Open();
                    }
                }

                if (statusMessages.Count > 2)
                {
                    statusMessages.RemoveAt(0);
                }
            }

            _serialPort.Close();
            if (file != null)
            {
                file.Close();
                file.Dispose();
            }
        }
Exemplo n.º 3
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            DateTime       sunset       = DateTime.Now.Date + TimeSpan.FromHours(18.5);
            DateTime       sunrise      = DateTime.Now.Date + TimeSpan.FromHours(6.5);
            ReadLoopResult res;
            DateTime       lastday = DateTime.Now.Date - TimeSpan.FromHours(24);


            // load the configuration
            BuildConfiguration();
            string port = appSettings.serialport;

            // set up the serial port
            serialPort = new SerialPort(port, 9600)
            {
                // Set the read/write timeouts
                ReadTimeout  = 1500,
                WriteTimeout = 1500,
                StopBits     = StopBits.One
            };
            serialPort.DataReceived += SerialPort_DataReceived;

            // create the dictionary of inverters
            inverters = new Dictionary <string, Inverter>();
            foreach (string inv in appSettings.inverters)
            {
                inverters.Add(inv, new Inverter()
                {
                    Id = inv
                });
            }


            // open the state file
            try
            {
                stateFile = new FileStream(appSettings.logfilepath + "servicestate.json", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e.ToString());
            }
            await ReadLastState();

            while (!stoppingToken.IsCancellationRequested)
            {
                //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                //await Task.Delay(1000, stoppingToken);

                if (DateTime.Now.Date != lastday)  // we have rolled over to a new day
                {
                    SunriseSunsetResults ssr = await GetSunriseSunsetData(stoppingToken);

                    if (ssr != null)
                    {
                        sunrise = ssr.results.sunrise;
                        sunset  = ssr.results.sunset;
                    }
                    lastday = DateTime.Now.Date;

                    _logger.LogInformation(string.Format($"Logging will run from {sunrise:HH:mm:ss} to {sunset:HH:mm:ss}"));

                    if (serviceState != null)
                    {
                        serviceState.TotalEnergy = 0.0;                        // reset the total energy for the day
                    }
                    // reset the inverter counters
                    foreach (Inverter inv in inverters.Values)
                    {
                        inv.Reset();
                    }
                }



                while ((sunrise < DateTime.Now) && (DateTime.Now < sunset))
                {
                    res = await DoReadLoop(sunset, stoppingToken);

                    _logger.LogInformation(string.Format($"Returned from ReadLoop with {res}"));
                }

                await Task.Delay(1000); // wait a second before going around again
            }
        }