示例#1
0
        public CreateOrEditViewModel Create(int?id)
        {
            if (id == null)
            {
                return new CreateOrEditViewModel()
                       {
                           CSharpClassNameOptions = this.GetCSharpClassNameOptions()
                       }
            }
            ;

            Microcontroller microcontroller = this.RequestHandler.Storage.GetRepository <IMicrocontrollerRepository>().WithKey((int)id);

            return(new CreateOrEditViewModel()
            {
                Id = microcontroller.Id,
                Name = microcontroller.Name,
                UrlTemplate = microcontroller.UrlTemplate,
                ViewName = microcontroller.ViewName,
                CSharpClassName = microcontroller.CSharpClassName,
                CSharpClassNameOptions = this.GetCSharpClassNameOptions(),
                UseCaching = microcontroller.UseCaching,
                Position = microcontroller.Position
            });
        }
示例#2
0
        public async Task <IActionResult> Create([Bind("MicrocontrollerID,MicrocontrollerName")] Microcontroller microcontroller)
        {
            microcontroller.UserID = Convert.ToInt32(this.User.FindFirstValue(ClaimTypes.NameIdentifier));

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                byte[] val = new byte[4];
                rng.GetBytes(val);

                int value = BitConverter.ToInt32(val, 0);

                string _AuthKey = hashData.ComputeHashSha512(value.ToString(), microcontroller.UserID.ToString());
                _AuthKey = _AuthKey.Substring(0, 12);
                microcontroller.APIauthKey = _AuthKey;
            }


            if (ModelState.IsValid)
            {
                _context.Add(microcontroller);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(microcontroller));
        }
示例#3
0
 private static void Blink(int pin, int delay)
 {
     Microcontroller.DigitalWrite(Microcontroller.High, pin);
     Delay(delay);
     Microcontroller.DigitalWrite(Microcontroller.Low, pin);
     Delay(delay);
 }
示例#4
0
        public async Task <IActionResult> Edit(int id, [Bind("MicrocontrollerID,MicrocontrollerName,isPrivate,UserID")] Microcontroller microcontroller)
        {
            if (id != microcontroller.MicrocontrollerID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(microcontroller);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MicrocontrollerExists(microcontroller.MicrocontrollerID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserID"] = new SelectList(_context.Users, "UserID", "Name", microcontroller.UserID);
            return(View(microcontroller));
        }
        public IActionResult Invoke(IRequestHandler requestHandler, Microcontroller microcontroller, IEnumerable <KeyValuePair <string, string> > parameters)
        {
            string  url       = string.Format("/{0}", requestHandler.HttpContext.GetRouteValue("url"));
            dynamic viewModel = null;

            SerializedObject serializedPage = requestHandler.Storage.GetRepository <ISerializedObjectRepository>().WithCultureIdAndUrlPropertyStringValue(
                CultureManager.GetCurrentCulture(requestHandler.Storage).Id, url
                );

            if (serializedPage != null)
            {
                viewModel = this.CreateViewModel(requestHandler, microcontroller, serializedPage);
            }

            else
            {
                Object page = requestHandler.Storage.GetRepository <IObjectRepository>().WithUrl(url);

                if (page != null)
                {
                    viewModel = this.CreateViewModel(requestHandler, microcontroller, page);
                }
            }

            if (viewModel != null)
            {
                return((requestHandler as Platformus.Barebone.Frontend.Controllers.ControllerBase).View(microcontroller.ViewName, viewModel));
            }

            return(null);
        }
 public void Add(Microcontroller microcontroller)
 {
     if (!Contains(microcontroller.DeviceId))
     {
         this._mqqtSvcDbContext.Microcontrollers.Add(this._microcontrollerMapper.Map(microcontroller));
         this._mqqtSvcDbContext.SaveChanges();
     }
 }
 public MicrocontrollerViewModel Create(Microcontroller microcontroller)
 {
     return(new MicrocontrollerViewModel()
     {
         Id = microcontroller.Id,
         Name = microcontroller.Name,
         Position = microcontroller.Position
     });
 }
示例#8
0
 public MicrocontrollerEntity Map(Microcontroller mc)
 {
     return(new MicrocontrollerEntity
     {
         DeviceId = mc.DeviceId,
         Powered = mc.Powered,
         Temperature = mc.Temperature
     });
 }
示例#9
0
 public AutonomousBehaviour(IMU440 IMU1, Microcontroller uC1, PositionTracker pos1, ThrustManager lev1, log ERRORLOG)
 {
     // TODO: Complete member initialization
     this.IMU      = IMU1;
     this.uC       = uC1;
     this.pos      = pos1;
     this.lev      = lev1;
     this.ERRORLOG = ERRORLOG;
 }
示例#10
0
        private dynamic CreateViewModel(IRequestHandler requestHandler, Microcontroller microcontroller)
        {
            ViewModelBuilder viewModelBuilder = new ViewModelBuilder();

            foreach (DataSource dataSource in requestHandler.Storage.GetRepository <IDataSourceRepository>().FilteredByMicrocontrollerId(microcontroller.Id))
            {
                viewModelBuilder.BuildProperty(dataSource.Code, this.CreateDataSourceViewModel(requestHandler, dataSource));
            }

            return(viewModelBuilder.Build());
        }
        public void Delete(Microcontroller microcontroller)
        {
            var entry = _mqqtSvcDbContext.Microcontrollers.Where(
                p => p.DeviceId == microcontroller.DeviceId).FirstOrDefault <MicrocontrollerEntity>();

            if (entry != null)
            {
                _mqqtSvcDbContext.Entry(entry).State = EntityState.Deleted;
                _mqqtSvcDbContext.SaveChanges();
            }
        }
示例#12
0
        public override void AddRemoteControlling(PeerConnection Connection)
        {
            // Creating instance of system component to manipulate of equipment
            FirmwareLoader = Quartus.GetInstance();
            InputEmulator  = Microcontroller.Create();


            // Adding data channel for loading firmware and controling equipment
            Connection.DataChannelAdded += DataChannelAddedHandler;

            //Console.WriteLine("End of GetMedia which initialized UserCell in Thread {0}", Thread.CurrentThread.ManagedThreadId);
        }
示例#13
0
 private async void CommandChannelHandler(byte[] command)
 {
     try
     {
         Console.WriteLine("Received command {0}", ASCIIEncoding.ASCII.GetString(command));
         Console.WriteLine(Microcontroller.WasOpened());
         await InputEmulator.SendCTP_CommandAsync(JsonSerializer.Deserialize <CTP_packet>(command));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
示例#14
0
        public IActionResult Invoke(IRequestHandler requestHandler, Microcontroller microcontroller, IEnumerable <KeyValuePair <string, string> > parameters)
        {
            string url = string.Format("/{0}", requestHandler.HttpContext.GetRouteValue("url"));

            if (microcontroller.UseCaching)
            {
                return(requestHandler.HttpContext.RequestServices.GetService <ICache>().GetPageActionResultWithDefaultValue(
                           url + requestHandler.HttpContext.Request.QueryString, () => this.GetActionResult(requestHandler, microcontroller, parameters, url)
                           ));
            }

            return(this.GetActionResult(requestHandler, microcontroller, parameters, url));
        }
        public async Task <Microcontroller> GetAsync(int id, string authKey)
        {
            Microcontroller microcontroller = await _context.Microcontrollers
                                              .AsNoTracking()
                                              .Include(s => s.Readings)
                                              .ThenInclude(s => s.ReadingValues)
                                              .FirstOrDefaultAsync(m => m.MicrocontrollerID == id);

            if (authKey == microcontroller.APIauthKey)
            {
                return(microcontroller);
            }

            return(null);
        }
        public Microcontroller Map(CreateOrEditViewModel createOrEdit)
        {
            Microcontroller microcontroller = new Microcontroller();

            if (createOrEdit.Id != null)
            {
                microcontroller = this.RequestHandler.Storage.GetRepository <IMicrocontrollerRepository>().WithKey((int)createOrEdit.Id);
            }

            microcontroller.Name            = createOrEdit.Name;
            microcontroller.UrlTemplate     = createOrEdit.UrlTemplate;
            microcontroller.ViewName        = createOrEdit.ViewName;
            microcontroller.CSharpClassName = createOrEdit.CSharpClassName;
            microcontroller.Position        = createOrEdit.Position;
            return(microcontroller);
        }
        public async Task <ActionResult <Reading> > PostReading(int ID, string authKey, [FromBody] Reading reading)
        {
            Microcontroller microcontroller = await _context.Microcontrollers
                                              .AsNoTracking()
                                              .Include(s => s.Readings)
                                              .FirstOrDefaultAsync(m => m.MicrocontrollerID == ID);

            Reading _reading = new Reading {
                Date_time = DateTime.Now, MicrocontrollerID = ID, Microcontroller = microcontroller, ReadingValues = reading.ReadingValues
            };

            _reading.Microcontroller = microcontroller;

            microcontroller.Readings.Add(_reading);

            foreach (ReadingValue readingValue in _reading.ReadingValues)
            {
                _context.ReadingValues.Add(readingValue);
            }

            _context.Entry(microcontroller).State = EntityState.Modified;
            _context.Readings.Add(_reading);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ReadingExists(ID))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            if (authKey == microcontroller.APIauthKey)
            {
                return(CreatedAtAction("GetReading", new { id = ID }, reading));
            }

            return(null);
        }
示例#18
0
文件: Leveler.cs 项目: NGCP/UUV
        public ThrustManager(IMU440 nav, Microcontroller u, PositionTracker p, log loger)
        {
            //Purpose: Constructor for thrustManager
            //Inputs: the IMU object, and the microcontroller object, which each have the serial communication functions within.
            lg           = loger;
            navigation   = nav;
            position     = p;
            uCon         = u;
            desiredPitch = 0;
            desiredRoll  = 0;
            desiredDepth = -0.5;
            desiredYaw   = 0;
            desiredSurge = 0;
            desiredSway  = 0;
            Tp           = 0; //pitch
            Tr           = 0; //roll
            Ty           = 0; //yaw
            Td           = 0; //depth
            Tsu          = 0; //surge
            Tsw          = 0; //sway

            uCon.sensorRequest();

            //gots to tune these pids
            ptch  = new PID(0, 0, 0, 60.0, -60.0, 40, -40, getActualPitch, getDesiredPitch, computeTp);
            rll   = new PID(.5, 0, .4, 60.0, -60.0, 40, -40, getActualRoll, getDesiredRoll, computeTr);
            surge = new PID(0.6, 0, 0, 3, -3, 75, -75, getActualSurge, getDesiredSurge, computeTsu);
            sway  = new PID(0.6, 0, 0, 3, -3, 75, -75, getActualSway, getDesiredSway, computeTsw);
            depth = new PID(0.8, 0.1, .8, 0, -9, 75, -75, getActualDepth, getDesiredDepth, computeTd);
            yaw   = new PID(0, 0, 0, 180, -180, 40, -40, getActualYaw, getDesiredYaw, computeTy);


            ptch.Enable();
            rll.Enable();
            //commented cause we dont have everything worked out for yaw, and i haven't written something to calculate velocity
            surge.Enable();
            sway.Enable();
            depth.Enable();
            yaw.Enable();

            backgroundThrustManager = new Thread(new ThreadStart(levelingTask));
            backgroundThrustManager.IsBackground = true;
            backgroundThrustManager.Start();
        }
        public IActionResult TryHandle(IRequestHandler requestHandler, string url)
        {
            IMicrocontrollerResolver microcontrollerResolver = requestHandler.HttpContext.RequestServices.GetService <IMicrocontrollerResolver>();
            Microcontroller          microcontroller         = microcontrollerResolver.GetMicrocontroller(requestHandler, url);

            if (microcontroller == null)
            {
                return(null);
            }

            IMicrocontroller microcontrollerInstance = this.GetMicrocontrollerInstance(microcontroller);

            if (microcontrollerInstance == null)
            {
                return(null);
            }

            return(microcontrollerInstance.Invoke(requestHandler, microcontroller, microcontrollerResolver.GetParameters(microcontroller.UrlTemplate, url)));
        }
示例#20
0
        //
        // Constructors
        //
        #region Constructors

        /// <summary>
        /// Initializes the members of this instance.
        /// </summary>
        static Globals()
        {
            _database        = new SQLServerDatabase(@"Gamer-PC\SQLEXPRESS", "HCS");
            _account         = null;
            _kwh             = 0;
            _microcontroller = null;

            /*bool flag = false;
             * foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
             * {
             *  try
             *  {
             *      _database = new SQLServerDatabase(css.ConnectionString);
             *      flag = true;
             *      break;
             *  }
             *  catch { }
             * }
             * if (!flag) throw new ArgumentException("No connection string was valid.");*/
        }
示例#21
0
 public static bool LoadMicrocontroller(string portName = "")
 {
     if (portName == "")
     {
         if (System.IO.File.Exists("port.txt"))
         {
             _microcontroller = new Microcontroller(System.IO.File.ReadAllText("port.txt"), 9600);
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         _microcontroller = new Microcontroller(portName, 9600);
         System.IO.File.WriteAllText("port.txt", portName);
         return(true);
     }
 }
示例#22
0
 public void AddNew(Microcontroller employee)
 {
     throw new NotImplementedException();
 }
示例#23
0
 private static void Init(int pin)
 {
     Microcontroller.PinMode(Microcontroller.Output, pin);
 }
示例#24
0
 public async Task InitAsync()
 {
     Microcontroller.Initialize(mcu);
     await mcu.ExecuteAction(Init, pin);
 }
示例#25
0
        private void readBoardInfos()
        {
            this.micros_list = new List <Microcontroller>();

            XmlDocument xml_doc = new XmlDocument();

            try
            {
                xml_doc.Load(µC_file_settings_name);
            }
            catch (Exception e) {
                MessageBox.Show("XML Error: " + e.Message);
            }

            XmlNodeList xml_boards  = xml_doc.GetElementsByTagName("microcontroller");
            int         boards_size = xml_boards.Count;

            Microcontroller micro;

            foreach (XmlNode a_xml_board in xml_boards)
            {
                micro = new Microcontroller(a_xml_board.Attributes[0].Value);
                micro.setFamily(a_xml_board.Attributes[1].Value);
                micro.setManufacturer(a_xml_board.Attributes[2].Value);

                //Architecture
                string size_archi_str = a_xml_board.ChildNodes[0].Attributes[0].Value;
                string unit_archi_str = a_xml_board.ChildNodes[0].Attributes[1].Value;
                micro.setArchitecture(Int32.Parse(size_archi_str), unit_archi_str);

                //Processor
                string speed_proc_str = a_xml_board.ChildNodes[1].Attributes[0].Value;
                string unit_proc_str  = a_xml_board.ChildNodes[1].Attributes[1].Value;
                micro.setProcessor(Int32.Parse(speed_proc_str), unit_proc_str);

                //Ram Memory
                string ram_type = a_xml_board.ChildNodes[2].Attributes[0].Value;
                string ram_size = a_xml_board.ChildNodes[2].Attributes[1].Value;
                string ram_unit = a_xml_board.ChildNodes[2].Attributes[2].Value;
                micro.setRamMemory(ram_type, Int32.Parse(ram_size), ram_unit);

                //Program Memory
                string prog_type = a_xml_board.ChildNodes[3].Attributes[0].Value;
                string prog_size = a_xml_board.ChildNodes[3].Attributes[1].Value;
                string prog_unit = a_xml_board.ChildNodes[3].Attributes[2].Value;
                micro.setProgramMemory(prog_type, Int32.Parse(prog_size), prog_unit);

                //Data Memory
                string data_type = a_xml_board.ChildNodes[4].Attributes[0].Value;
                string data_size = a_xml_board.ChildNodes[4].Attributes[1].Value;
                string data_unit = a_xml_board.ChildNodes[4].Attributes[2].Value;
                micro.setDataMemory(data_type, Int32.Parse(data_size), data_unit);

                //Read Digital pins and save
                micro.max_digital_pin = Int32.Parse(a_xml_board.ChildNodes[5].Attributes[0].Value);
                int N_Digit_Pins = a_xml_board.ChildNodes[5].ChildNodes.Count;
                for (int i = 0; i < N_Digit_Pins; i++)
                {
                    string pin_address = a_xml_board.ChildNodes[5].ChildNodes[i].Attributes[0].Value;
                    string pin_type    = a_xml_board.ChildNodes[5].ChildNodes[i].Attributes[1].Value;
                    micro.pins_list_digital.Add(new IOPin(pin_address, pin_type));
                }

                //Read Analog pins and save
                micro.max_analog_pin = Int32.Parse(a_xml_board.ChildNodes[6].Attributes[0].Value);
                int N_Analog_Pins = a_xml_board.ChildNodes[6].ChildNodes.Count;
                for (int i = 0; i < N_Analog_Pins; i++)
                {
                    string pin_address = a_xml_board.ChildNodes[6].ChildNodes[i].Attributes[0].Value;
                    string pin_type    = a_xml_board.ChildNodes[6].ChildNodes[i].Attributes[1].Value;
                    micro.pins_list_analog.Add(new IOPin(pin_address, pin_type));
                }

                micro.set_SC_header_path(a_xml_board.ChildNodes[7].ChildNodes[0].Attributes[0].Value);
                micro.set_SC_read_pins_path(a_xml_board.ChildNodes[7].ChildNodes[1].Attributes[0].Value);
                micro.set_SC_write_pins_path(a_xml_board.ChildNodes[7].ChildNodes[2].Attributes[0].Value);
                micro.set_SC_pinMode_config_path(a_xml_board.ChildNodes[7].ChildNodes[3].Attributes[0].Value);
                micro.set_SC_timer_definition_path(a_xml_board.ChildNodes[7].ChildNodes[4].Attributes[0].Value);
                micro.set_SC_readInMemory_path(a_xml_board.ChildNodes[7].ChildNodes[5].Attributes[0].Value);
                micro.set_SC_writeInMemory_path(a_xml_board.ChildNodes[7].ChildNodes[6].Attributes[0].Value);

                this.micros_list.Add(micro);
            }
        }
示例#26
0
        private IActionResult GetActionResult(IRequestHandler requestHandler, Microcontroller microcontroller, IEnumerable <KeyValuePair <string, string> > parameters, string url)
        {
            dynamic viewModel = this.CreateViewModel(requestHandler, microcontroller);

            return((requestHandler as Platformus.Barebone.Frontend.Controllers.ControllerBase).View(microcontroller.ViewName, viewModel));
        }
示例#27
0
        public static void Initialize(SensorLoggerContext context)
        {
            context.Database.EnsureCreated();

            if (context.Microcontrollers.Any())
            {
                return;   // DB has been seeded
            }

            var microcontrollers = new Microcontroller[]
            {
                new Microcontroller {
                    MicrocontrollerName = "Controller 1 med temperatur og fugtmaaler"
                },
                new Microcontroller {
                    MicrocontrollerName = "Controller 2 med temperaturmaaler"
                },
                new Microcontroller {
                    MicrocontrollerName = "Controller 3 med lysmaaler"
                }
            };

            foreach (Microcontroller s in microcontrollers)
            {
                context.Microcontrollers.Add(s);
            }
            //context.SaveChanges();

            var readings = new Reading[]
            {
                new Reading {
                    MicrocontrollerID = 1, ReadingID = 1, Date_time = DateTime.Parse("2020-09-01 7:24:37")
                },
                new Reading {
                    MicrocontrollerID = 2, ReadingID = 2, Date_time = DateTime.Parse("2020-12-03 9:11:42")
                },
                new Reading {
                    MicrocontrollerID = 2, ReadingID = 3, Date_time = DateTime.Parse("2020-01-11 1:53:26")
                },
                new Reading {
                    MicrocontrollerID = 3, ReadingID = 4, Date_time = DateTime.Parse("2020-11-03 3:36:51")
                },
                new Reading {
                    MicrocontrollerID = 3, ReadingID = 5, Date_time = DateTime.Parse("2020-03-02 8:34:12")
                }
            };

            foreach (Reading c in readings)
            {
                context.Readings.Add(c);
            }
            //context.SaveChanges();

            var readingValues = new ReadingValue[]
            {
                new ReadingValue {
                    ReadingValueID = 1, ReadingID = 1, Value = 23, ValueType = "C"
                },
                new ReadingValue {
                    ReadingValueID = 2, ReadingID = 1, Value = 67, ValueType = "Procent"
                },

                new ReadingValue {
                    ReadingValueID = 3, ReadingID = 2, Value = 25, ValueType = "C"
                },

                new ReadingValue {
                    ReadingValueID = 4, ReadingID = 3, Value = 21, ValueType = "C"
                },

                new ReadingValue {
                    ReadingValueID = 5, ReadingID = 4, Value = 1032, ValueType = "LUX"
                },

                new ReadingValue {
                    ReadingValueID = 6, ReadingID = 5, Value = 21032, ValueType = "LUX"
                }
            };

            foreach (ReadingValue e in readingValues)
            {
                context.ReadingValues.Add(e);
            }
            //context.SaveChanges();
        }
示例#28
0
        static private async Task StartStend()
        {
            var             autoEvent        = new AutoResetEvent(false);
            bool            video_translator = true;
            bool            file_created     = false;
            FileStream      file             = null;
            Quartus         quartus          = Quartus.GetInstance();
            Microcontroller arduino          = Microcontroller.Create();

            if (video_translator)
            {
                // Asynchronously retrieve a list of available video capture devices (webcams).
                var deviceList = await DeviceVideoTrackSource.GetCaptureDevicesAsync();


                // For example, print them to the standard output
                foreach (var device in deviceList)
                {
                    Console.WriteLine($"Found webcam {device.name} (id: {device.id})");
                }
            }

            // Create a new peer connection automatically disposed at the end of the program
            var pc = new PeerConnection();
            // Initialize the connection with a STUN server to allow remote access
            var config = SystemConfiguration.PeerConnectionSettings;


            await pc.InitializeAsync(config);

            Console.WriteLine("Peer connection initialized.");
            //var chen = await pc.AddDataChannelAsync("sendDataChannel", true, true, cancellationToken: default);
            Console.WriteLine("Opening local webcam...");


            // pc - PeerConnection object
            Transceiver                videoTransceiver = null;
            VideoTrackSource           videoTrackSource = null;
            LocalVideoTrack            localVideoTrack  = null;
            LocalVideoDeviceInitConfig c = new LocalVideoDeviceInitConfig();

            await VideoDeviceSelection();

            videoTrackSource = await Camera.CreateAsync(SystemConfiguration.VideoDeviceSettings);


            WebSocketSharp.WebSocket signaling = new WebSocketSharp.WebSocket(CreateSignalingServerUrl(), "id_token", "alpine");
            pc.LocalSdpReadytoSend += (SdpMessage message) =>
            {
                //Console.WriteLine(SdpMessage.TypeToString(message.Type));
                Console.WriteLine(message.Content);
                //Console.WriteLine(HttpUtility.JavaScriptStringEncode(message.Content));
                Console.WriteLine("Sdp offer to send: {\"data\":{\"description\":{\"type\":\"" + SdpMessage.TypeToString(message.Type) + "\",\"sdp\":\"" + HttpUtility.JavaScriptStringEncode(message.Content) + "\"}}}");
                signaling.Send(message.ToABJson());
            };

            pc.RenegotiationNeeded += () =>
            {
                Console.WriteLine("Regotiation needed");
                bool OfferCreated = pc.CreateOffer();
                Console.WriteLine("OfferCreated? {0}", OfferCreated);
            };
            pc.DataChannelAdded += (DataChannel channel) =>
            {
                Console.WriteLine("Added data channel ID: {0}, Label: {1}; Reliable: {2}, Ordered: {3}", channel.ID, channel.Label, channel.Reliable, channel.Ordered);

                if (channel.Label == "sendDataChannel")
                {
                    channel.MessageReceived += (byte[] mess) => {
                        try
                        {
                            CTP_packet command = JsonSerializer.Deserialize <CTP_packet>(mess);
                            Console.WriteLine(arduino.SendCTP_Command(command));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    };
                }
                else
                {
                    if (file_created == false)
                    {
                        file         = new FileStream(channel.Label, FileMode.Append);
                        file_created = true;
                    }
                    channel.MessageReceived += async(byte[] mess) =>
                    {
                        // Console.WriteLine(System.Text.Encoding.Default.GetString(mess));
                        if (mess.Length == 3 && System.Text.Encoding.Default.GetString(mess) == "EOF")
                        {
                            string file_name = file.Name;
                            file.Close();
                            string t = await quartus.RunQuartusCommandAsync($"quartus_pgm -m jtag –o \"p;{file_name}@1\"");

                            File.Delete(file_name);
                            file_created = false;
                        }
                        else
                        {
                            WriteFileSegment(mess, file);
                        }
                    };
                }

                channel.StateChanged += () =>
                {
                    Console.WriteLine("State change: {0}", channel.State);
                };
            };

            pc.IceCandidateReadytoSend += (IceCandidate candidate) =>
            {
                //Console.WriteLine("Content: {0}, SdpMid: {1}, SdpMlineIndex: {2}", candidate.Content, candidate.SdpMid, candidate.SdpMlineIndex);
                try
                {
                    Console.WriteLine("Candidate to send: Content: {0}, SdpMid: {1}, SdpMlineIndex: {2}", candidate.Content, candidate.SdpMid, candidate.SdpMlineIndex);
                    signaling.Send(candidate.ToABJson());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error to send local ice candidate");
                }
            };
            //videoTrackSource.I420AVideoFrameReady += (frame) =>
            //{
            //    Console.WriteLine("Argb32 frame ready. {0} : {1}", frame.width, frame.height);
            //    Console.WriteLine("DataA: {0}, DataU: {1}, DataV: {2}, DataY: {3}", Marshal.SizeOf(frame.dataA),
            //                        Marshal.SizeOf(frame.dataU),
            //                        Marshal.SizeOf(frame.dataV),
            //                        Marshal.SizeOf(frame.dataY));
            //};

            signaling.OnMessage += async(sender, message) =>
            {
                (string header, string correct_message) = message.Data.DivideHeaderAndOriginalJSON();
                Console.WriteLine("Correct message: {0}", correct_message);
                Console.WriteLine("Header: {0}", header);
                if (header == "{\"data\":{\"getRemoteMedia\":" && correct_message == "true")
                {
                    Console.WriteLine("Create local video track...");
                    var trackSettings = new LocalVideoTrackInitConfig {
                        trackName = "webcam_track"
                    };
                    localVideoTrack = LocalVideoTrack.CreateFromSource(videoTrackSource, new LocalVideoTrackInitConfig {
                        trackName = "webcam_track"
                    });
                    Console.WriteLine("Create video transceiver and add webcam track...");
                    TransceiverInitSettings option = new TransceiverInitSettings();
                    option.Name      = "webcam_track";
                    option.StreamIDs = new List <string> {
                        "webcam_name"
                    };
                    videoTransceiver = pc.AddTransceiver(MediaKind.Video, option);
                    videoTransceiver.DesiredDirection = Transceiver.Direction.SendOnly;
                    videoTransceiver.LocalVideoTrack  = localVideoTrack;

                    bool OfferCreated = pc.CreateOffer();
                    Console.WriteLine("OfferCreated? {0}", OfferCreated);
                }
                //Console.WriteLine(message.Data);
                if (header.IndexOf("candidate") != -1 && correct_message != "null")
                {
                    try
                    {
                        var candidate = JsonSerializer.Deserialize <ICEJavaScriptNotation>(correct_message);
                        Console.WriteLine("Content of ice: {0}, SdpMid: {1}, SdpMLineIndex: {2}", candidate.candidate, candidate.sdpMid, candidate.sdpMLineIndex);
                        pc.AddIceCandidate(candidate.ToMRNetCoreNotation());
                        Console.WriteLine("Deserialized by ice_candidate");
                        //return;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Could not deserialize as ice candidate");
                    }
                }

                if (header.IndexOf("description") != -1)
                {
                    try
                    {
                        SdpMessage received_description = JsonSerializer.Deserialize <SDPJavaScriptNotation>(correct_message).ToMRNetCoreNotation();
                        await pc.SetRemoteDescriptionAsync(received_description);

                        if (received_description.Type == SdpMessageType.Offer)
                        {
                            bool res = pc.CreateAnswer();
                            Console.WriteLine("Answer created? {0}", res);
                        }
                        Console.WriteLine("Deserialized by sdp_message");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Could not deserialize as sdp message");
                    }
                }
            };


            pc.Connected += () =>
            {
                Console.WriteLine("Connected");
            };
            pc.IceStateChanged += (IceConnectionState newState) =>
            {
                if (newState == IceConnectionState.Disconnected)
                {
                    Console.WriteLine("Disconected");
                }
            };


            signaling.Connect();
            if (!video_translator)
            {
                signaling.Send("{\"data\":{\"getRemoteMedia\":true}}");
            }

            //Console.WriteLine("Press a key to terminate the application...");
            Console.ReadKey(true);
            Console.WriteLine("Program termined.");
            file?.Close();
            pc?.Close();
            signaling?.Close();
            //arduino?.Close();
            //(var a, var b) = ConvertString("{\"data\":{\"candidate\":null}}");
            //Console.WriteLine("{0}, {1}", a, b);
        }
 private IMicrocontroller GetMicrocontrollerInstance(Microcontroller microcontroller)
 {
     return(StringActivator.CreateInstance <IMicrocontroller>(microcontroller.CSharpClassName));
 }
示例#30
0
文件: Leveler.cs 项目: NGCP/UUV
 private double getDesiredDepth()
 {
     return((uCon.gamepad_depth - 81 >= 0) ? desiredDepth : -Microcontroller.map(uCon.gamepad_depth, 0, 81, 2, 0));
 }