//
        // WARNING: EXTRA-SENSITIVE CODE ! Don't change a single dot in the code below without running
        //                                 the "hidden/AutoTest" test suite (using the dedicated test tool)
        //
        public static void deviceRemoval(YModule m)
        {
            string serial = m.get_serialNumber();

            //InternalStuff.log("device removal(" + serial + ")");

            for (int j = 0; j < _allProxies.Count; j++)
            {
                if (_allProxies[j].Online)
                {
                    if (_allProxies[j].get_hardwareId().Substring(0, serial.Length) == serial)
                    {
                        _allProxies[j].removal();
                    }
                }
            }
        }
Пример #2
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List <object> genericlist = e.Argument as List <object>;
            string        inFilename  = (string)genericlist[0];
            string        outFilename = (string)genericlist[1];
            string        serial      = (string)genericlist[2];
            YModule       m           = YModule.FindModule(serial);

            List <List <double> > angles = GetRecordList(m.get_serialNumber());
            VideoOSD osd = new VideoOSD(System.Drawing.Color.Aqua, inFilename);

            osd.setAngles(angles);
            osd.output(outFilename, backgroundWorker1);
            osd.release();

            e.Result = "done";            //return temp
        }
Пример #3
0
        public override async Task <int> Run()
        {
            YModule m;
            string  errmsg = "";

            if (await YAPI.RegisterHub(HubURL) != YAPI.SUCCESS)
            {
                WriteLine("RegisterHub error: " + errmsg);
                return(-1);
            }
            m = YModule.FindModule(Target + ".module"); // use serial or logical name
            if (await m.isOnline())
            {
                if (Beacon)
                {
                    await m.set_beacon(YModule.BEACON_ON);
                }
                else
                {
                    await m.set_beacon(YModule.BEACON_OFF);
                }

                WriteLine("serial: " + await m.get_serialNumber());
                WriteLine("logical name: " + await m.get_logicalName());
                WriteLine("luminosity: " + await m.get_luminosity());
                Write("beacon: ");
                if (await m.get_beacon() == YModule.BEACON_ON)
                {
                    WriteLine("ON");
                }
                else
                {
                    WriteLine("OFF");
                }
                WriteLine("upTime: " + (await m.get_upTime() / 1000) + " sec");
                WriteLine("USB current: " + await m.get_usbCurrent() + " mA");
                WriteLine("Logs:\r\n" + await m.get_lastLogs());
            }
            else
            {
                WriteLine(Target + " not connected  on" + HubURL +
                          "(check identification and USB cable)");
            }
            YAPI.FreeAPI();
            return(0);
        }
Пример #4
0
        private void DeviceRemoval(YModule m)
        {
            bool   oneItemRemoved = false;
            string serial         = m.get_serialNumber();

            for (int i = SensorChooser.Items.Count - 1; i >= 0; i--)
            {
                if (((CustomSensor)SensorChooser.Items[i]).serial == serial)
                {
                    if (SensorChooser.SelectedIndex == i)
                    {
                        SensorChooser.SelectedIndex = -1;
                    }
                    SensorChooser.Items.RemoveAt(i);
                    oneItemRemoved = true;
                }
            }

            if (oneItemRemoved)
            {
                if (SensorChooser.Items.Count == 0)
                {
                    ChooseSensorTitle.Text = "No more sensor available";
                }
                else if (SensorChooser.Items.Count == 1)
                {
                    ChooseSensorTitle.Text = "One WeighScale sensor left, Click on Next if this is the one you want use";
                }
                else
                {
                    ChooseSensorTitle.Text = SensorChooser.Items.Count.ToString() + " WeighScale sensors found. Choose the one you want to use and click on Next";
                }
                NextButton.Enabled    = (SensorChooser.Items.Count) > 0 && (SensorChooser.SelectedIndex > 0);
                SensorChooser.Visible = SensorChooser.Items.Count > 0;
            }

            if (ChoosedWeighScale != null)
            {
                if (ChoosedWeighScale.serial == serial)
                {
                    ClearCurrentPanel();
                    CurrentStep = PanelDesc.WizardSteps.DEVICEDISCONNECTED;
                    DrawCurrentPanel();
                }
            }
        }
Пример #5
0
        static void HubDiscovered(string serial, string url)
        {
            // The call-back can be called several times for the same hub
            // (the discovery technique is based on a periodic broadcast)
            // So we use a dictionnary to avoid duplicates
            if (KnownHubs.Contains(serial))
            {
                return;
            }

            Console.WriteLine("hub found: " + serial + " (" + url + ")");

            // connect to the hub
            string msg = "";

            YAPI.RegisterHub(url, ref msg);

            //  find the hub module
            YModule hub = YModule.FindModule(serial);

            // iterate on all functions on the module and find the ports
            int fctCount = hub.functionCount();

            for (int i = 0; i < fctCount; i++)
            {
                // retreive the hardware name of the ith function
                string fctHwdName = hub.functionId(i);
                if (fctHwdName.Length > 7)
                {
                    if (fctHwdName.Substring(0, 7) == "hubPort")
                    {
                        // The port logical name is always the serial#
                        // of the connected device
                        string deviceid = hub.functionName(i);
                        Console.WriteLine("  " + fctHwdName + " : " + deviceid);
                    }
                }
            }
            // add the hub to the dictionnary so we won't have to
            // process is again.
            KnownHubs.Add(serial);

            // disconnect from the hub
            YAPI.UnregisterHub(url);
        }
        private void RefreshInventory()
        {
            LinearLayout layout = FindViewById <LinearLayout>(Resource.Id.InventoryList);

            layout.RemoveAllViews();

            YAPI.UpdateDeviceList();
            YModule module = YModule.FirstModule();

            while (module != null)
            {
                string   line = module.SerialNumber + " (" + module.ProductName + ")";
                TextView tx   = new TextView(this);
                tx.Text = line;
                layout.AddView(tx);
                module = module.NextModule();
            }
        }
Пример #7
0
        public async Task ModifyConfig(string moduleName, string property, string value, bool save = true)
        {
            YModule module = Bot.ModuleManager.LoadedModules.Find(a => a.Name == moduleName);

            if (module is null)
            {
                await Channel.SendMessageAsync($"Module '{moduleName} does not exist'");

                return;
            }

            Config config = module?.GetType().GetCustomAttribute <Config>(true);

            if (config is null)
            {
                await Channel.SendMessageAsync($"Module '{moduleName} does not have a config class'");

                return;
            }

            Type         configType = module.GetConfig().GetType();
            PropertyInfo pInfo      = configType.GetProperty(property);
            FieldInfo    fInfo      = configType.GetField(property);

            if (pInfo != null)
            {
                pInfo.SetValue(module.GetConfig(), ParseParameter(value, pInfo.PropertyType));
            }

            if (fInfo != null)
            {
                fInfo.SetValue(module.GetConfig(), ParseParameter(value, fInfo.FieldType));
            }


            await Channel.SendMessageAsync($"Config updated");

            if (save)
            {
                await Bot.ModuleManager.SaveConfig();

                await Channel.SendMessageAsync($"Config saved");
            }
        }
Пример #8
0
        static void Main(string[] args)
        {
            YModule m;
            string  errmsg = "";

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

            Console.WriteLine("Device list");
            m = YModule.FirstModule();
            while (m != null)
            {
                Console.WriteLine(m.get_serialNumber() + " (" + m.get_productName() + ")");
                m = m.nextModule();
            }
            YAPI.FreeAPI();
        }
        private static void configChangeCallback(YModule module)
        {
            string id = module.get_serialNumber();

            //InternalStuff.log(" Module " + id + " config change  ");
            if (id == "")
            {
                return;            // just in case
            }
            foreach (YFunctionProxy f in _allProxies)
            {
                if (f.HardwareId.Length >= id.Length)
                {
                    if (f.HardwareId.Substring(0, id.Length) == id)
                    {
                        f.moduleConfigHasChanged();
                    }
                }
            }
        }
Пример #10
0
        static void arrivalCallback(YModule module)
        {
            string serial    = module.get_serialNumber();
            string parentHub = module.get_parentHub();

            if (parentHub == "")
            {
                // root device (
                string url = module.get_url();
                addRootDevice(serial, url);
            }
            else
            {
                RootDevice hub = getYoctoHub(parentHub);
                if (hub != null)
                {
                    hub.addSubDevice(serial);
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Load or create config for module.
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        async Task <object> LoadConfig(YModule module)
        {
            Config configAttribute = module.GetType().GetCustomAttribute <Config>();

            if (configAttribute != null)
            {
                Directory.CreateDirectory("Config/Modules");

                string path = $"Config/Modules/{module.Name}.json";
                if (File.Exists(path))
                {
                    object config;
                    string json;
                    using (StreamReader reader = new StreamReader(path))
                    {
                        json = await reader.ReadToEndAsync().ConfigureAwait(false);

                        config = JToken.Parse(json).ToObject(configAttribute.Type);
                    }

                    // Update config file JSON in case there is a new parameter
                    json = JsonConvert.SerializeObject(config, Formatting.Indented);
                    await File.WriteAllTextAsync(path, json);

                    return(config);
                }
                else
                {
                    object instance = Activator.CreateInstance(configAttribute.Type);
                    string json     = JsonConvert.SerializeObject(instance, Formatting.Indented);
                    using (StreamWriter writer = File.CreateText(path))
                    {
                        await writer.WriteLineAsync(json).ConfigureAwait(false);
                    }

                    return(instance);
                }
            }

            return(null);
        }
Пример #12
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();
            }
        }
Пример #13
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();
        }
Пример #14
0
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (comboBox1.SelectedIndex >= 0)
     {
         YModule m      = (YModule)comboBox1.Items[comboBox1.SelectedIndex];
         string  serial = m.get_serialNumber();
         currentGps            = YGps.FindGps(serial + ".gps");
         currentLat            = YLatitude.FindLatitude(serial + ".latitude");
         currentLon            = YLongitude.FindLongitude(serial + ".longitude");
         overlayOne.IsVisibile = true;
         refreshUI();
         myMap.Position = currentPos.Position;
     }
     else
     {
         overlayOne.IsVisibile = false;
         currentGps            = null;
         currentLat            = null;
         currentLon            = null;
     }
 }
Пример #15
0
        static void Main(string[] args)
        {
            YModule m;
            string  errmsg = "";
            string  newname;

            if (args.Length != 2)
            {
                usage();
            }

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

            m = YModule.FindModule(args[0]); // use serial or logical name

            if (m.isOnline())
            {
                newname = args[1];
                if (!YAPI.CheckLogicalName(newname))
                {
                    Console.WriteLine("Invalid name (" + newname + ")");
                    Environment.Exit(0);
                }

                m.set_logicalName(newname);
                m.saveToFlash(); // do not forget this

                Console.Write("Module: serial= " + m.get_serialNumber());
                Console.WriteLine(" / name= " + m.get_logicalName());
            }
            else
            {
                Console.Write("not connected (check identification and USB cable");
            }
            YAPI.FreeAPI();
        }
Пример #16
0
        public async Task DisplayConfig(string moduleName)
        {
            YModule module = Bot.ModuleManager.LoadedModules.Find(a => a.Name == moduleName);

            if (module is null)
            {
                await Channel.SendMessageAsync($"Module '{moduleName} does not exist'");

                return;
            }

            Config config = module?.GetType().GetCustomAttribute <Config>(true);

            if (config is null)
            {
                await Channel.SendMessageAsync($"Module '{moduleName} does not have a config class'");

                return;
            }

            await Channel.SendMessageAsync($"```{DisplayConfig(module.GetConfig())}```");
        }
Пример #17
0
        // called when a device is plugged
        public void deviceArrival(YModule m)
        { // new device arrived, lets check if any Ytemperature function are hosted
            int          fctCount = m.functionCount();
            YTemperature t;

            // list the functions availble on the device
            for (int i = 0; i < fctCount; i++)
            {
                string fname = m.functionId(i);
                if (fname.StartsWith("temperature"))
                {
                    t = YTemperature.FindTemperature(m.get_serialNumber() + '.' + fname);
                    // used in deviceRemoval
                    t.set_userData(t.get_module().get_serialNumber());

                    // ok  temperature found, lets add it to all gauges control dropdown
                    for (int j = 0; j < gauges.GetLength(0); j++)
                    {
                        ComboBox      d  = gauges[j].getDropDown();
                        MyTemperature mt = new MyTemperature(t);
                        d.Items.Add(mt);
                    }
                }
            }

            // enable the dropdowns if  not empty
            for (int j = 0; j < gauges.GetLength(0); j++)
            {
                ComboBox d = gauges[j].getDropDown();
                if (!d.Enabled && d.Items.Count > 0)
                {
                    if (j < d.Items.Count)
                    {
                        d.SelectedIndex = j;
                        d.Enabled       = true;
                    }
                }
            }
        }
Пример #18
0
        public override async Task <int> Run()
        {
            try {
                YVoc vocsensor;
                // Setup the API to use local USB devices
                await YAPI.RegisterHub(HubURL);

                if (Target.ToLower() == "any")
                {
                    vocsensor = YVoc.FirstVoc();

                    if (vocsensor == null)
                    {
                        WriteLine("No module connected (check USB cable) ");
                        return(-1);
                    }

                    YModule m = await vocsensor.get_module();

                    WriteLine("using " + await m.get_serialNumber());
                }
                else
                {
                    vocsensor = YVoc.FindVoc(Target + ".voc");
                }

                while (await vocsensor.isOnline())
                {
                    WriteLine("VOC: " + await vocsensor.get_currentValue() + " ppm");
                    await YAPI.Sleep(1000);
                }
                WriteLine("Module not connected (check identification and USB cable)");
            } catch (YAPI_Exception ex) {
                WriteLine("error: " + ex.Message);
            }

            YAPI.FreeAPI();
            return(0);
        }
Пример #19
0
        public override async Task <int> Run()
        {
            try {
                await YAPI.RegisterHub(HubURL);

                YCarbonDioxide co2sensor;

                if (Target.ToLower() == "any")
                {
                    co2sensor = YCarbonDioxide.FirstCarbonDioxide();

                    if (co2sensor == null)
                    {
                        WriteLine("No module connected (check USB cable) ");
                        return(-1);
                    }
                    YModule ymod = await co2sensor.get_module();

                    WriteLine("using " + await ymod.get_serialNumber());
                }
                else
                {
                    co2sensor = YCarbonDioxide.FindCarbonDioxide(Target + ".carbonDioxide");
                }

                while (await co2sensor.isOnline())
                {
                    WriteLine("CO2: " + await co2sensor.get_currentValue() + " ppm");
                    await YAPI.Sleep(1000);
                }

                WriteLine("Module not connected (check identification and USB cable)");
            } catch (YAPI_Exception ex) {
                WriteLine("error: " + ex.Message);
            }

            YAPI.FreeAPI();
            return(0);
        }
    void YoctopuceInitialisation()
    {
        Debug.Log("Use Yoctopuce Lib " + YAPI.GetAPIVersion());
        string errmsg = "";
        int    res    = YAPI.RegisterHub("usb", ref errmsg);

        if (res != YAPI.SUCCESS)
        {
            Debug.Log("error with RegisterHub:" + errmsg);
            errorText.text = errmsg;
            return;
        }
        YModule module = YModule.FirstModule();

        while (module != null)
        {
            string product = module.get_productName();
            if (product == "Yocto-3D" || product == "Yocto-3D-V2")
            {
                Debug.Log("Use " + product + " " + module.get_serialNumber());
                break;
            }
            module = module.nextModule();
        }
        if (module == null)
        {
            errorText.text = "No Yocto-3D or Yocto-3D-V2 found";
            return;
        }
        string serial = module.get_serialNumber();

        tilt_x = YTilt.FindTilt(serial + ".tilt1");
        tilt_z = YTilt.FindTilt(serial + ".tilt2");

        tilt_x.registerValueCallback(TiltCallbackX);
        tilt_z.registerValueCallback(TiltCallbackZ);
    }
Пример #21
0
        private void imm_logCallbackHandle(object context, byte[] result, int error, string errmsg)
        {
            if (result == null)
            {
                _logIsPulling = false;
                return;
            }

            if (_logCallback == null)
            {
                _logIsPulling = false;
                return;
            }

            string resultStr = YAPI.DefaultEncoding.GetString(result, 0, result.Length);
            int    pos       = resultStr.LastIndexOf("@", StringComparison.Ordinal);

            if (pos < 0)
            {
                _logIsPulling = false;
                return;
            }

            string logs   = resultStr.Substring(0, pos);
            string posStr = resultStr.Substring(pos + 1);

            _logpos = Convert.ToInt32(posStr);
            YModule module = YModule.FindModuleInContext(_hub._yctx, imm_getSerialNumber());

            string[] lines = logs.Split('\n');
            foreach (string line in lines)
            {
                _logCallback(module, line);
            }

            _logIsPulling = false;
        }
Пример #22
0
        /// <summary>
        /// Gets the YModule object for the device on which the function is located.
        /// If the function cannot be located on any module, the returned instance of
        /// YModule is not shown as on-line.
        /// </summary>
        /// <returns> an instance of YModule </returns>
        public virtual async Task <YModule> get_module()
        {
            // try to resolve the function name to a device id without query
            if (_serial != null && !_serial.Equals(""))
            {
                return(YModule.FindModuleInContext(_yapi, _serial + ".module"));
            }

            int ofs = _func.IndexOf('.');

            if (ofs == -1)
            {
                try {
                    string serial = _yapi._yHash.imm_resolveSerial(_className, _func);
                    return(YModule.FindModuleInContext(_yapi, serial + ".module"));
                } catch (YAPI_Exception) { }
            }

            if (ofs >= 0)
            {
                try {
                    string serial = _func.Substring(0, ofs);
                    return(YModule.FindModuleInContext(_yapi, serial + ".module"));
                } catch (YAPI_Exception) { }
            }

            try {
                // device not resolved for now, force a communication for a last chance resolution
                if (await load(await _yapi.GetCacheValidity()) == YAPI.SUCCESS)
                {
                    string serial = _yapi._yHash.imm_resolveSerial(_className, _func);
                    return(YModule.FindModuleInContext(_yapi, serial + ".module"));
                }
            } catch (YAPI_Exception) { }
            // return a true yFindModule object even if it is not a module valid for communicating
            return(YModule.FindModuleInContext(_yapi, "module_of_" + _className + "_" + _func));
        }
        public bool TestOnline()
        {
            if (_func == null)
            {
                return(false);
            }
            //InternalStuff.log("test if " + _hwdid + "(" + _instantiationName + ")  is online");
            if (!_func.isOnline())
            {
                //InternalStuff.log(" Nope, " + _hwdid + "(" + _instantiationName + ") is still offline");
                _online = false;
                return(false);
            }
            //InternalStuff.log(" Yes, " + _hwdid + "(" + _instantiationName + ") is online");
            _m            = _func.get_module();
            _hwdid        = _func.get_hardwareId();
            _serialNumber = _func.get_serialNumber();
            _functionId   = _func.get_functionId();
            _friendlyName = _func.get_friendlyName();

            _online = true;
            //InternalStuff.log(_hwdid + " is online");
            return(true);
        }
Пример #24
0
        private void moduleInventory()
        {
            YModule m, currentmodule;
            string  name;
            int     index;

            comboBox1.Items.Clear();
            currentmodule = null;
            m             = YModule.FirstModule();
            while (m != null)
            {
                if (m.get_productName() == "Yocto-3D")
                {
                    comboBox1.Items.Add(m);
                    //stop the datalogger
                    YDataLogger d = YDataLogger.FindDataLogger(m.get_serialNumber() + ".dataLogger");
                    d.set_recording(YDataLogger.RECORDING_OFF);
                }
                m = m.nextModule();
            }

            if (comboBox1.Items.Count == 0)
            {
                comboBox1.Enabled  = false;
                reset.Enabled      = false;
                loadButton.Enabled = false;
            }
            else
            {
                comboBox1.Enabled  = true;
                reset.Enabled      = true;
                loadButton.Enabled = true;
                index = 0;
                comboBox1.SelectedIndex = index;
            }
        }
        //
        // WARNING: EXTRA-SENSITIVE CODE ! Don't change a single dot in the code below without running
        //                                 the "hidden/AutoTest" test suite (using the dedicated test tool)
        //
        public static void deviceArrival(YModule m)
        {
            string ms = m.get_serialNumber();
            //InternalStuff.log("*** device arrival(" + m.get_serialNumber() + ")");
            string key         = ms + ".module";
            string mynamespace = InternalStuff.currentNameSpace;

            // try to find some unknown module proxy can be linked to the new arrival
            //InternalStuff.log("*** looking for existing Module proxies");
            for (int j = 0; j < _allProxies.Count; j++)
            {
                if (_allProxies[j].IsUnknown)
                {
                    if (_allProxies[j].GetType().ToString() == mynamespace + ".YModuleProxy")
                    {
                        //InternalStuff.log(" found");
                        _allProxies[j].linkToHardware(ms);
                        _allProxies[j].arrival();
                    }
                }
                else if (_allProxies[j].get_funcHardwareId() == key)
                {
                    _allProxies[j].linkToHardware(ms);
                    _allProxies[j].arrival();
                }
            }

            string myNameSpace = InternalStuff.currentNameSpace;

            // try to find some unknown function proxy  can be linked to the new arrival
            //InternalStuff.log("*** looking for existing Function proxies");
            for (int i = 0; i < m.functionCount(); i++)
            {
                string hwid     = ms + "." + m.functionId(i);
                string type     = m.functionType(i);
                string basetype = m.functionBaseType(i);

                for (int j = 0; j < _allProxies.Count; j++)
                {
                    if (_allProxies[j].IsUnknown)
                    {
                        string proxyType = _allProxies[j].GetType().ToString();
                        if (proxyType == myNameSpace + ".Y" + type + "Proxy" || proxyType == myNameSpace + ".Y" + basetype + "Proxy")
                        {
                            //InternalStuff.log(" found " + type);
                            _allProxies[j].linkToHardware(hwid);
                            _allProxies[j].arrival();
                        }
                    }
                    else if (_allProxies[j].get_funcHardwareId() == hwid)
                    {
                        _allProxies[j].linkToHardware(hwid);
                        _allProxies[j].arrival();
                    }
                }
            }

            m.registerConfigChangeCallback(configChangeCallback);
            configChangeCallback(m); // not triggered automatically at register
            InternalStuff.log("Arrival completed");
        }
Пример #26
0
 public PlugEvent(EVTYPE type, YModule mod)
 {
     _eventtype = type;
     _module = mod;
 }
Пример #27
0
 public void devicelistchanged(YModule m)
 {
     moduleInventory();
     refreshUI();
 }
Пример #28
0
        static void Main(string[] args)
        {
            string   errmsg = "";
            string   target;
            YCurrent sensor;
            YCurrent sensorDC = null;
            YCurrent sensorAC = null;
            YModule  m        = null;

            if (args.Length < 1)
            {
                usage();
            }
            target = args[0].ToUpper();

            // Setup the API to use local USB devices
            if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS)
            {
                Console.WriteLine("RegisterHub error: " + errmsg);
                Environment.Exit(0);
            }

            if (target == "ANY")
            {
                // retreive any voltage sensor (can be AC or DC)
                sensor = YCurrent.FirstCurrent();
                if (sensor == null)
                {
                    die("No module connected");
                }
            }
            else
            {
                sensor = YCurrent.FindCurrent(target + ".current1");
            }

            // we need to retreive both DC and AC voltage from the device.
            if (sensor.isOnline())
            {
                m        = sensor.get_module();
                sensorDC = YCurrent.FindCurrent(m.get_serialNumber() + ".current1");
                sensorAC = YCurrent.FindCurrent(m.get_serialNumber() + ".current2");
            }
            else
            {
                die("Module not connected");
            }

            if (!m.isOnline())
            {
                die("Module not connected");
            }

            while (m.isOnline())
            {
                Console.Write("DC: " + sensorDC.get_currentValue().ToString() + " mA ");
                Console.Write("AC: " + sensorAC.get_currentValue().ToString() + " mA ");
                Console.WriteLine("  (press Ctrl-C to exit)");

                YAPI.Sleep(1000, ref errmsg);
            }
            YAPI.FreeAPI();
        }
Пример #29
0
        private void refreshUI()
        { // draw  the dial.
            double value = -5;
            bool   on    = false;

            if (comboBox1.Enabled)
            { // if a yocto-volt device is connected, lets check it value
                YModule  m  = (YModule)comboBox1.Items[comboBox1.SelectedIndex];
                YVoltage DC = YVoltage.FindVoltage(m.get_serialNumber() + ".voltage1");
                YVoltage AC = YVoltage.FindVoltage(m.get_serialNumber() + ".voltage2");
                if (DC.isOnline())
                { // read DC or AC value, according to ACDCcheckBox
                    if (ACDCcheckBox.Checked)
                    {
                        value = 100 * (AC.get_currentValue() / maxvalue);
                    }
                    else
                    {
                        value = 100 * (DC.get_currentValue() / maxvalue);
                    }
                    on = true;
                }
            }

            // lets use a double buffering technique to avoid flickering
            Bitmap   BackBuffer = new Bitmap(on ? Properties.Resources.bg : Properties.Resources.bgoff);
            Graphics buffer     = Graphics.FromImage(BackBuffer);

            buffer.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            int DialWidth  = BackBuffer.Width;
            int DialHeight = BackBuffer.Height;

            // add inertia to the needle
            needleposition = needleposition + (value - needleposition) / 10;

            // make sure une needle won't go off chart
            if (needleposition < -5)
            {
                needleposition = -5;
            }
            if (needleposition > 105)
            {
                needleposition = 105;
            }

            double angle = 3.1416 * (180 - 30 - 120 * (needleposition / 100)) / 180;
            int    x     = Convert.ToInt32(DialWidth / 2 + Math.Cos(angle) * (DialHeight - 15));
            int    y     = Convert.ToInt32(DialHeight * 1.066 - Math.Sin(angle) * (DialHeight - 15));

            // draw the needle shadow
            Pen   shadow = new Pen(Color.FromArgb(16, 0, 0, 00), 3);
            Point point1 = new Point(DialWidth / 2 - 3, DialHeight + 3);
            Point point2 = new Point(Convert.ToInt32(x) - 3, Convert.ToInt32(y) + 3);

            buffer.DrawLine(shadow, point1, point2);

            // draw the needle
            Pen red = new Pen(on ? Color.FromArgb(255, 255, 0, 00) : Color.FromArgb(255, 64, 0, 00), 3);

            point1 = new Point(DialWidth / 2, DialHeight);
            point2 = new Point(Convert.ToInt32(x), Convert.ToInt32(y));
            buffer.DrawLine(red, point1, point2);

            // draw the scale
            FontFamily fontFamily = new FontFamily("Arial");
            Font       font       = new Font(fontFamily, DialHeight / 10, FontStyle.Regular, GraphicsUnit.Pixel);

            buffer.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 20, 20, 20));

            for (int i = 0; i <= 10; i++)
            {
                double dvalue = (maxvalue * i / 10);
                angle = 3.1416 * (180 - 30 - 120 * (i / 10.0)) / 180;
                string text = dvalue.ToString();
                SizeF  size = buffer.MeasureString(text, font);
                int    tx   = Convert.ToInt32(DialWidth / 2 + Math.Cos(angle) * DialHeight * 1.01 - size.Width / 2);
                int    ty   = Convert.ToInt32(DialHeight * 1.066 - Math.Sin(angle) * DialHeight * 0.98 - size.Height / 2);
                buffer.DrawString(dvalue.ToString(), font, solidBrush, new PointF(tx, ty));
            }

            Bitmap frame = new Bitmap(Properties.Resources.frame);

            buffer.DrawImage(frame, 0, 0);

            Graphics Viewable = pictureBox1.CreateGraphics();

            // fast rendering
            //Viewable.DrawImageUnscaled(BackBuffer, 0, 0);

            // slower, but pictureBox can be resized, rendering will still be ok,
            // try to respect a 2:1 ratio anyway
            Viewable.DrawImage(BackBuffer, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));

            Viewable.Dispose();
        }
Пример #30
0
 /**
  * <summary>
  *   Allows you to find a module from its serial number or from its logical name.
  * <para>
  * </para>
  * <para>
  *   This function does not require that the module is online at the time
  *   it is invoked. The returned object is nevertheless valid.
  *   Use the method <c>YModule.isOnline()</c> to test if the module is
  *   indeed online at a given time. In case of ambiguity when looking for
  *   a module 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 containing either the serial number or
  *   the logical name of the desired module
  * </param>
  * <returns>
  *   a <c>YModule</c> object allowing you to drive the module
  *   or get additional information on the module.
  * </returns>
  */
 public static YModule FindModule(string func)
 {
     YModule obj;
     obj = (YModule) YFunction._FindFromCache("Module", func);
     if (obj == null) {
         obj = new YModule(func);
         YFunction._AddToCache("Module", func, obj);
     }
     return obj;
 }
Пример #31
0
 public SavedObject(string name, string ex, YModule module, Type type) : this(name, ex, module.ID, type.FullName, $"Saves/{SanetizeName(module.Name)}/{name}{ex}")
 {
     DirectoryInfo dir = Directory.CreateDirectory($"Saves/{SanetizeName(module.Name)}");
 }
Пример #32
0
 //--- (generated code: Module functions)
 /**
    * <summary>
    *   Allows you to find a module from its serial number or from its logical name.
    * <para>
    * </para>
    * <para>
    *   This function does not require that the module is online at the time
    *   it is invoked. The returned object is nevertheless valid.
    *   Use the method <c>YModule.isOnline()</c> to test if the module is
    *   indeed online at a given time. In case of ambiguity when looking for
    *   a module 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 containing either the serial number or
    *   the logical name of the desired module
    * </param>
    * <returns>
    *   a <c>YModule</c> object allowing you to drive the module
    *   or get additional information on the module.
    * </returns>
    */
 public static YModule FindModule(string func)
 {
     YModule res;
     if (_ModuleCache.ContainsKey(func))
       return (YModule)_ModuleCache[func];
     res = new YModule(func);
     _ModuleCache.Add(func, res);
     return res;
 }
Пример #33
0
        private void button2_Click(object sender, EventArgs e)
        {
            YModule m = (YModule)comboBox1.Items[comboBox1.SelectedIndex];

            ConfigureYocto3d(m.get_serialNumber());
        }