Esempio n. 1
0
        /// <summary>
        /// Detects Cuda devices.
        /// </summary>
        /// <param name="predicate">
        /// The predicate to include a given device.
        /// </param>
        /// <param name="registry">The registry to add all devices to.</param>
        private static void GetDevicesInternal(
            Predicate <CudaDevice> predicate,
            DeviceRegistry registry)
        {
            // Resolve all devices
            if (CurrentAPI.GetDeviceCount(out int numDevices) !=
                CudaError.CUDA_SUCCESS ||
                numDevices < 1)
            {
                return;
            }

            for (int i = 0; i < numDevices; ++i)
            {
                if (CurrentAPI.GetDevice(out int device, i) != CudaError.CUDA_SUCCESS)
                {
                    continue;
                }

                var desc = new CudaDevice(device);
                if (predicate(desc))
                {
                    registry.Register(desc);
                }
            }
        }
        public List <DeviceRegistry> ToList()
        {
            deviceRegistries.Clear();
            int index       = 0;
            var deviceQuery = registryManager.CreateQuery("SELECT * FROM devices");

            while (deviceQuery.HasMoreResults)
            {
                var twinsTask = deviceQuery.GetNextAsTwinAsync();
                twinsTask.Wait();
                foreach (var twin in twinsTask.Result)
                {
                    var dr = new DeviceRegistry()
                    {
                        Id                 = index++,
                        DeviceId           = twin.DeviceId,
                        ETags              = twin.ETag,
                        DesiredProperties  = twin.Properties.Desired.ToJson(),
                        ReportedProperties = twin.Properties.Reported.ToJson()
                    };
                    deviceRegistries.Add(dr);
                }
            }

            return(deviceRegistries);
        }
Esempio n. 3
0
 void FillRegisteredDevices()
 {
     if (UnityEngine.Windows.File.Exists(RegisteryPath))
     {
         byte[] data = UnityEngine.Windows.File.ReadAllBytes(RegisteryPath);
         if (data != null && data.Length > 0)
         {
             string text = Encoding.ASCII.GetString(data);
             JsonSerializerSettings settings = new JsonSerializerSettings
             {
                 TypeNameHandling = TypeNameHandling.All
             };
             _registry = JsonConvert.DeserializeObject <DeviceRegistry>(text, settings);
             Debug.Log("Registered devices: " + _registry.Devices.Count);
             foreach (var device in _registry.Devices)
             {
                 RestoreDevice(device);
             }
         }
         else
         {
             _registry = new DeviceRegistry();
         }
     }
     else
     {
         _registry = new DeviceRegistry();
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Detects OpenCL devices.
        /// </summary>
        /// <param name="predicate">
        /// The predicate to include a given device.
        /// </param>
        /// <param name="registry">The registry to add all devices to.</param>
        private static void GetDevicesInternal(
            Predicate <CLDevice> predicate,
            DeviceRegistry registry)
        {
            var devices = new IntPtr[MaxNumDevicesPerPlatform];

            // Resolve all platforms
            if (!CurrentAPI.IsSupported ||
                CurrentAPI.GetNumPlatforms(out int numPlatforms) !=
                CLError.CL_SUCCESS ||
                numPlatforms < 1)
            {
                return;
            }

            var platforms = new IntPtr[numPlatforms];

            if (CurrentAPI.GetPlatforms(platforms, ref numPlatforms) !=
                CLError.CL_SUCCESS)
            {
                return;
            }

            foreach (var platform in platforms)
            {
                // Resolve all devices
                int numDevices = devices.Length;
                Array.Clear(devices, 0, numDevices);

                if (CurrentAPI.GetDevices(
                        platform,
                        CLDeviceType.CL_DEVICE_TYPE_ALL,
                        devices,
                        out numDevices) != CLError.CL_SUCCESS)
                {
                    continue;
                }

                for (int i = 0; i < numDevices; ++i)
                {
                    // Resolve device and ignore invalid devices
                    var device = devices[i];
                    if (device == IntPtr.Zero)
                    {
                        continue;
                    }

                    // Check for available device
                    if (CurrentAPI.GetDeviceInfo <int>(
                            device,
                            CLDeviceInfoType.CL_DEVICE_AVAILABLE) == 0)
                    {
                        continue;
                    }

                    var desc = new CLDevice(platform, device);
                    registry.Register(desc, predicate);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Returns CPU devices.
        /// </summary>
        /// <param name="predicate">
        /// The predicate to include a given device.
        /// </param>
        /// <returns>All CPU devices.</returns>
        public static ImmutableArray <Device> GetDevices(Predicate <CPUDevice> predicate)
        {
            var registry = new DeviceRegistry();

            GetDevices(predicate, registry);
            return(registry.ToImmutable());
        }
        public ActionResult Invoke([Bind(Include = "Id,DeviceId,MethodName,MethodPayload")] DeviceRegistry deviceRegistry)
        {
            var            result = db.Invoke(deviceRegistry);
            DeviceRegistry listedDeviceRegistry = db.Find(deviceRegistry.Id);

            listedDeviceRegistry.MethodPayload = result;
            return(RedirectToAction("Details", new { id = deviceRegistry.Id }));
        }
        public ActionResult MotorDrive([Bind(Include = "Id,DeviceId,MethodName")] DeviceRegistry deviceRegistry)
        {
            string invocationResult = invokeMotorDrive(deviceRegistry);
            var    listedDR         = db.Find(deviceRegistry.Id);

            listedDR.MethodPayload = invocationResult;
            return(RedirectToAction("Details", new { id = deviceRegistry.Id }));
        }
        public ActionResult TriggerAlarm([Bind(Include = "Id,DeviceId")] DeviceRegistry deviceRegistry)
        {
            deviceRegistry.MethodName    = "TriggerAlarm";
            deviceRegistry.MethodPayload = "{\"msg\":\"hello\"}";
            string result   = db.Invoke(deviceRegistry);
            var    listedDR = db.Find(deviceRegistry.Id);

            listedDR.MethodPayload = result;
            return(RedirectToAction("Details", new { id = deviceRegistry.Id }));
        }
        public void Update(DeviceRegistry item)
        {
            var twinTask = registryManager.GetTwinAsync(item.DeviceId);

            twinTask.Wait();
            var twin = twinTask.Result;

            twin.Properties.Desired = new TwinCollection(item.DesiredProperties);
            twin.ETag = item.ETags;
            registryManager.UpdateTwinAsync(item.DeviceId, twin, twin.ETag).Wait();
        }
        public ActionResult Create([Bind(Include = "Id,DeviceId,DesiredProperties,ReportedProperties,ETags")] DeviceRegistry deviceRegistry)
        {
            if (ModelState.IsValid)
            {
                // db.DeviceRegistries.Add(deviceRegistry);
                // db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(deviceRegistry));
        }
 public ActionResult Edit([Bind(Include = "Id,DeviceId,DesiredProperties,ReportedProperties,ETags,MethodName")] DeviceRegistry deviceRegistry)
 {
     if (ModelState.IsValid)
     {
         //                db.Entry(deviceRegistry).State = EntityState.Modified;
         //              db.SaveChanges();
         db.Update(deviceRegistry);
         return(RedirectToAction("Index"));
     }
     return(View(deviceRegistry));
 }
Esempio n. 12
0
        // [END iot_send_command]

        // [START iot_create_registry]
        public static object CreateRegistry(string projectId, string cloudRegion,
                                            string registryId, string pubsubTopic)
        {
            var cloudIot = CreateAuthorizedClient();
            // The resource name of the location associated with the key rings.
            var parent = $"projects/{projectId}/locations/{cloudRegion}";

            Console.WriteLine(parent);

            try
            {
                Console.WriteLine($"Creating {registryId}");
                DeviceRegistry body = new DeviceRegistry()
                {
                    Id = registryId,
                };
                body.EventNotificationConfigs =
                    new List <EventNotificationConfig>();
                var toAdd = new EventNotificationConfig()
                {
                    PubsubTopicName = pubsubTopic.StartsWith("projects/") ?
                                      pubsubTopic : $"projects/{projectId}" +
                                      $"/topics/{pubsubTopic}",
                };
                body.EventNotificationConfigs.Add(toAdd);
                var registry = cloudIot
                               .Projects
                               .Locations
                               .Registries
                               .Create(body, parent)
                               .Execute();
                Console.WriteLine("Registry: ");
                Console.WriteLine($"{registry.Id}");
                Console.WriteLine($"\tName: {registry.Name}");
                Console.WriteLine($"\tHTTP Enabled: " +
                                  $"{registry.HttpConfig.HttpEnabledState}");
                Console.WriteLine($"\tMQTT Enabled: " +
                                  $"{registry.MqttConfig.MqttEnabledState}");
            }
            catch (Google.GoogleApiException e)
            {
                Console.WriteLine(e.Message);
                if (e.Error != null)
                {
                    return(e.Error.Code);
                }
                return(-1);
            }
            return(0);
        }
        string invokeMotorDrive(DeviceRegistry deviceRegistry)
        {
            string cmd   = "";
            string speed = "150";

            switch (deviceRegistry.MethodName)
            {
            case "LF":
                cmd = "LF" + speed;
                break;

            case "LFRF":
                cmd = "LF" + speed + ";" + "RF" + speed;
                break;

            case "RF":
                cmd = "RF" + speed;
                break;

            case "LB":
                cmd = "LB";
                break;

            case "LBRB":
                cmd = "LB;RB";
                break;

            case "RB":
                cmd = "RB";
                break;

            case "LR":
                cmd = "LR" + speed;
                break;

            case "LRRR":
                cmd = "LR" + speed + ";" + "RR" + speed;
                break;

            case "RR":
                cmd = "RR" + speed;
                break;
            }
            string order = "{\"command\":\"" + cmd + "\"}";

            deviceRegistry.MethodName    = "MotorDrive";
            deviceRegistry.MethodPayload = order;
            return(db.Invoke(deviceRegistry));
        }
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
//            DeviceRegistry deviceRegistry = db.DeviceRegistries.Find(id);
            DeviceRegistry deviceRegistry = db.Find(id.Value);

            if (deviceRegistry == null)
            {
                return(HttpNotFound());
            }
            return(View(deviceRegistry));
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the dev console!");

            var devices = AudioDeviceHost.GetDeviceIds();

            var host     = new AudioDeviceHost();
            var registry = new DeviceRegistry(Scheduler.Immediate);

            registry.RegisterHost(host);

            var dev = registry.Bind <Microphone>(new AudioDeviceIdentifier(devices.First()));

            //var dev = registry.Bind<Microphone>(new AudioDeviceIdentifier("Microphone (2- Logitech G933 Gaming Headset)"));
            //var dev = registry.Bind<Microphone>(new AudioDeviceIdentifier("Casque (PXC 550 Stereo)"));

            dev.TurnOff().ToTask().Wait();
        }
        public string Invoke(DeviceRegistry item)
        {
            string result      = "";
            var    cloudMethod = new CloudToDeviceMethod(item.MethodName);

            cloudMethod.SetPayloadJson(item.MethodPayload);
            try
            {
                var invocationTask = serviceClient.InvokeDeviceMethodAsync(item.DeviceId, cloudMethod);
                invocationTask.Wait();
                result = string.Format("\"Status\":{0},\"Payload\":{1}", invocationTask.Result.Status, invocationTask.Result.GetPayloadAsJson());
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return(result);
        }
Esempio n. 17
0
        /// <summary>
        /// Registers CPU devices.
        /// </summary>
        /// <param name="predicate">
        /// The predicate to include a given device.
        /// </param>
        /// <param name="registry">The registry to add all devices to.</param>
        internal static void GetDevices(
            Predicate <CPUDevice> predicate,
            DeviceRegistry registry)
        {
            if (registry is null)
            {
                throw new ArgumentNullException(nameof(registry));
            }
            if (predicate is null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            foreach (var desc in All)
            {
                registry.Register(desc, predicate);
            }
        }
Esempio n. 18
0
        internal static void GetDevices(
            Predicate <CLDevice> predicate,
            DeviceRegistry registry)
        {
            if (registry is null)
            {
                throw new ArgumentNullException(nameof(registry));
            }
            if (predicate is null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            try
            {
                GetDevicesInternal(predicate, registry);
            }
            catch (Exception)
            {
                // Ignore API-specific exceptions at this point
            }
        }
 public ActionResult Send([Bind(Include = "Id,DeviceId,C2DMessage")] DeviceRegistry deviceRegistry)
 {
     db.Send(deviceRegistry);
     return(RedirectToAction("Details", new { id = deviceRegistry.Id }));
 }
Esempio n. 20
0
 /// <summary>
 /// Converts this builder instance into a context instance.
 /// </summary>
 /// <returns>The created context instance.</returns>
 public Context ToContext() => new Context(
     this,
     DeviceRegistry.ToImmutable());
 public DeviceExposer(ServiceClient serviceClient,  DeviceRegistry deviceRegistry)
 {
     this.serviceClient = serviceClient;
      this.deviceRegistry = deviceRegistry;
 }
        public void Send(DeviceRegistry item)
        {
            var c2dmsg = new Microsoft.Azure.Devices.Message(System.Text.Encoding.UTF8.GetBytes(item.C2DMessage));

            serviceClient.SendAsync(item.DeviceId, c2dmsg).Wait();
        }
Esempio n. 23
0
        public void Startup()
        {
            MqttApplicationMessage lastwill = new MqttApplicationMessage()
            {
                Topic   = $"{Global.mqtt_prefix}/status",
                Payload = Encoding.UTF8.GetBytes(OFFLINE),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
                Retain = true
            };

            MqttClientOptionsBuilder options = new MqttClientOptionsBuilder()
                                               .WithTcpServer(Global.mqtt_server)
                                               .WithWillMessage(lastwill);

            if (!string.IsNullOrEmpty(Global.mqtt_username))
            {
                options = options
                          .WithCredentials(Global.mqtt_username, Global.mqtt_password);
            }

            ManagedMqttClientOptions manoptions = new ManagedMqttClientOptionsBuilder()
                                                  .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                                  .WithClientOptions(options.Build())
                                                  .Build();

            MqttClient = new MqttFactory().CreateManagedMqttClient();
            MqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate((e) =>
            {
                log.Debug("Connected");

                MqttDeviceRegistry = new DeviceRegistry()
                {
                    identifiers  = Global.mqtt_prefix,
                    name         = Global.mqtt_prefix,
                    sw_version   = $"{OmniLink.Controller.GetVersionText()} - OmniLinkBridge {Assembly.GetExecutingAssembly().GetName().Version}",
                    model        = OmniLink.Controller.GetModelText(),
                    manufacturer = "Leviton"
                };

                // For the initial connection wait for the controller connected event to publish config
                // For subsequent connections publish config immediately
                if (ControllerConnected)
                {
                    PublishConfig();
                }
            });
            MqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate((e) => log.Error("Error connecting {reason}", e.Exception.Message));
            MqttClient.DisconnectedHandler     = new MqttClientDisconnectedHandlerDelegate((e) => log.Debug("Disconnected"));

            MqttClient.StartAsync(manoptions);

            MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate((e) =>
                                                                                                             MessageProcessor.Process(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload)));

            // Subscribe to notifications for these command topics
            List <Topic> toSubscribe = new List <Topic>()
            {
                Topic.command,
                Topic.alarm_command,
                Topic.brightness_command,
                Topic.scene_command,
                Topic.temperature_heat_command,
                Topic.temperature_cool_command,
                Topic.humidify_command,
                Topic.dehumidify_command,
                Topic.mode_command,
                Topic.fan_mode_command,
                Topic.hold_command
            };

            toSubscribe.ForEach((command) => MqttClient.SubscribeAsync(
                                    new MqttTopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{command}").Build()));

            // Wait until shutdown
            trigger.WaitOne();

            PublishControllerStatus(OFFLINE);

            MqttClient.StopAsync();
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            log4net.Config.BasicConfigurator.Configure();
            Tracer.Initialize(new TracerManager());

            AppDomain.CurrentDomain.UnhandledException += (s, e) => tracer.Error(e.ExceptionObject);
            TaskScheduler.UnobservedTaskException += (s, e) => tracer.Error(e.Exception);

            try
            {
                short port = 1055;
                if (args.Length > 0)
                    port = short.Parse(args[0]);

                ServiceRegistration.Start(port);

                var devices = new DeviceRegistry();
                var topics = new Dictionary<string, TopicType>();
                var stream = new EventStream();
                var state = new SystemState();
                var impulseStore = new FileImpulseStore("Store\\Impulses");
                var commandStore = new FileCommandStore("Store\\Commands");

                SetupTracing(stream);

                // Hook up event stream consumers that perform orthogonal operations.
                new ClockImpulses(Clock.Default).Connect(stream);
                new CommandToBytes().Connect(stream);
                new SensedToImpulse(Sensorium.Clock.Default, topics).Connect(stream);
                new SetSystemState(state).Connect(stream);
                // Hook up stores
                new StoreCommands(commandStore).Connect(stream);
                new StoreImpulses(impulseStore).Connect(stream);
                
                var brain = new Brain(stream, devices, topics, state, Clock.Default);

                if (File.Exists("Server.cfg"))
                {
                    var setup = Setup.Read("Server.cfg", File.ReadAllText("Server.cfg"));
                    Console.WriteLine("Applying configuration file:");
                    Console.WriteLine(setup.ToString(true));
                    foreach (var topic in setup.Topics)
                    {
                        topics[topic.Key] = topic.Value;
                    }
                    foreach (var device in setup.DeviceTypes)
                    {
                        devices.Register(device.Type, device.Commands.ToArray());
                    }
                    foreach (var behavior in setup.Behaviors)
                    {
                        brain.Behave(behavior);
                    }
                }

                var server = new ReactiveListener(port);
                server.Connections.Subscribe(socket =>
                {
                    Console.WriteLine("New socket connected {0}", socket.GetHashCode());

                    var binary = new BinaryChannel(socket);
                    var message = new MessageChannel(binary);
                    var device = new TcpDevice(brain, message, Clock.Default);

                    connectedDevices.Add(device);
                    device.Disconnected += (sender, e) => socket.Dispose();
                    socket.Disconnected += (sender, e) =>
                        {
                            Console.WriteLine("Socket disconnected {0}", sender.GetHashCode());
                            connectedDevices.Remove(device);
                            device.Dispose();
                        };
                    socket.Disposed += (sender, e) =>
                        {
                            Console.WriteLine("Socket disposed {0}", sender.GetHashCode());
                            connectedDevices.Remove(device);
                            device.Dispose();
                        };
                });

                server.Start();

                Console.WriteLine("Define topic:");
                Console.WriteLine("  topic [void|bool|number|string] [name]");
                Console.WriteLine("Define device:");
                Console.WriteLine("  device [type] [comma-separated list of topic commands the device can receive]");
                Console.WriteLine("Define behavior:");
                Console.WriteLine("  behave [when then expression]");

                Console.WriteLine("Press Enter to exit");

                string line = null;
                while ((line = Console.ReadLine()) != "")
                {
                    if (line == Environment.NewLine)
                        return;

                    if (line.StartsWith("topic"))
                    {
                        var topic = TopicParser.Parse(line);
                        topics[topic.Item1] = topic.Item2;
                        Console.WriteLine("Registered topic '{0}' of type {1}", topic.Item1, topic.Item2);
                    }
                    else if (line.StartsWith("device"))
                    {
                        var device = DeviceParser.Parse(line);
                        devices.Register(device.Item1, device.Item2.ToArray());
                        Console.WriteLine("Registered device type '{0}' to receive commands {1}", device.Item1, string.Join(", ", device.Item2.Select(s => "'" + s + "'")));
                    }
                    else if (line.StartsWith("behave "))
                    {
                        try
                        {
                            brain.Behave(line.Substring(7));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed: {0}", e);
            }
        }
Esempio n. 25
0
 public DeviceExposer(ServiceClient serviceClient, DeviceRegistry deviceRegistry)
 {
     this.serviceClient  = serviceClient;
     this.deviceRegistry = deviceRegistry;
 }
Esempio n. 26
0
        public void Startup()
        {
            MqttApplicationMessage lastwill = new MqttApplicationMessage()
            {
                Topic   = $"{Global.mqtt_prefix}/status",
                Payload = Encoding.UTF8.GetBytes("offline"),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
                Retain = true
            };

            MqttClientOptionsBuilder options = new MqttClientOptionsBuilder()
                                               .WithTcpServer(Global.mqtt_server)
                                               .WithWillMessage(lastwill);

            if (!string.IsNullOrEmpty(Global.mqtt_username))
            {
                options = options
                          .WithCredentials(Global.mqtt_username, Global.mqtt_password);
            }

            ManagedMqttClientOptions manoptions = new ManagedMqttClientOptionsBuilder()
                                                  .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                                  .WithClientOptions(options.Build())
                                                  .Build();

            MqttClient = new MqttFactory().CreateManagedMqttClient();
            MqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate((e) =>
            {
                log.Debug("Connected");

                MqttDeviceRegistry = new DeviceRegistry()
                {
                    identifiers  = Global.mqtt_prefix,
                    name         = Global.mqtt_prefix,
                    sw_version   = $"EnergySmartBridge {Assembly.GetExecutingAssembly().GetName().Version}",
                    model        = "Water Heater Controller",
                    manufacturer = "EnergySmart"
                };

                // Clear cache so we publish config on next check-in
                connectedModules.Clear();

                log.Debug("Publishing controller online");
                PublishAsync($"{Global.mqtt_prefix}/status", "online");
            });
            MqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate((e) => log.Debug("Error connecting " + e.Exception.Message));
            MqttClient.DisconnectedHandler     = new MqttClientDisconnectedHandlerDelegate((e) => log.Debug("Disconnected"));

            MqttClient.StartAsync(manoptions);

            MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnAppMessage);

            // Subscribe to notifications for these command topics
            List <Topic> toSubscribe = new List <Topic>()
            {
                Topic.updaterate_command,
                Topic.mode_command,
                Topic.setpoint_command
            };

            toSubscribe.ForEach((command) => MqttClient.SubscribeAsync(
                                    new MqttTopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{command}").Build()));

            // Wait until shutdown
            trigger.WaitOne();

            log.Debug("Publishing controller offline");
            PublishAsync($"{Global.mqtt_prefix}/status", "offline");

            MqttClient.StopAsync();
        }