public dataLoader(YSensor sensor)
 {
     _sensor           = sensor;
     _hwdName          = _sensor.get_hardwareId();
     _progressCallback = null;
     _mustStopNow      = false;
 }
Beispiel #2
0
        // Methods

        /// <summary>
        /// Get sensor
        /// </summary>
        /// <returns></returns>
        protected override YSensor GetSensor()
        {
            string errmsg = "";

            if (hardwaredetect == 0)
            {
                YAPI.UpdateDeviceList(ref errmsg);
            }
            hardwaredetect = (hardwaredetect + 1) % 20;
            YAPI.HandleEvents(ref errmsg);
            YSensor sensor = YPressure.FirstPressure();

            if (sensor is null)
            {
                throw new SensorNotDetectedException();
            }
            else if (!sensor.isOnline())
            {
                throw new SensorOfflineException();
            }
            else
            {
                return(sensor);
            }
        }
Beispiel #3
0
        // Datalogger buttons handling
        private void DataLoggerButton_Click(object sender, EventArgs e)
        {
            YSensor s = getSelectedSensor();

            if (s != null)
            {
                YModule     m   = s.get_module(); // get the module harboring the sensor
                YDataLogger dtl = YDataLogger.FindDataLogger(m.get_serialNumber() + ".dataLogger");
                if (dtl.isOnline())
                {
                    if (sender == RecordButton)
                    {
                        dtl.set_recording(YDataLogger.RECORDING_ON);
                    }
                    if (sender == PauseButton)
                    {
                        dtl.set_recording(YDataLogger.RECORDING_OFF);
                    }
                    if (sender == DeleteButton)
                    {
                        dtl.set_recording(YDataLogger.RECORDING_OFF);
                        MessageBox.Show("clear");
                        dtl.forgetAllDataStreams();
                        clearGraph();
                    }
                }
            }
            refreshDatloggerButton(s);
        }
Beispiel #4
0
        private void DisplayCalPoints(YSensor fct)
        {
            List <double> ValuesRaw = new List <double>();
            List <double> ValuesCal = new List <double>();

            int retcode = fct.loadCalibrationPoints(ValuesRaw, ValuesCal);

            if (retcode == YAPI.NOT_SUPPORTED)
            {
                EnableCalibrationUI(false);
                unsupported_warning.Visible = true;
                return;
            }

            // display the calibration points
            unsupported_warning.Visible = false;
            int i;

            for (i = 0; i < ValuesRaw.Count; i++)
            {
                rawedit[i].Text      = YAPI._floatToStr(ValuesRaw[i]);
                caledit[i].Text      = YAPI._floatToStr(ValuesCal[i]);
                rawedit[i].BackColor = System.Drawing.Color.FromArgb(0xA0, 0xFF, 0xA0);
                caledit[i].BackColor = System.Drawing.Color.FromArgb(0xA0, 0xFF, 0xA0);
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            string errmsg = "";

            if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS)
            {
                Console.WriteLine("RegisterHub error: " + errmsg);
                Environment.Exit(1);
            }

            YSensor sensor;

            if (args.Length == 0 || args[0] == "any")
            {
                sensor = YSensor.FirstSensor();
                if (sensor == null)
                {
                    Console.WriteLine("No module connected (check USB cable)");
                    Environment.Exit(1);
                }
            }
            else
            {
                sensor = YSensor.FindSensor(args[0]);
                if (!sensor.isOnline())
                {
                    Console.WriteLine("Sensor " + sensor + " is not connected (check USB cable)");
                    Environment.Exit(1);
                }
            }
            dumpSensor(sensor);
            YAPI.FreeAPI();
            Console.WriteLine("Done. Have a nice day :)");
        }
Beispiel #6
0
        async Task dispatcherTimer_Tick()
        {
            try {
                if (hardwaredetect == 0)
                {
                    await YAPI.UpdateDeviceList();
                }

                hardwaredetect = (hardwaredetect + 1) % 20;
                await YAPI.HandleEvents();

                if (sensor == null)
                {
                    sensor = YSensor.FirstSensor();
                }
                if (sensor != null)
                {
                    HwIdTextBox.Text = await sensor.get_friendlyName();

                    TempTextBox.Text = await sensor.get_currentValue() + await sensor.get_unit();
                }
            } catch (YAPI_Exception ex) {
                HwIdTextBox.Text = "Sensor is offline";
                TempTextBox.Text = "OFFLINE";
                sensor           = null;
            }
        }
Beispiel #7
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            string errmsg = "";

            if (hardwaredetect == 0)
            {
                YAPI.UpdateDeviceList(ref errmsg);
            }
            hardwaredetect = (hardwaredetect + 1) % 20;
            YAPI.HandleEvents(ref errmsg);
            if (sensor == null)
            {
                sensor = YSensor.FirstSensor();
            }
            if (sensor != null)
            {
                if (sensor.isOnline())
                {
                    label1.Text = sensor.get_friendlyName();
                    label2.Text = sensor.get_currentValue() + " " + sensor.get_unit();
                }
                else
                {
                    label1.Text = "OFFLINE";
                    label2.Text = "Sensor is offline";
                    sensor      = null;
                }
            }
        }
Beispiel #8
0
 // update the datalogger control buttons
 private void refreshDatloggerButton(YSensor s)
 {
     if (s != null)
     {
         YModule     m   = s.get_module(); // get the module harboring the sensor
         YDataLogger dtl = YDataLogger.FindDataLogger(m.get_serialNumber() + ".dataLogger");
         if (dtl.isOnline())
         {
             if (dtl.get_recording() == YDataLogger.RECORDING_ON)
             {
                 RecordButton.Enabled = false;
                 PauseButton.Enabled  = true;
                 DeleteButton.Enabled = false;
                 return;
             }
             else
             {
                 RecordButton.Enabled = true;
                 PauseButton.Enabled  = false;
                 DeleteButton.Enabled = true;
                 return;
             }
         }
     }
     RecordButton.Enabled = false;
     PauseButton.Enabled  = false;
     DeleteButton.Enabled = false;
 }
Beispiel #9
0
        // link the instance to a real YoctoAPI object
        internal override void linkToHardware(string hwdName)
        {
            YSensor hwd = YSensor.FindSensor(hwdName);

            // first redo base_init to update all _func pointers
            base_init(hwd, hwdName);
            // then setup Yocto-API pointers and callbacks
            init(hwd);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Console dotNET Application 0.1.0");
            Console.WriteLine("--------------------------------");
            Console.WriteLine("");

            Console.WriteLine("Using Yoctopuce lib " + YAPI.GetAPIVersion());
            string errsmg = "";

            if (YAPI.RegisterHub("usb", ref errsmg) != YAPI.SUCCESS)
            {
                Console.WriteLine("Unable to register the USB port :" + errsmg);
                return;
            }

            YSensor sensor = YSensor.FirstSensor();

            if (sensor == null)
            {
                Console.WriteLine("No Yoctopuce sensor find on USB.");
                return;
            }

            YDisplay display = YDisplay.FirstDisplay();

            if (display == null)
            {
                Console.WriteLine("No Yoctopuce display find on USB.");
                return;
            }

            // display clean up
            display.resetAll();

            YDisplayLayer l1 = display.get_displayLayer(1);

            l1.hide();    // L1 is hidden, l2 stay visible
            int w = display.get_displayWidth();
            int h = display.get_displayHeight();


            while (sensor.isOnline() && display.isOnline())
            {
                string value = sensor.get_currentValue() + " " + sensor.get_unit();
                string name  = sensor.get_friendlyName();
                // display a text in the middle of the screen
                l1.clear();
                l1.selectFont("Large.yfm");
                l1.drawText(w / 2, h / 2, YDisplayLayer.ALIGN.CENTER, value);
                l1.selectFont("Small.yfm");
                l1.drawText(w - 1, h - 1, YDisplayLayer.ALIGN.BOTTOM_RIGHT, name);
                display.swapLayerContent(0, 1);
                Console.WriteLine(name + " ->" + value);
                YAPI.Sleep(500, ref errsmg);
            }
            YAPI.FreeAPI();
        }
Beispiel #11
0
 // perform the 2nd stage setup that requires YoctoAPI object
 protected void init(YSensor hwd)
 {
     if (hwd == null)
     {
         return;
     }
     base.init(hwd);
     InternalStuff.log("registering Sensor callback");
     _func.registerValueCallback(valueChangeCallback);
     _func.registerTimedReportCallback(timedReportCallback);
 }
Beispiel #12
0
        public static YDataloggerContext init(string name, int start, int stop)
        {
            YSensor s = YSensor.FindSensor(name);

            if (!s.isOnline())
            {
                throw new Exception("sensor " + name + " is offline or does not exist.");
            }
            YDataloggerContext ctx = new YDataloggerContext(s, start, stop);

            return(ctx);
        }
Beispiel #13
0
        /**
         * <summary>
         *   Enumerates all functions of type Sensor available on the devices
         *   currently reachable by the library, and returns their unique hardware ID.
         * <para>
         *   Each of these IDs can be provided as argument to the method
         *   <c>YSensor.FindSensor</c> to obtain an object that can control the
         *   corresponding device.
         * </para>
         * </summary>
         * <returns>
         *   an array of strings, each string containing the unique hardwareId
         *   of a device function currently connected.
         * </returns>
         */
        public static new string[] GetSimilarFunctions()
        {
            List <string> res = new List <string>();
            YSensor       it  = YSensor.FirstSensor();

            while (it != null)
            {
                res.Add(it.get_hardwareId());
                it = it.nextSensor();
            }
            return(res.ToArray());
        }
Beispiel #14
0
        public static YSensorProxy FindSensor(string name)
        {
            // cases to handle:
            // name =""  no matching unknwn
            // name =""  unknown exists
            // name != "" no  matching unknown
            // name !="" unknown exists
            YSensor      func = null;
            YSensorProxy res  = (YSensorProxy)YFunctionProxy.FindSimilarUnknownFunction("YSensorProxy");

            if (name == "")
            {
                if (res != null)
                {
                    return(res);
                }
                res = (YSensorProxy)YFunctionProxy.FindSimilarKnownFunction("YSensorProxy");
                if (res != null)
                {
                    return(res);
                }
                func = YSensor.FirstSensor();
                if (func != null)
                {
                    name = func.get_hardwareId();
                    if (func.get_userData() != null)
                    {
                        return((YSensorProxy)func.get_userData());
                    }
                }
            }
            else
            {
                func = YSensor.FindSensor(name);
                if (func.get_userData() != null)
                {
                    return((YSensorProxy)func.get_userData());
                }
            }
            if (res == null)
            {
                res = new YSensorProxy(func, name);
            }
            if (func != null)
            {
                res.linkToHardware(name);
                if (func.isOnline())
                {
                    res.arrival();
                }
            }
            return(res);
        }
Beispiel #15
0
        //  This is the key function: it sets the calibration
        //  data in the device. Note: the parameters are written
        //  in the device RAM, if you want the calibration
        //  to be persistent, you have to call saveToflash();

        private void CalibrationChange(object sender, EventArgs e)
        {
            List <double> ValuesRaw = new List <double>();
            List <double> ValuesCal = new List <double>();
            List <int>    ParseRaw = new List <int>();
            List <int>    ParseCal = new List <int>();
            int           i = 0, j;

            if (functionsList.SelectedIndex < 0)
            {
                return;
            }

            while ((caledit[i].Text != "") && (rawedit[i].Text != "") && (i < 5))
            {
                ParseRaw = YAPI._decodeFloats(rawedit[i].Text);
                ParseCal = YAPI._decodeFloats(caledit[i].Text);
                if (ParseRaw.Count != 1 || ParseCal.Count != 1)
                {
                    break;
                }
                if (i > 0)
                {
                    if (ParseRaw[0] / 1000.0 <= ValuesRaw[i - 1])
                    {
                        break;
                    }
                }
                ValuesRaw.Add(ParseRaw[0] / 1000.0);
                ValuesCal.Add(ParseCal[0] / 1000.0);
                i++;
            }

            // some ui cosmetics: correct values are turned to green
            for (j = 0; j < i; j++)
            {
                caledit[j].BackColor = System.Drawing.Color.FromArgb(0xA0, 0xFF, 0xA0);
                rawedit[j].BackColor = System.Drawing.Color.FromArgb(0xA0, 0xFF, 0xA0);
            }
            for (j = i; j < 5; j++)
            {
                caledit[j].BackColor = System.Drawing.SystemColors.Window;
                rawedit[j].BackColor = System.Drawing.SystemColors.Window;
            }

            // send the calibration point to the device
            YSensor fct = (YSensor)functionsList.Items[functionsList.SelectedIndex];

            if (fct.isOnline())
            {
                fct.calibrateFromPoints(ValuesRaw, ValuesCal);
            }
        }
Beispiel #16
0
        async Task deviceArrival(YModule m)
        {
            string serial = await m.get_serialNumber();

            Output.Text += "Device arrival : " + serial + "\n";
            await m.registerLogCallback(deviceLog);

            await m.registerConfigChangeCallback(configChange);

            await m.registerBeaconCallback(beaconChange);

            // First solution: look for a specific type of function (eg. anButton)
            int fctcount = await m.functionCount();

            for (int i = 0; i < fctcount; i++)
            {
                string hardwareId = serial + "." + await m.functionId(i);

                if (hardwareId.IndexOf(".anButton") >= 0)
                {
                    Output.Text += "- " + hardwareId + "\n";
                    YAnButton anButton = YAnButton.FindAnButton(hardwareId);
                    await anButton.registerValueCallback(anButtonValueChangeCallBack);
                }
            }

            // Alternate solution: register any kind of sensor on the device
            YSensor sensor = YSensor.FirstSensor();

            while (sensor != null)
            {
                YModule module = await sensor.get_module();

                if (await module.get_serialNumber() == serial)
                {
                    string hardwareId = await sensor.get_hardwareId();

                    Output.Text += "- " + hardwareId + "\n";
                    string unit = await sensor.get_unit();

                    await sensor.set_userData(unit);

                    await sensor.registerValueCallback(sensorValueChangeCallBack);

                    await sensor.registerTimedReportCallback(sensorTimedReportCallBack);
                }

                sensor = sensor.nextSensor();
            }
        }
            public virtual async Task invoke()
            {
                if (_value == null)
                {
                    YSensor  sensor = (YSensor)_fun;
                    YMeasure mesure = await sensor._decodeTimedReport(_timestamp, _report);

                    await sensor._invokeTimedReportCallback(mesure);
                }
                else
                {
                    // new value
                    await _fun._invokeValueCallback(_value);
                }
            }
Beispiel #18
0
        internal YDataloggerContext(YSensor s, int start, int stop)
        {
            if (start < 0)
            {
                start = 0;
            }
            if (stop < 0)
            {
                stop = 0;
            }

            _sensor   = s;
            _dataset  = _sensor.get_recordedData(start, stop);
            _progress = _dataset.loadMore();
            _preview  = _dataset.get_preview();
        }
Beispiel #19
0
        private void choosenDeviceChanged()
        {
            YModule currentDevice;

            devicesList.Enabled = devicesList.Items.Count > 0;
            // clear the functions drop down
            functionsList.Items.Clear();
            functionsList.Enabled = devicesList.Enabled;

            if (!devicesList.Enabled)
            {
                unsupported_warning.Visible = false;
                nosensorfunction.Visible    = false;
                return;  // no device at all connected,
            }

            if (devicesList.SelectedIndex < 0)
            {
                devicesList.SelectedIndex = 0;
            }
            currentDevice = (YModule)devicesList.Items[devicesList.SelectedIndex];

            // populate the second drop down
            if (currentDevice.isOnline())
            {  // device capabilities inventory
                int fctcount = currentDevice.functionCount();
                for (int i = 0; i < fctcount; i++)
                {
                    string  fctName     = currentDevice.functionId(i);
                    string  fctFullName = currentDevice.get_serialNumber() + '.' + fctName;
                    YSensor fct         = YSensor.FindSensor(fctFullName);
                    // add the function in the second drop down
                    if (fct.isOnline())
                    {
                        functionsList.Items.Add(fct);
                    }
                }
            }
            functionsList.Enabled = functionsList.Items.Count > 0;
            if (functionsList.Enabled)
            {
                functionsList.SelectedIndex = 0;
            }

            refreshFctUI(true);
        }
Beispiel #20
0
        public override async Task <int> Run()
        {
            DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            try {
                await YAPI.RegisterHub(HubURL);

                // Enumerate all connected sensors
                YSensor        sensor;
                List <YSensor> sensorList = new List <YSensor>();
                sensor = YSensor.FirstSensor();
                while (sensor != null)
                {
                    sensorList.Add(sensor);
                    sensor = sensor.nextSensor();
                }

                if (sensorList.Count == 0)
                {
                    WriteLine("No Yoctopuce sensor connected (check USB cable)");
                }
                else
                {
                    // Generate consolidated CSV output for all sensors
                    YConsolidatedDataSet data   = new YConsolidatedDataSet(0, 0, sensorList);
                    List <Double>        record = new List <Double>();
                    while (await data.nextRecord(record) < 100)
                    {
                        string line = _epoch.AddSeconds(record[0]).ToString("yyyy-MM-ddTHH:mm:ss.fff");
                        for (int i = 1; i < record.Count; i++)
                        {
                            line += String.Format(";{0:0.000}", record[i]);
                        }
                        WriteLine(line);
                    }
                }
            } catch (YAPI_Exception ex) {
                WriteLine("Error:" + ex.Message);
            }


            YAPI.FreeAPI();
            return(0);
        }
Beispiel #21
0
        public Form1()
        {
            InitializeComponent();
            _t.Interval = 1000;
            _t.Enabled  = true;
            _t.Tick    += (sender, args) =>
            {
                YAPI.HandleEvents(ref _err);
            };

            YAPI.RegisterHub("USB", ref _err);
            YAPI.UpdateDeviceList(ref _err);
            var sensor = YSensor.FirstSensor();

            sensor.registerTimedReportCallback(timedReport);
            _t.Start();

            tbLux.Text = sensor.FriendlyName;
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string   errmsg = "";

            if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS)
            {
                Console.WriteLine("RegisterHub error: " + errmsg);
                Environment.Exit(1);
            }

            // Enumerate all connected sensors
            List <YSensor> sensorList = new List <YSensor>();
            YSensor        sensor;

            sensor = YSensor.FirstSensor();
            while (sensor != null)
            {
                sensorList.Add(sensor);
                sensor = sensor.nextSensor();
            }
            if (sensorList.Count == 0)
            {
                Console.WriteLine("No Yoctopuce sensor connected (check USB cable)");
                Environment.Exit(1);
            }

            // Generate consolidated CSV output for all sensors
            YConsolidatedDataSet data   = new YConsolidatedDataSet(0, 0, sensorList);
            List <double>        record = new List <double>();

            while (data.nextRecord(record) < 100)
            {
                string line = _epoch.AddSeconds(record[0]).ToString("yyyy-MM-ddTHH:mm:ss.fff");
                for (int i = 1; i < record.Count; i++)
                {
                    line += String.Format(";{0:0.000}", record[i]);
                }
                Console.WriteLine(line);
            }

            YAPI.FreeAPI();
        }
Beispiel #23
0
        private void refreshFctUI(bool newone)
        {
            nosensorfunction.Visible   = false;
            toolStripStatusLabel1.Text = devicesList.Items.Count.ToString() + " device(s) found";

            if (!functionsList.Enabled)
            { // disable the UI
                ValueDisplay.Text      = "N/A";
                ValueDisplayUnits.Text = "-";
                RawValueDisplay.Text   = "-";
                EnableCalibrationUI(false);
                if (devicesList.Enabled)
                {
                    nosensorfunction.Visible = true;
                }
                else
                {
                    toolStripStatusLabel1.Text = "Plug a Yocto-device";
                }
                return;
            }

            YSensor fct = (YSensor)functionsList.Items[functionsList.SelectedIndex];

            if (newone)
            { // enable the ui
                EnableCalibrationUI(true);
                for (int i = 0; i < 5; i++)
                {
                    caledit[i].Text      = "";
                    caledit[i].BackColor = System.Drawing.SystemColors.Window;
                    rawedit[i].Text      = "";
                    rawedit[i].BackColor = System.Drawing.SystemColors.Window;
                }
                DisplayCalPoints(fct);
            }

            if (fct.isOnline())
            {
                DisplayValue(fct);
            }
        }
Beispiel #24
0
        static void deviceArrival(YModule m)
        {
            string serial = m.get_serialNumber();

            Console.WriteLine("Device arrival : " + serial);
            m.registerLogCallback(deviceLog);
            m.registerConfigChangeCallback(configChange);
            m.registerBeaconCallback(beaconChange);

            // First solution: look for a specific type of function (eg. anButton)
            int fctcount = m.functionCount();

            for (int i = 0; i < fctcount; i++)
            {
                string hardwareId = serial + "." + m.functionId(i);
                if (hardwareId.IndexOf(".anButton") >= 0)
                {
                    Console.WriteLine("- " + hardwareId);
                    YAnButton anButton = YAnButton.FindAnButton(hardwareId);
                    anButton.registerValueCallback(anButtonValueChangeCallBack);
                }
            }

            // Alternate solution: register any kind of sensor on the device
            YSensor sensor = YSensor.FirstSensor();

            while (sensor != null)
            {
                if (sensor.get_module().get_serialNumber() == serial)
                {
                    string hardwareId = sensor.get_hardwareId();
                    Console.WriteLine("- " + hardwareId);
                    string unit = sensor.get_unit();
                    sensor.set_userData(unit);
                    sensor.registerValueCallback(sensorValueChangeCallBack);
                    sensor.registerTimedReportCallback(sensorTimedReportCallBack);
                }

                sensor = sensor.nextSensor();
            }
        }
Beispiel #25
0
        // automatically called each time a new yoctopuce device is plugged
        public void deviceArrival(YModule m)
        {   // new device just arrived, lets enumerate all sensors and
            // add the one missing to the combobox
            YSensor s = YSensor.FirstSensor();

            while (s != null)
            {
                if (!comboBox1.Items.Contains(s))
                {
                    int index = comboBox1.Items.Add(s);
                }
                s = s.nextSensor();
            }
            comboBox1.Enabled = comboBox1.Items.Count > 0;
            if ((comboBox1.SelectedIndex < 0) && (comboBox1.Items.Count > 0))
            {
                comboBox1.SelectedIndex = 0;
            }

            setSensorCount();
        }
        /**
         * <summary>
         *   Returns an object holding historical data for multiple
         *   sensors, for a specified time interval.
         * <para>
         *   The measures will be retrieved from the data logger, which must have been turned
         *   on at the desired time. The resulting object makes it possible to load progressively
         *   a large set of measures from multiple sensors, consolidating data on the fly
         *   to align records based on measurement timestamps.
         * </para>
         * <para>
         * </para>
         * </summary>
         * <param name="sensorNames">
         *   array of logical names or hardware identifiers of the sensors
         *   for which data must be loaded from their data logger.
         * </param>
         * <param name="startTime">
         *   the start of the desired measure time interval,
         *   as a Unix timestamp, i.e. the number of seconds since
         *   January 1, 1970 UTC. The special value 0 can be used
         *   to include any measure, without initial limit.
         * </param>
         * <param name="endTime">
         *   the end of the desired measure time interval,
         *   as a Unix timestamp, i.e. the number of seconds since
         *   January 1, 1970 UTC. The special value 0 can be used
         *   to include any measure, without ending limit.
         * </param>
         * <returns>
         *   an instance of <c>YConsolidatedDataSet</c>, providing access to
         *   consolidated historical data. Records can be loaded progressively
         *   using the <c>YConsolidatedDataSet.nextRecord()</c> method.
         * </returns>
         */
        public static YConsolidatedDataSet Init(List <string> sensorNames, double startTime, double endTime)
        {
            int                  nSensors;
            List <YSensor>       sensorList = new List <YSensor>();
            int                  idx;
            string               sensorName;
            YSensor              s;
            YConsolidatedDataSet obj;

            nSensors = sensorNames.Count;
            sensorList.Clear();
            idx = 0;
            while (idx < nSensors)
            {
                sensorName = sensorNames[idx];
                s          = YSensor.FindSensor(sensorName);
                sensorList.Add(s);
                idx = idx + 1;
            }
            obj = new YConsolidatedDataSet(startTime, endTime, sensorList);
            return(obj);
        }
Beispiel #27
0
        private void DisplayValue(YSensor fct)
        {
            double value      = fct.get_currentValue();
            double rawvalue   = fct.get_currentRawValue();
            double resolution = fct.get_resolution();
            string valunit    = fct.get_unit();

            // displays the sensor value on the ui
            ValueDisplayUnits.Text = valunit;

            if (resolution != YSensor.RESOLUTION_INVALID)
            {  // if resolution is available on the device the use it to  round the value
                string format = "F" + ((int)-Math.Round(Math.Log10(resolution))).ToString();

                RawValueDisplay.Text = "(raw value: " + (resolution * Math.Round(rawvalue / resolution)).ToString(format) + ")";
                ValueDisplay.Text    = (resolution * Math.Round(value / resolution)).ToString(format);
            }
            else
            {
                ValueDisplay.Text    = value.ToString();
                RawValueDisplay.Text = "";
            }
        }
Beispiel #28
0
        static void dumpSensor(YSensor sensor)
        {
            string fmt = "dd MMM yyyy hh:mm:ss,fff";

            Console.WriteLine("Using DataLogger of " + sensor.get_friendlyName());
            YDataSet dataset = sensor.get_recordedData(0, 0);

            Console.WriteLine("loading summary... ");
            dataset.loadMore();
            YMeasure summary = dataset.get_summary();
            String   line    =
                String.Format("from {0} to {1} : min={2:0.00}{5} avg={3:0.00}{5}  max={4:0.00}{5}",
                              summary.get_startTimeUTC_asDateTime().ToString(fmt),
                              summary.get_endTimeUTC_asDateTime().ToString(fmt), summary.get_minValue(),
                              summary.get_averageValue(), summary.get_maxValue(), sensor.get_unit());

            Console.WriteLine(line);
            Console.Write("loading details :   0%");
            int progress = 0;

            do
            {
                progress = dataset.loadMore();
                Console.Write(String.Format("\b\b\b\b{0,3:##0}%", progress));
            } while(progress < 100);
            Console.WriteLine("");
            List <YMeasure> details = dataset.get_measures();

            foreach (YMeasure m in details)
            {
                Console.WriteLine(
                    String.Format("from {0} to {1} : min={2:0.00}{5} avg={3:0.00}{5}  max={4:0.00}{5}",
                                  m.get_startTimeUTC_asDateTime().ToString(fmt),
                                  m.get_endTimeUTC_asDateTime().ToString(fmt), m.get_minValue(), m.get_averageValue(),
                                  m.get_maxValue(), sensor.get_unit()));
            }
        }
Beispiel #29
0
        // the core function :  load data from datalogger to send it to the graph
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // lets hide the graph wgile updating
            chart1.Visible    = false;
            comboBox1.Enabled = false;


            // remove any previous timed report call back
            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                ((YSensor)comboBox1.Items[i]).registerTimedReportCallback(null);
            }

            // allow zooming
            chart1.ChartAreas[0].CursorX.Interval                   = 0.001;
            chart1.ChartAreas[0].CursorX.IsUserEnabled              = true;
            chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled     = true;
            chart1.ChartAreas[0].CursorX.AutoScroll                 = true;
            chart1.ChartAreas[0].AxisX.ScaleView.Zoomable           = true;
            chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;

            int index = comboBox1.SelectedIndex;

            if (index >= 0)
            {
                clearGraph();
            }


            YSensor s = getSelectedSensor();

            if (s != null)
            {
                FirstPointDate = -1;
                LastPointDate  = -1;
                // some ui control
                loading.Visible = true;
                refreshDatloggerButton(null);
                progressBar.Visible = true;
                Status.Text         = "Loading data from datalogger...";
                for (int i = 0; i < 100; i++)
                {
                    Application.DoEvents();                          // makes sure the UI changes are repainted
                }
                // load data from datalogger
                YDataSet data     = s.get_recordedData(0, 0);
                int      progress = data.loadMore();
                while (progress < 100)
                {
                    try {
                        progressBar.Value = progress;
                    } catch { return; }

                    Application.DoEvents();
                    progress = data.loadMore();
                }

                // sets the unit (because ° is not a ASCII-128  character, Yoctopuce temperature
                // sensors report unit as 'C , so we fix it).
                chart1.ChartAreas[0].AxisY.Title     = s.get_unit().Replace("'C", "°C");
                chart1.ChartAreas[0].AxisY.TitleFont = new Font("Arial", 12, FontStyle.Regular);

                // send the data to the graph
                List <YMeasure> alldata = data.get_measures();
                for (int i = 0; i < alldata.Count; i++)
                {
                    chart1.Series[0].Points.AddXY(UnixTimeStampToDateTime(alldata[i].get_endTimeUTC()), alldata[i].get_averageValue());
                }

                // used to compute graph length
                if (alldata.Count > 0)
                {
                    FirstPointDate = alldata[0].get_endTimeUTC();
                    LastPointDate  = alldata[alldata.Count - 1].get_endTimeUTC();
                }
                setGraphScale();

                // restore UI
                comboBox1.Enabled   = true;
                progressBar.Visible = false;
                setSensorCount();
                s.set_reportFrequency("3/s");
                s.registerTimedReportCallback(newSensorValue);
                loading.Visible = false;
                chart1.Visible  = true;
                refreshDatloggerButton(s);
            }
        }
 public DataEvent(YFunction fun, String value)
 {
     _fun = fun;
     _sensor = null;
     _value = value;
     _report = null;
     _timestamp = 0;
 }
 public DataEvent(YSensor sensor, double timestamp, List<int> report)
 {
     _fun = null;
     _sensor = sensor;
     _value = null;
     _timestamp = timestamp;
     _report = report;
 }
 protected static void _UpdateTimedReportCallbackList(YSensor func, Boolean add)
 {
     if (add)
     {
         func.isOnline();
         if (!_TimedReportCallbackList.Contains(func))
         {
             _TimedReportCallbackList.Add(func);
         }
     }
     else
     {
         _TimedReportCallbackList.Remove(func);
     }
 }
 /**
  * <summary>
  *   Retrieves a sensor for a given identifier.
  * <para>
  *   The identifier can be specified using several formats:
  * </para>
  * <para>
  * </para>
  * <para>
  *   - FunctionLogicalName
  * </para>
  * <para>
  *   - ModuleSerialNumber.FunctionIdentifier
  * </para>
  * <para>
  *   - ModuleSerialNumber.FunctionLogicalName
  * </para>
  * <para>
  *   - ModuleLogicalName.FunctionIdentifier
  * </para>
  * <para>
  *   - ModuleLogicalName.FunctionLogicalName
  * </para>
  * <para>
  * </para>
  * <para>
  *   This function does not require that the sensor is online at the time
  *   it is invoked. The returned object is nevertheless valid.
  *   Use the method <c>YSensor.isOnline()</c> to test if the sensor is
  *   indeed online at a given time. In case of ambiguity when looking for
  *   a sensor by logical name, no error is notified: the first instance
  *   found is returned. The search is performed first by hardware name,
  *   then by logical name.
  * </para>
  * </summary>
  * <param name="func">
  *   a string that uniquely characterizes the sensor
  * </param>
  * <returns>
  *   a <c>YSensor</c> object allowing you to drive the sensor.
  * </returns>
  */
 public static YSensor FindSensor(string func)
 {
     YSensor obj;
     obj = (YSensor) YFunction._FindFromCache("Sensor", func);
     if (obj == null) {
         obj = new YSensor(func);
         YFunction._AddToCache("Sensor", func, obj);
     }
     return obj;
 }
Beispiel #34
0
 // perform the initial setup that may be done without a YoctoAPI object (hwd can be null)
 internal override void base_init(YFunction hwd, string instantiationName)
 {
     _func = (YSensor)hwd;
     base.base_init(hwd, instantiationName);
 }