コード例 #1
0
ファイル: Kernel32.cs プロジェクト: psryland/rylogic_code
 public static void CtlCodeDecode(uint code, out EDeviceType device_type, out uint function, out EDeviceIoMethod method, out EDeviceAccess access)
 {
     device_type = (EDeviceType)((code >> 16) & 0xFFFF);
     access      = (EDeviceAccess)((code >> 14) & 0x3);
     function    = (code >> 2) & 0xFFF;
     method      = (EDeviceIoMethod)((code >> 0) & 0x3);
 }
コード例 #2
0
        public Fx2Device(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType = EDeviceType.Unknown)
        {
            if (usbDevice != null)
            {
                USBDevice = usbDevice;
            }
            if (usbProfile != null)
            {
                USBProfile = usbProfile;
            }
            DeviceType = deviceType;

            if (deviceType == EDeviceType.Unknown)
            {
                Console.WriteLine($"+ {this}");
            }

            if (deviceType == EDeviceType.DAC_SA || deviceType == EDeviceType.ADC_SA)
            {
                if (usbDevice != null)
                {
                    CyBulkEndPoint outEndpoint = usbDevice.EndPointOf(0x01) as CyBulkEndPoint;
                    CyBulkEndPoint inEndpoint  = usbDevice.EndPointOf(0x81) as CyBulkEndPoint;
                    avalonPacket = new AvalonPacket(outEndpoint, inEndpoint);
                }
                else
                {
                    avalonPacket = new MonoAvalonPacket(MonoDeviceHandle);
                }
            }
        }
コード例 #3
0
        public static byte[] GenerateByteArray(RawInputData rawInputData)
        {
            dynamic     dataObject = rawInputData;
            EDeviceType deviceType = RawInputWrapper.GetCustomDeviceType(rawInputData.Device);
            EEventType  eventType;

            byte[] ByteData = new byte[] { };
            switch (deviceType)
            {
            case EDeviceType.Keyboard:
                eventType = (dataObject.Keyboard.Flags.ToString() == "Down") ? EEventType.KeyPressed : EEventType.KeyReleased;
                int keyCode  = (dataObject.Keyboard.VirutalKey);
                int scanCode = (dataObject.Keyboard.ScanCode);
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)deviceType));
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)eventType));
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)keyCode));
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)scanCode));
                break;

            case EDeviceType.Joystick:
                int    size    = dataObject.Hid.ElementSize;
                byte[] content = dataObject.Hid.RawData;
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)deviceType));
                ByteData = ByteData.Combine(BitConverter.GetBytes((int)size));
                ByteData = ByteData.Combine(content);
                break;
            }

            return(ByteData.ToArray());
        }
コード例 #4
0
        private static Tuple <List <DeviceInfo>, DateTimeOffset> LoadDevices(Database db, SQLiteConnection conn)
        {
            // Insert some Devices and Collectors
            List <EDeviceType> device_types = new List <EDeviceType>(new EDeviceType[] {
                EDeviceType.Server,
                EDeviceType.System,
                EDeviceType.Workstation,
                EDeviceType.Generic,
                EDeviceType.Workstation,
                EDeviceType.Generic,
            });
            List <DeviceInfo> devices = new List <DeviceInfo>();
            DateTimeOffset    dt      = new DateTimeOffset(2018, 10, 11, 8, 9, 10, TimeSpan.FromHours(-6));

            for (int i = 0; i < device_types.Count; ++i)
            {
                EDeviceType type = device_types[i];
                DeviceInfo  di   = new DeviceInfo(type)
                {
                    DID = new DeviceID(i, $"Device{i:00}"), ipAddress = $"11.22.33.{i}"
                };
                db.AddDevice(di, dt, conn);
                devices.Add(di);
            }

            return(Tuple.Create(devices, dt));
        }
コード例 #5
0
        internal static IReadOnlyCollection <Panel> getAllPanels(EDeviceType deviceType)
        {
            List <Panel> panels = new List <Panel>();

            foreach (var controller in clients.Where(c => c.DeviceType == deviceType || deviceType == EDeviceType.UNKNOWN))
            {
                panels.AddRange(controller.Panels);
            }
            return(panels.AsReadOnly());
        }
コード例 #6
0
ファイル: EDeviceType.cs プロジェクト: gaybro8777/common
        public static bool IsValidCollector(this EDeviceType d, ECollectorType c)
        {
            bool is_collector = false;

            if (c_device_to_collectors.ContainsKey(d))
            {
                is_collector = c_device_to_collectors[d].Contains(c);
            }

            return(is_collector);
        }
コード例 #7
0
        private void NanoleafHandlerNode_PanelIDChanged(object sender, EventArgs e)
        {
            var d = sender as NanoleafDevice;

            if (d != null)
            {
                this.deviceType = d.DeviceType;
                this.panelId    = d.PanelID;
                this.setInstance();
            }
        }
コード例 #8
0
 public override AbstractUserControl MakeControl(EDeviceType type)
 {
     if (type == EDeviceType.Server)
     {
         return(new ServerUserControl());
     }
     else
     {
         return(new MachineUserControl());
     }
 }
コード例 #9
0
ファイル: DeviceFactory.cs プロジェクト: sjhill01/Plugin-SDK
        public DeviceFactory AsType(EDeviceType deviceType, int deviceSubType)
        {
            _device.TypeInfo = new TypeInfo()
            {
                ApiType = EApiType.Device,
                Type    = (int)deviceType,
                SubType = deviceSubType
            };

            return(this);
        }
コード例 #10
0
 public DeviceInfo(EDeviceType type)
 {
     m_device_id     = new DeviceID(-1, string.Empty);
     this.type       = type;
     ipAddress       = "0.0.0.0";
     username        = password = string.Empty;
     deleted         = false;
     collectors      = CollectorInfo.FromCollectorTypes(type.GetCollectors());
     driveNames      = new Dictionary <string, string>();
     monitoredDrives = new MonitoredDriveManager();
     groupID         = -1;
 }
コード例 #11
0
        public static List <ECollectorType> GetCollectors(this EDeviceType d)
        {
            List <ECollectorType> collectors = new List <ECollectorType>();

            foreach (ECollectorType c in Enum.GetValues(typeof(ECollectorType)))
            {
                List <EDeviceType> devices = c.GetDevices();
                if (devices.Contains(d))
                {
                    collectors.Add(c);
                }
            }
            return(collectors);
        }
コード例 #12
0
        /// <summary>
        /// Queries all of the device that are of the given type.
        /// </summary>
        /// <returns>The all devices of type.</returns>
        /// <param name="deviceType">Device type.</param>
        public List <IDevice> GetAllDevicesOfType(EDeviceType deviceType)
        {
            var ret = new List <IDevice>();

            foreach (var device in devices)
            {
                if (device.type == deviceType)
                {
                    ret.Add(device);
                }
            }

            return(ret);
        }
コード例 #13
0
        public Fx2Device(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType = EDeviceType.Unknown)
        {
            if (usbDevice != null)
            {
                USBDevice = usbDevice;
            }
            if (usbProfile != null)
            {
                USBProfile = usbProfile;
            }
            DeviceType = deviceType;

            if (deviceType == EDeviceType.Unknown)
            {
                Console.WriteLine($"DeviceAttached: {this}");
            }
        }
コード例 #14
0
 public void AddDevice(string name, EDeviceType type, string imei, string annotation)
 {
     if (string.IsNullOrWhiteSpace(name) == false)
     {
         _serwisContext.Devices.Add(new Device {
             Name       = name,
             Type       = type,
             Imei       = imei,
             Annotation = annotation
         });
         _serwisContext.SaveChanges();
     }
     else
     {
         MessageBox.Show(Messages.DevicesManagement_EmptyName);
     }
 }
コード例 #15
0
        /// <summary>
        /// DevicesModels are reified DeviceInfos, that is to say that devices first come into the application
        /// as pure data. It is our responsibility to inflate them into the correct DeviceModel.
        /// </summary>
        /// <returns>DeviceModel representation of a DeviceInfo</returns>
        public DeviceModel MakeDeviceModel()
        {
            EDeviceType type = GetNewDeviceType();
            var         di   = new DeviceInfo(type)
            {
                DID = new DeviceID(-1, GetDeviceName())
            };
            AbstractUserControlContext ctx = new AbstractUserControlContext()
            {
                Info = di
            };
            var dm = new DeviceModel
            {
                Type    = type,
                Control = MakeControl(type).Initialize(ctx),
                Info    = di,
                Name    = di.name
            };

            return(dm);
        }
コード例 #16
0
ファイル: EDeviceType.cs プロジェクト: psryland/rylogic_code
 /// <summary>The number of channels associated with this device type</summary>
 public static int ChannelCount(this EDeviceType dev)
 {
     return(dev switch
     {
         EDeviceType.SOCKET => 1,
         EDeviceType.SWITCH_CHANGE => 1,
         EDeviceType.GSM_UNLIMIT_SOCKET => 1,
         EDeviceType.SWITCH => 1,
         EDeviceType.THERMOSTAT => 1,
         EDeviceType.SOCKET_POWER => 1,
         EDeviceType.GSM_SOCKET => 1,
         EDeviceType.POWER_DETECTION_SOCKET => 1,
         EDeviceType.SOCKET_2 => 2,
         EDeviceType.GSM_SOCKET_2 => 2,
         EDeviceType.SWITCH_2 => 2,
         EDeviceType.SOCKET_3 => 3,
         EDeviceType.GSM_SOCKET_3 => 3,
         EDeviceType.SWITCH_3 => 3,
         EDeviceType.SOCKET_4 => 4,
         EDeviceType.GSM_SOCKET_4 => 4,
         EDeviceType.SWITCH_4 => 4,
         EDeviceType.CUN_YOU_DOOR => 4,
         _ => 0,
     });
コード例 #17
0
    public static Device Input(EDeviceType type)
    {
        WVR_DeviceType _type = WVR_DeviceType.WVR_DeviceType_Invalid;

        switch (type)
        {
        case EDeviceType.Head:
            _type = WVR_DeviceType.WVR_DeviceType_HMD;
            break;

        case EDeviceType.Dominant:
            _type = isLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Left : WVR_DeviceType.WVR_DeviceType_Controller_Right;
            break;

        case EDeviceType.NonDominant:
            _type = isLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Right : WVR_DeviceType.WVR_DeviceType_Controller_Left;
            break;

        default:
            break;
        }

        return(ChangeRole(_type));
    }
コード例 #18
0
        public static async Task <ExternalControlConnectionInfo> SetExternalControlStreaming(string ip, string port, string auth_token, EDeviceType deviceType)
        {
            ExternalControlConnectionInfo result = null;
            string address       = $"http://{ip}:{port}/api/v1/{auth_token}/effects";
            string contentString = "{\"write\": {\"command\": \"display\", \"animType\": \"extControl\", \"extControlVersion\": \"v2\"}}";

            var response = await put(address, contentString);

            switch (deviceType)
            {
            case EDeviceType.LightPanles:
                result = JsonConvert.DeserializeObject <ExternalControlConnectionInfo>(response.Content);
                break;

            case EDeviceType.Shapes:
            case EDeviceType.Canvas:
            case EDeviceType.Elements:
            case EDeviceType.Lines:
            case EDeviceType.Essentials:
            default:
                result = new ExternalControlConnectionInfo()
                {
                    StreamIPAddress = ip, StreamPort = 60222, StreamProtocol = "udp"
                };
                break;
            }
            return(result);
        }
コード例 #19
0
 public override AbstractUserControl MakeControl(EDeviceType type)
 {
     // Don't worry about the type--always make a System control
     return(new SystemUserControl());
 }
コード例 #20
0
 public override AbstractUserControl MakeControl(EDeviceType type)
 {
     // Don't worry about type--always create a generic device control
     return(new GenericDeviceUserControl());
 }
コード例 #21
0
ファイル: DeviceModel.cs プロジェクト: lkruljac/diplomskiV2
 public DeviceModel(string name, string id, EDeviceType type)
 {
     Name = name;
     Id   = id;
     Type = type;
 }
コード例 #22
0
        public BorIPDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");


            var ct = Cts.Token;

            Task.Run(() =>
            {
                TcpListener listener = BorIPCreateListener(BORIP_SERVERPORT);
                try
                {
                    listener.Start();
                    var addresses = Dns.GetHostAddresses(Dns.GetHostName())
                                    .Where(p => p.ToString().Contains('.'));
                    Console.WriteLine($"{BORIP_SERVERPORT}: {string.Join(" ", addresses)}");

                    CancellationTokenSource tcpCts = null;
                    while (!ct.IsCancellationRequested)
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        Console.WriteLine($"{BORIP_SERVERPORT}: accepted");

                        if (tcpCts != null)
                        {
                            tcpCts.Cancel();
                        }

                        tcpCts    = new CancellationTokenSource();
                        var tcpCt = tcpCts.Token;
                        Task.Run(() =>
                        {
                            BorIPClient borIPClient = new BorIPClient(client);
                            borIPClients.Add(borIPClient);
                            try
                            {
                                using (NetworkStream ns = client.GetStream())
                                    using (StreamReader sr = new StreamReader(ns, Encoding.ASCII))
                                        using (StreamWriter sw = new StreamWriter(ns, Encoding.ASCII))
                                        {
                                            BorIPWriteLine(sw, "DEVICE -");

                                            while (!tcpCt.IsCancellationRequested)
                                            {
                                                string str = sr.ReadLine();
                                                if (string.IsNullOrWhiteSpace(str))
                                                {
                                                    return;                                     // keep alive
                                                }
                                                Console.WriteLine($"{BORIP_SERVERPORT}: [in] {str.Trim()}");

                                                BorIPProcessInput(borIPClient, sw, str);
                                            }
                                        }
                            }
                            catch (Exception)
                            {
                                // nothing to do
                            }
                            finally
                            {
                                borIPClients.Remove(borIPClient);
                                Console.WriteLine($"{BORIP_SERVERPORT}: closed");
                            }
                        }, tcpCt);
                    }
                }
                catch (SocketException ex) when(ex.ErrorCode == 10004)
                {
                    // nothing to do
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{BORIP_SERVERPORT}: {ex.Message}");
                }
                finally
                {
                    listener.Stop();
                    //Console.WriteLine($"{BORIP_PORTNO}: listener stopped");
                }
            }, ct);


            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0))
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData    = new byte[maxPacketSize];
                        byte[] outData   = null;
                        int outDataPos   = 0;
                        byte[] borIPData = null;
                        int borIPDataPos = 0;

                        while (!ct.IsCancellationRequested &&
                               !(borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0)))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                if (borIPData == null)
                                {
                                    borIPData = new byte[4 + 4 * NUM_SAMPLES];
                                    borIPData[borIPDataPos++] = (byte)((RunningState == ERunningState.Start) ? 0x10 : 0x00);
                                    RunningState = ERunningState.Continued;
                                    borIPData[borIPDataPos++] = 0;
                                    borIPData[borIPDataPos++] = (byte)(sequence & 0xff);
                                    borIPData[borIPDataPos++] = (byte)((sequence >> 8) & 0xff);
                                }

                                while (outDataPos < outData.Length && borIPDataPos < borIPData.Length && inDataPos < xferLen)
                                {
                                    byte b = inData[inDataPos++];
                                    outData[outDataPos++]     = b;
                                    borIPData[borIPDataPos++] = b;
                                }

                                if (borIPDataPos == borIPData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(borIPData, borIPData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    sequence++;
                                    if (sequence == 0x10000)
                                    {
                                        sequence = 0;
                                    }

                                    borIPData    = null;
                                    borIPDataPos = 0;
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header == false)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(outData, outData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    remoteAddrList.Clear();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    //catch (Exception ex)
                    //{
                    //	Console.WriteLine($"BorIP: {ex.Message}");
                    //}
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }
コード例 #23
0
ファイル: Kernel32.cs プロジェクト: psryland/rylogic_code
 /// <summary>The native macros (CTL_CODE) used to encode commands passed to DeviceIoControl (see winioctl.h, bthioctl.h)</summary>
 public static uint CtlCodeEncode(EDeviceType device_type, uint function, EDeviceIoMethod method, EDeviceAccess access)
 {
     return(((uint)device_type << 16) | ((uint)access << 14) | (function << 2) | ((uint)method));
 }
コード例 #24
0
 public DiscoveredDevice(string ip, string name, EDeviceType deviceType) : this()
 {
     IP        = ip;
     Name      = name;
     DeviceTyp = deviceType;
 }
コード例 #25
0
        public ADCDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (ControlPortNo > 0 && controlClients.Count == 0)
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData  = new byte[maxPacketSize];
                        byte[] outData = null;
                        int outDataPos = 0;

                        while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                while (outDataPos < outData.Length && inDataPos < xferLen)
                                {
                                    outData[outDataPos++] = inData[inDataPos++];
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{dataPortNo}: {ex.Message}");
                    }
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }
コード例 #26
0
 public DevicesAttribute(EDeviceType device)
 {
     Devices = new List <EDeviceType>(new EDeviceType[] { device });
 }
コード例 #27
0
 public DevicesAttribute(EDeviceType device1, EDeviceType device2)
 {
     Devices = new List <EDeviceType>(new EDeviceType[] { device1, device2 });
 }
コード例 #28
0
        public DACDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.DAC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x02) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        if (ControlPortNo > 0 && controlClients.Count == 0)
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                        TcpClient client = null;
                        try
                        {
                            string remoteAddr;
                            if (ControlPortNo == 0)
                            {
                                remoteAddr = "127.0.0.1";
                            }
                            else
                            {
                                try
                                {
                                    remoteAddr = ((IPEndPoint)controlClients[0].Client.RemoteEndPoint).Address.ToString();
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                            client = new TcpClient(remoteAddr, dataPortNo);
                        }
                        catch (SocketException ex)
                        {
                            if (ex.ErrorCode == 10061)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }

                            throw ex;
                        }
                        Console.WriteLine($"{dataPortNo}: accepted",
                                          DeviceType,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Address,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Port);

                        NetworkStream ns = client.GetStream();
                        try
                        {
                            int maxPacketSize;
                            if (USBDevice != null)
                            {
                                maxPacketSize = endpoint2.MaxPktSize;
                            }
                            else
                            {
                                maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x02);
                            }
                            byte[] inData  = new byte[64 * 1024];
                            byte[] outData = new byte[maxPacketSize - 16]; // Some PCs cannot send 1024 bytes
                            int outDataPos = 0;

                            while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                            {
                                int resSize = ns.Read(inData, 0, inData.Length);
                                if (resSize == 0)
                                {
                                    break;
                                }

                                int inDataLen = resSize;
                                int inDataPos = 0;
                                while (!ct.IsCancellationRequested && inDataPos < inDataLen)
                                {
                                    while (outDataPos < outData.Length && inDataPos < inDataLen)
                                    {
                                        outData[outDataPos++] = inData[inDataPos++];
                                    }

                                    if (outDataPos == outData.Length)
                                    {
                                        int xferLen = outData.Length;
                                        bool ret    = false;
                                        if (USBDevice != null)
                                        {
                                            ret = endpoint2.XferData(ref outData, ref xferLen);
                                        }
                                        else
                                        {
                                            ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x02, outData, outData.Length, out xferLen, TIMEOUT) == 0;
                                        }
                                        if (ret == false || xferLen == 0)
                                        {
                                            break;
                                        }
                                        if (xferLen != outData.Length)
                                        {
                                            Console.WriteLine($"{dataPortNo}: the response size {xferLen} not equal to the requested size {outData.Length}");
                                        }
                                        outDataPos = 0;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // nothing to do
                        }
                        finally
                        {
                            ns.Close();
                            client.Close();
                            Console.WriteLine($"{dataPortNo}: closed");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{dataPortNo}: {ex.Message}");
                }
            }, ct);
        }
コード例 #29
0
ファイル: EDeviceType.cs プロジェクト: gaybro8777/common
 public static bool IsWindowsMachine(this EDeviceType d)
 {
     return(d == EDeviceType.Server || d == EDeviceType.Workstation);
 }
コード例 #30
0
        public static void StartDiscoveryTask()
        {
            if (discoveryThreadRunning || discoverTask != null)
            {
                return;
            }

            discoveryThreadRunning = true;
            discoverTask           = new Task(() =>
            {
                IPAddress SSDP_IP = new IPAddress(new byte[] { 239, 255, 255, 250 });
                int SSDP_PORT     = 1900;
                var client        = new UdpClient();
                try
                {
                    client.Client.Bind(new IPEndPoint(IPAddress.Any, SSDP_PORT));
                    foreach (IPAddress IP in IPs)
                    {
                        client.JoinMulticastGroup(SSDP_IP, IP);
                    }
                    client.MulticastLoopback = true;
                    while (discoveryThreadRunning)
                    {
                        log.Debug("Discover started");
                        NanoleafPlugin.DiscoverState = "Started";
                        var result = client.ReceiveAsync().GetAwaiter().GetResult();
                        NanoleafPlugin.DiscoverState = "Result Received";
                        string message = Encoding.Default.GetString(result.Buffer);
                        if (message.Contains("nl-devicename"))
                        {
                            if (discoveredDevices.Any(d => d.IP.Equals(result.RemoteEndPoint.Address.ToString())))
                            {
                                return;
                            }
                            var array        = message.Replace("\r\n", "|").Split('|');
                            EDeviceType type = EDeviceType.UNKNOWN;
                            switch (array.FirstOrDefault(s => s.StartsWith("NT"))?.Replace("NT: ", ""))
                            {
                            case "nanoleaf:nl22":
                            case "Nanoleaf_aurora:light":
                                type = EDeviceType.LightPanles;
                                break;

                            case "nanoleaf:nl29":
                                type = EDeviceType.Canvas;
                                break;

                            case "nanoleaf:nl42":
                                type = EDeviceType.Shapes;
                                break;

                            case "nanoleaf:nl45":
                                type = EDeviceType.Essentials;
                                break;

                            case "nanoleaf:nl52":
                                type = EDeviceType.Elements;
                                break;

                            case "nanoleaf:nl59":
                                type = EDeviceType.Lines;
                                break;
                            }
                            string name = array.FirstOrDefault(s => s.StartsWith("nl-devicename"))?.Replace("nl-devicename: ", "");
                            var device  = new DiscoveredDevice(result.RemoteEndPoint.Address.ToString(), name, type);;
                            discoveredDevices.Add(device);
                            deviceDiscovered?.Invoke(null, new DiscoveredEventArgs(device));
                        }
                        log.Debug("Discover passed");
                        NanoleafPlugin.DiscoverState = "Passed";
                    }
                }
                catch (Exception e)
                {
                    log.Warn("The Socket is already in use." + Environment.NewLine +
                             "there Are a feaw things to fix this issue." + Environment.NewLine +
                             "Open the CMD.exe and perform the command \"netstat -a -n -o\"" + Environment.NewLine +
                             "Now you see all open Ports" + Environment.NewLine +
                             "find TCP [the IP address]:[port number] .... #[target_PID]# (ditto for UDP)" + Environment.NewLine +
                             "Open TaskManager and Klick on Processes" + Environment.NewLine +
                             "Enable \"PID\" column by going to: View > Select Columns > Check the box for PID" + Environment.NewLine +
                             "Find the PID of interest and \"END PROCESS\"" + Environment.NewLine + Environment.NewLine +
                             "Common Programs are Spotify or the SSPDSRF-Service"
                             , e);
                }
                log.Debug("Discover stopped");
                NanoleafPlugin.DiscoverState = "Stopped";
                client.Close();
                discoveryThreadRunning = false;
            }, token);
            discoverTask.Start();
        }