Exemplo n.º 1
0
        /// <summary>
        /// Constructor for creating the web server
        /// Example: HttpWebServer  webServer = new HttpWebServer("SSID", "password", -4);
        /// </summary>
        public HttpWebServer(string SSID, string Password, Double TimeOffSet = -5)
        {
            bool success;

            CancellationTokenSource cs = new(60000);

            success = NetworkHelper.ConnectWifiDhcp(SSID, Password, setDateTime: true, token: cs.Token);

            // Initialize Socket class
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Request and bind to an IP from DHCP server
            socket.Bind(new IPEndPoint(IPAddress.Any, 80));

            Debug.WriteLine("IP " + NetworkInterface.GetAllNetworkInterfaces()[0].IPv4Address);

            String macString = BitConverter.ToString(NetworkInterface.GetAllNetworkInterfaces()[0].PhysicalAddress);

            Debug.WriteLine("Mac " + macString);

            // Start listen for web requests
            socket.Listen(10);

            // SMTP connects automatically to get time
            Rtc.SetSystemTime(DateTime.UtcNow.AddHours(TimeOffSet));

            Debug.WriteLine("System time is:" + DateTime.UtcNow.ToString());

            // Create and start a thead for listening for server requests
            Thread tListenforRequest = new Thread(ListenForRequest);

            tListenforRequest.Start();
        }
Exemplo n.º 2
0
 private void SiriusEditorForm_Disposed(object sender, EventArgs e)
 {
     // 가공 시뮬레이션 중이면 중단
     Document?.Action?.ActEntityLaserPathSimulateStop();
     //RTC 가공 중이면 가공 정지
     Rtc?.CtlAbort();
 }
Exemplo n.º 3
0
        /// <summary>
        /// Constructor for creating the web server
        /// Example: HttpWebServer  webServer = new HttpWebServer("SSID", "password", -4);
        /// </summary>
        public HttpWebServer(string SSID, string Password, Double TimeOffSet = -5)
        {
            _SSID = SSID;

            _Password = Password;

            _TimeOffSet = TimeOffSet;

            ConnectNetwork();

            // Initialize Socket class
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Request and bind to an IP from DHCP server
            socket.Bind(new IPEndPoint(IPAddress.Any, 80));

            Console.WriteLine(NetworkInterface.GetAllNetworkInterfaces()[0].IPv4Address);

            // Start listen for web requests
            socket.Listen(10);

            // SMTP connects automatically to get time
            Rtc.SetSystemTime(DateTime.UtcNow.AddHours(_TimeOffSet));

            Console.WriteLine("System time is:" + DateTime.UtcNow.ToString());

            // Create and start a thead for listening for server requests
            Thread tListenforRequest = new Thread(ListenForRequest);

            tListenforRequest.Start();
        }
Exemplo n.º 4
0
        public static void Main()
        {
            Console.WriteLine("system time is: " + DateTime.UtcNow);

            // set RTC
            Rtc.SetSystemTime(new DateTime(2018, 2, 28, 10, 20, 30));

            Console.WriteLine("system time is: " + DateTime.UtcNow);

            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 5
0
        public JsonResult SetVhostRtc(string deviceId, string vhostDomain, Rtc rtc)
        {
            ResponseStruct rss = CommonFunctions.CheckParams(new object[] { deviceId, vhostDomain, rtc });

            if (rss.Code != ErrorNumber.None)
            {
                return(Program.CommonFunctions.DelApisResult(null !, rss));
            }

            var rt = VhostRtcApis.SetVhostRtc(deviceId, vhostDomain, rtc, out ResponseStruct rs);

            return(Program.CommonFunctions.DelApisResult(rt, rs));
        }
Exemplo n.º 6
0
        public bool Start(object args = null)
        {
            if (Rtc.CtlGetStatus(RtcStatus.Busy))
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: busy now !");
                return(false);
            }
            if (!Rtc.CtlGetStatus(RtcStatus.PowerOK))
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: rtc scanner supply power is not ok !");
                return(false);
            }
            if (!Rtc.CtlGetStatus(RtcStatus.PositionAckOK))
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: rtc scanner position ack is not ok !");
                return(false);
            }
            if (!Rtc.CtlGetStatus(RtcStatus.NoError))
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: rtc has a internal problem !");
                return(false);
            }
            if (Laser.IsError)
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: laser source has a error status !");
                return(false);
            }
            if (null != this.thread && this.thread.IsAlive)
            {
                return(false);
            }
            if (this.offsets.Count <= 0)
            {
                this.offsets.Add(Offset.Zero);
                Logger.Log(Logger.Type.Warn, $"marker [{this.Index}]: no offset information ...");
            }
            if (null == this.clonedDoc || 0 == this.clonedDoc.Layers.Count)
            {
                Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: document doesn't has any layers");
                return(false);
            }

            timer = Stopwatch.StartNew();
            this.OnProgress?.Invoke(this, 0);
            this.IsFinished      = false;
            this.thread          = new Thread(this.WorkerThread);
            this.thread.Name     = $"Marker: {this.Name}";
            this.thread.Priority = ThreadPriority.AboveNormal;
            this.thread.Start();
            return(true);
        }
        private void Sync_clocks()
        {
            var time = clock.GetDateTime();

            if (time.Year < 2100)
            {
                Rtc.SetSystemTime(time);
                InvokeOn1Spassed(time);
            }
            else
            {
                InvokeOn1Spassed(DateTime.UtcNow, false);
            }
        }
Exemplo n.º 8
0
 private bool PostWork()
 {
     Rtc.ListEnd();
     if (!Rtc.CtlGetStatus(RtcStatus.Aborted))
     {
         Rtc.ListExecute(true);
     }
     /// 가공완료
     timer.Stop();
     this.ElaspedTime = timer.Elapsed;
     this.IsFinished  = true;
     this.OnProgress?.Invoke(this, 100);
     this.OnFinished?.Invoke(this, this.ElaspedTime);
     Logger.Log(Logger.Type.Info, $"marker [{this.Index}]: job finished. time= {this.ElaspedTime.TotalSeconds:F3}s");
     return(true);
 }
Exemplo n.º 9
0
 public bool Stop()
 {
     Logger.Log(Logger.Type.Warn, $"marker [{this.Index}]: trying to stop ...");
     Rtc.CtlAbort();
     Rtc.CtlLaserOff();
     Motion?.StopAll();
     if (this.thread != null)
     {
         if (!this.thread.Join(2 * 1000))
         {
             Logger.Log(Logger.Type.Error, $"marker [{this.Index}]: fail to join the thread");
         }
         this.thread = null;
         return(true);
     }
     return(false);
 }
Exemplo n.º 10
0
        private static bool SetupNetwork()
        {
            CancellationTokenSource cs = new CancellationTokenSource(5000); //5 seconds.

            // We are using TLS and it requires valid date & time (so we should set the option to true, but SNTP is run in the background, and setting it manually causes issues for the moment!!!)
            // Although setting it to false seems to cause a worse issue. Let us fix this by using a managed class instead.

            try
            {
                _logger.LogInformation("Waiting for network up and IP address...");
                var success = NetworkHelper.SetupAndConnectNetwork(requiresDateTime: true, token: cs.Token);


                if (!success)
                {
                    _logger.LogWarning($"Failed to receive an IP address and/or valid DateTime. Error: {NetworkHelper.Status}.");
                    if (NetworkHelper.HelperException != null)
                    {
                        _logger.LogWarning($"Failed to receive an IP address and/or valid DateTime. Error: {NetworkHelper.HelperException}.");
                    }
                    _logger.LogInformation("It is likely a DateTime problem, so we will now try to set it using a managed helper class!");

                    success = Rtc.SetSystemTime(ManagedNtpClient.GetNetworkTime());
                    if (success)
                    {
                        _logger.LogInformation("Retrived DateTime using Managed NTP Helper class...");
                    }
                    else
                    {
                        _logger.LogWarning("Failed to Retrive DateTime (or IP Address)! Retrying...");
                        SetupNetwork();
                    }
                    _logger.LogInformation($"RTC = {DateTime.UtcNow}");

                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e.Message.ToString());
                return(false);
            }
        }
Exemplo n.º 11
0
        public void CreateApplication(bool passCreds)
        {
            //ARRANGE
            var uri = $"{ApiUrl}/v2/applications";
            var expectedResponse       = @"{
                  ""id"": ""78d335fa323d01149c3dd6f0d48968cf"",
                  ""name"": ""My Application"",
                  ""capabilities"": {
                                ""voice"": {
                                    ""webhooks"": {
                                        ""answer_url"": {
                                            ""address"": ""https://example.com/webhooks/answer"",
                          ""http_method"": ""GET""
                                        },
                        ""fallback_answer_url"": {
                                            ""address"": ""https://fallback.example.com/webhooks/answer"",
                          ""http_method"": ""GET""
                        },
                        ""event_url"": {
                                            ""address"": ""https://example.com/webhooks/event"",
                          ""http_method"": ""POST""
                        }
                                    }
                                },
                    ""messages"": {
                                    ""webhooks"": {
                                        ""inbound_url"": {
                                            ""address"": ""https://example.com/webhooks/inbound"",
                          ""http_method"": ""POST""
                                        },
                        ""status_url"": {
                                            ""address"": ""https://example.com/webhooks/status"",
                          ""http_method"": ""POST""
                        }
                                    }
                                },
                    ""rtc"": {
                                    ""webhooks"": {
                                        ""event_url"": {
                                            ""address"": ""https://example.com/webhooks/event"",
                          ""http_method"": ""POST""
                                        }
                                    }
                                },
                    ""vbc"": { }
                            },
                  ""keys"": {
                                ""public_key"": ""-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSLcjxu33G\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xsO\nOUNhPx2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n"",
                    ""private_key"": ""-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFA\nASCBKcwggSjAgEAAoIBAQDEPpvi+3\nRH1efQ\\nkveWzZDrNNoEXmBw61w+O\n0u/N36tJnN5XnYecU64yHzu2ByEr0\n7iIvYbavFnADwl\\nHMTJwqDQakpa3\n8/SFRnTDq3zronvNZ6nOp7S6K7pcZ\nrw/CvrL6hXT1x7cGBZ4jPx\\nqhjqY\nuJPgZD7OVB69oYOV92vIIJ7JLYwqb\n-----END PRIVATE KEY-----\n""
                  }
                        }";
            var expectedRequestContent = @"{""name"":""My Application"",""capabilities"":{""voice"":{""webhooks"":{""answer_url"":{""http_method"":""GET"",""address"":""https://example.com/webhooks/answer""},""event_url"":{""http_method"":""POST"",""address"":""https://example.com/webhooks/events""},""fallback_answer_url"":{""http_method"":""GET"",""address"":""https://fallback.example.com/webhooks/answer""}}},""rtc"":{""webhooks"":{""event_url"":{""http_method"":""POST"",""address"":""https://example.com/webhooks/events""}}},""vbc"":{},""messages"":{""webhooks"":{""inbound_url"":{""http_method"":""POST"",""address"":""https://example.com/webhooks/inbound""},""status_url"":{""http_method"":""POST"",""address"":""https://example.com/webhooks/status""}}}},""keys"":{""public_key"":""-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwxyBT5FqzibSYK0vB+Gr\\nP+YlyYqsx4lvAmotTwmObZEhTWNAdU0p9hrnNXWX1Gy5O0NDIue40SUhYhJT5r4x\\nugbpNA/1KJauB8VQjetKr9bu697yskz2+EuKa2D9e6N2EMY6PD1tJWmeMmddM1tW\\n2DAXuYo7/xsDWIIA6egCTzyShNvzlKo5081t41xVVsPjsWN887Xp1KYfE0IMGV2j\\n8Nwdtw/MQfP/7Qz7i9VXb7bgx0LEg84dWsnz8u3VZ3IQHlydzPX/2iw7e4pc+k27\\nOU1SkmPn/2JtfFFS2LJpcO/FmdSyNnyHezNPyzNRLVbE0sJJ1tEhxi9GZc1I+Oc4\\ndwIDAQAB\\n-----END PUBLIC KEY-----\\n""}}";

            Setup(uri: uri, responseContent: expectedResponse, requestContent: expectedRequestContent);

            //ACT
            var messagesWebhooks = new Dictionary <Common.Webhook.Type, Common.Webhook>();

            messagesWebhooks.Add(Common.Webhook.Type.inbound_url, new Common.Webhook {
                Address = "https://example.com/webhooks/inbound", Method = "POST"
            });
            messagesWebhooks.Add(Common.Webhook.Type.status_url, new Common.Webhook {
                Address = "https://example.com/webhooks/status", Method = "POST"
            });
            var messagesCapability = new Messages(messagesWebhooks);

            var rtcWebhooks = new Dictionary <Common.Webhook.Type, Common.Webhook>();

            rtcWebhooks.Add(Common.Webhook.Type.event_url, new Common.Webhook {
                Address = "https://example.com/webhooks/events", Method = "POST"
            });
            var rtcCapability = new Rtc(rtcWebhooks);

            var voiceWebhooks = new Dictionary <Common.Webhook.Type, Common.Webhook>();

            voiceWebhooks.Add(Common.Webhook.Type.answer_url, new Common.Webhook {
                Address = "https://example.com/webhooks/answer", Method = "GET"
            });
            voiceWebhooks.Add(Common.Webhook.Type.event_url, new Common.Webhook {
                Address = "https://example.com/webhooks/events", Method = "POST"
            });
            voiceWebhooks.Add(Common.Webhook.Type.fallback_answer_url, new Common.Webhook {
                Address = "https://fallback.example.com/webhooks/answer", Method = "GET"
            });
            var voiceCapability = new Applications.Capabilities.Voice(voiceWebhooks);
            var json            = JsonConvert.SerializeObject(voiceCapability);
            var vbcCapability   = new Vbc();

            var capabilities = new ApplicationCapabilities {
                Messages = messagesCapability, Rtc = rtcCapability, Voice = voiceCapability, Vbc = vbcCapability
            };
            var keys = new Applications.Keys
            {
                PublicKey = PUBLIC_KEY
            };
            var request = new CreateApplicationRequest {
                Capabilities = capabilities, Keys = keys, Name = "My Application"
            };
            var         creds  = Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret);
            var         client = new VonageClient(creds);
            Application response;

            if (passCreds)
            {
                response = client.ApplicationClient.CreateApplicaiton(request);
            }
            else
            {
                response = client.ApplicationClient.CreateApplicaiton(request, creds);
            }


            Assert.Equal("78d335fa323d01149c3dd6f0d48968cf", response.Id);
            Assert.Equal("https://example.com/webhooks/answer", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.answer_url].Address);
            Assert.Equal("GET", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.answer_url].Method);

            Assert.Equal("https://fallback.example.com/webhooks/answer", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.fallback_answer_url].Address);
            Assert.Equal("GET", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.fallback_answer_url].Method);

            Assert.Equal("https://example.com/webhooks/event", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.event_url].Address);
            Assert.Equal("POST", response.Capabilities.Voice.Webhooks[Common.Webhook.Type.event_url].Method);

            Assert.Equal("https://example.com/webhooks/inbound", response.Capabilities.Messages.Webhooks[Common.Webhook.Type.inbound_url].Address);
            Assert.Equal("POST", response.Capabilities.Messages.Webhooks[Common.Webhook.Type.inbound_url].Method);

            Assert.Equal("https://example.com/webhooks/status", response.Capabilities.Messages.Webhooks[Common.Webhook.Type.status_url].Address);
            Assert.Equal("POST", response.Capabilities.Messages.Webhooks[Common.Webhook.Type.status_url].Method);

            Assert.Equal("https://example.com/webhooks/event", response.Capabilities.Rtc.Webhooks[Common.Webhook.Type.event_url].Address);
            Assert.Equal("POST", response.Capabilities.Rtc.Webhooks[Common.Webhook.Type.event_url].Method);

            Assert.Equal("My Application", response.Name);
        }
Exemplo n.º 12
0
        static void UpdateRTCFromNetwork()
        {
            Console.WriteLine("... requesting time from NTP server ...");

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // the following code block uses an async call to SNTP client which should be OK for most of the use scenarios
            // check an alternative in the code block commented bellow

            SIM800H.SntpClient.SyncNetworkTimeAsync("pool.ntp.org", TimeSpan.Zero, (ar) =>
            {
                // update RTC only if update was successful
                if (((SyncNetworkTimeAsyncResult)ar).Result == SyncResult.SyncSuccessful)
                {
                    // get current date time and update RTC
                    DateTime rtcValue = SIM800H.GetDateTime();
                    // set framework date time
                    Rtc.SetSystemTime(rtcValue);

                    Console.WriteLine("!!! new time from NTP server: " + rtcValue.ToString());

                    // done here, dispose SNTP client to free up memory
                    SIM800H.SntpClient.Dispose();
                    SIM800H.SntpClient = null;
                }
                else
                {
                    Console.WriteLine("### failed to get time from NTP server ###");
                }
            });

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // if your network connection is not that good and you definitely need a valid RTC better do this inside a try/catch AND using a retry strategy
            // the implementation bellow uses a synchronous call to SNTP client
            // for the simplest async call see the

            //byte retryCounter = 0;

            //while (retryCounter <= 3)
            //{
            //    try
            //    {
            //        var result = SIM800H.SntpClient.SyncNetworkTimeAsync("time.nist.gov", TimeSpan.Zero).End();

            //        // check result
            //        if (result == SyncResult.SyncSuccessful)
            //        {
            //            // get current date time and update RTC
            //            DateTime rtcValue = SIM800H.GetDateTime();
            //            // set framework date time
            //            Rtc.SetSystemTime(rtcValue);

            //            Console.WriteLine("!!! new time from NTP server: " + rtcValue.ToString());

            //            // done here, dispose SNTP client to free up memory
            //            SIM800H.SntpClient.Dispose();
            //            SIM800H.SntpClient = null;

            //            return;
            //        }
            //        else
            //        {
            //            Console.WriteLine("### failed to get time from NTP server ###");
            //        }
            //    }
            //    catch
            //    {
            //        // failed updating RTC
            //        // flag this
            //    }

            //    // add retry
            //    retryCounter++;

            //    // progressive wait 15*N seconds before next retry
            //    Thread.Sleep(15000 * retryCounter);
            //}
        }
Exemplo n.º 13
0
 private bool PreWork()
 {
     /// 가공을 위한 RTC 버퍼 초기화
     Rtc.ListBegin(this.Laser);
     return(true);
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            string stream =
                "{\"code\":0,\"server\":87846,\"data\":{\"ok\":true,\"now_ms\":1591068638439,\"self\":{\"version\":\"4.0.23\",\"pid\":29282,\"ppid\":1,\"argv\":\"/root/StreamNode/srs -c /root/StreamNode/22364bc4-5134-494d-8249-51d06777fb7f.conf\",\"cwd\":\"/root/StreamNode\",\"mem_kbyte\":71448,\"mem_percent\":0.00,\"cpu_percent\":0.09,\"srs_uptime\":214},\"system\":{\"cpu_percent\":0.02,\"disk_read_KBps\":0,\"disk_write_KBps\":0,\"disk_busy_percent\":0.00,\"mem_ram_kbyte\":16266040,\"mem_ram_percent\":0.06,\"mem_swap_kbyte\":8257532,\"mem_swap_percent\":0.00,\"cpus\":8,\"cpus_online\":8,\"uptime\":162062.71,\"ilde_time\":1275660.46,\"load_1m\":0.12,\"load_5m\":0.22,\"load_15m\":0.19,\"net_sample_time\":1591068632439,\"net_recv_bytes\":0,\"net_send_bytes\":0,\"net_recvi_bytes\":458866896997,\"net_sendi_bytes\":218579639053,\"srs_sample_time\":1591068638439,\"srs_recv_bytes\":447805521,\"srs_send_bytes\":33944,\"conn_sys\":55,\"conn_sys_et\":29,\"conn_sys_tw\":10,\"conn_sys_udp\":4,\"conn_srs\":10}}}";
            var a = JsonHelper.FromJson <SrsSystemInfo>(stream);

            Console.WriteLine(a.ToString());
            Console.WriteLine("Hello World!");
            Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
            Console.WriteLine(JsonHelper.ToJson(SystemApis.GetSystemInfo()));
            Common.init_SrsServer();
            Common.startServers();
            List <string> srsdevidlist = SystemApis.GetAllSrsManagerDeviceId();

            Console.WriteLine(JsonHelper.ToJson(srsdevidlist));
            foreach (var s in srsdevidlist)
            {
                Console.WriteLine(JsonHelper.ToJson(SystemApis.GetSrsManagerInstanceByDeviceId(s)));
            }

            if (srsdevidlist.Count > 0)
            {
                SrsManager srsm = SystemApis.GetSrsManagerInstanceByDeviceId(srsdevidlist[0]);

                string d = "www.test1cn.tyz";

                Console.WriteLine("pid:" + srsm.IsRunning);
                ResponseStruct    rs;
                SrsvHostConfClass vhost = VhostApis.GetVhostTemplate(VhostIngestInputType.Stream, out rs);
                vhost.VhostDomain = d;
                VhostApis.SetVhost(srsm.SrsDeviceId, vhost, out rs);
                Rtc rtc = new Rtc();
                rtc.Bframe  = "known";
                rtc.Enabled = true;
                VhostRtcApis.SetVhostRtc(srsm.SrsDeviceId, d, rtc, out rs);
                Dvr dvr = new Dvr();
                dvr.Enabled  = true;
                dvr.Dvr_path = "/dvr/path/";
                VhostDvrApis.SetVhostDvr(srsm.SrsDeviceId, d, dvr, out rs);
                Hds hds = new Hds();
                hds.Enabled    = true;
                hds.Hds_window = 50;

                VhostHdsApis.SetVhostHds(srsm.SrsDeviceId, d, hds, out rs);
                SrtServerApis.DeleteSrtServer(srsm.SrsDeviceId, out rs);
                SrsSrtServerConfClass srt = new SrsSrtServerConfClass();
                srt = SrtServerApis.GetSrtServerTemplate(out rs);

                srt.Enabled = true;
                SrtServerApis.SetSrtServer(srsm.SrsDeviceId, srt, out rs);

                VhostApis.DeleteVhostByDomain(srsm.SrsDeviceId, "__defaultvhost__", out rs);
                VhostRtcApis.DeleteVhostRtc(srsm.SrsDeviceId, d, out rs);
                VhostHdsApis.DeleteVhostHds(srsm.SrsDeviceId, d, out rs);

                SrsConfigBuild.Build(srsm.Srs, srsm.SrsConfigPath);
                if (srsm.IsRunning)
                {
                    bool ret = srsm.Reload(out rs);
                }
            }
        }
Exemplo n.º 15
0
        public void Execute()
        {
            var APPLICATION_NAME      = Environment.GetEnvironmentVariable("APPLICATION_NAME") ?? "APPLICATION_NAME";
            var VONAGE_APPLICATION_ID = Environment.GetEnvironmentVariable("VONAGE_APPLICATION_ID") ?? "VONAGE_APPLICATION_ID";
            var VONAGE_API_KEY        = Environment.GetEnvironmentVariable("VONAGE_API_KEY") ?? "VONAGE_API_KEY";
            var VONAGE_API_SECRET     = Environment.GetEnvironmentVariable("VONAGE_API_SECRET") ?? "VONAGE_API_SECRET";

            var credentials = Credentials.FromApiKeyAndSecret(VONAGE_API_KEY, VONAGE_API_SECRET);
            var client      = new VonageClient(credentials);

            var messagesWebhooks = new Dictionary <Webhook.Type, Webhook>();

            messagesWebhooks.Add(
                Webhook.Type.inbound_url,
                new Webhook
            {
                Address = "https://example.com/webhooks/inbound",
                Method  = "POST"
            });
            messagesWebhooks.Add(
                Webhook.Type.status_url,
                new Webhook
            {
                Address = "https://example.com/webhooks/status",
                Method  = "POST"
            });
            var messagesCapability = new Messages(messagesWebhooks);
            var voiceWebhooks      = new Dictionary <Webhook.Type, Webhook>();

            voiceWebhooks.Add(Webhook.Type.answer_url,
                              new Webhook
            {
                Address = "https://example.com/webhooks/answer",
                Method  = "GET"
            });
            voiceWebhooks.Add(Webhook.Type.event_url,
                              new Webhook
            {
                Address = "https://example.com/webhooks/events",
                Method  = "POST"
            });
            var voiceCapability = new Vonage.Applications.Capabilities.Voice(voiceWebhooks);
            var rtcWebhooks     = new Dictionary <Webhook.Type, Webhook>();

            rtcWebhooks.Add(Webhook.Type.event_url,
                            new Webhook
            {
                Address = "https://example.com/webhooks/events",
                Method  = "POST"
            });
            var rtcCapability = new Rtc(rtcWebhooks);
            var vbcCapability = new Vbc();
            var request       = new CreateApplicationRequest {
                Name         = APPLICATION_NAME,
                Capabilities = new ApplicationCapabilities
                {
                    Messages = messagesCapability,
                    Rtc      = rtcCapability,
                    Voice    = voiceCapability,
                    Vbc      = vbcCapability
                }
            };
            var response = client.ApplicationClient.UpdateApplication(VONAGE_APPLICATION_ID, request);

            Console.WriteLine(JsonConvert.SerializeObject(response));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes all hardware and software classes
        /// </summary>
        void Initialize()
        {
            Console.WriteLine("Initialize hardware...");

            onboardLed = new RgbPwmLed(device: Device,
                                       redPwmPin: Device.Pins.OnboardLedRed,
                                       greenPwmPin: Device.Pins.OnboardLedGreen,
                                       bluePwmPin: Device.Pins.OnboardLedBlue,
                                       3.3f, 3.3f, 3.3f,
                                       Meadow.Peripherals.Leds.IRgbLed.CommonType.CommonAnode);

#if DEBUG
            Console.WriteLine("Initializing bus");
#endif
            bus = Device.CreateI2cBus(400000);

#if DEBUG
            Console.WriteLine("Initializing display 1");
#endif
            displaySmall = new DisplayLCD(bus, 0x27, 2, 16);
            displaySmall.Write("I'm alive!");

#if DEBUG
            Console.WriteLine("Initializing display 2");
#endif
            displayBig = new DisplayLCD(bus, 0x23, 4, 20);
            displayBig.Write("I'm alive!");

#if DEBUG
            Console.WriteLine("Initializing hc12");
#endif
            displaySmall.Write("Initializing radio");
            serialCom = new HC12Communication(Device.CreateSerialMessagePort(Device.SerialPortNames.Com4,
                                                                             suffixDelimiter: new byte[] { 10 },
                                                                             preserveDelimiter: true, 115200, 8, Parity.None,
                                                                             StopBits.One));
            com = new CommunicationWrapper(serialCom);

#if DEBUG
            Console.WriteLine("Initializing WiFi");
#endif
            displaySmall.Write("Initializing WiFi");
            ipCom = new WifiUdpCommunication(Device.WiFiAdapter, new Action <string>[] { com.SendMessage, displaySmall.Write });
            //Trying to connect at startup to speed process up, but router might be still booting so in that case will try again when requested
            Task.Run(() =>
            {
                try
                {
                    ConnectToWiFi("");
                }
                catch (Exception e)
                {
                    com.SendMessage(ReturnCommandList.exception + e.Message + ReturnCommandList.exceptionTrace + e.StackTrace);
#if DEBUG
                    Console.WriteLine(e.Message + "/n/n" + e.StackTrace);
#endif
                }
            });

#if DEBUG
            Console.WriteLine("Initializing RTC");
#endif
            displaySmall.Write("Initializing RTC");
            clock = new Rtc(bus, com.SendMessage, SetClock);
            clock.SetClockFromRtc();

#if DEBUG
            Console.WriteLine("Initializing watchdog");
#endif
            displaySmall.Write("Initializing watchdog");
            watchdog = new Watchdog(Watchdog.Type.SerialPort);
            //serialCom.RegisterWatchdog(watchdog.MessageReceived);
            //ipCom.RegisterWatchdog(watchdog.MessageReceived);
            watchdog.RegisterSender(com.SendMessage);
            watchdog.RegisterBlockAction(EmergencyDisable);
            watchdog.RegisterSwitchToSerial(SwitchToSerial);

            dict  = new MethodsDictionary();
            queue = new MethodsQueue(com, dict);
            ipCom.SubscribeToMessages(queue.MessageReceived);
            ipCom.SubscribeToMessages(watchdog.MessageReceived);
            serialCom.SubscribeToMessages(queue.MessageReceived);
            serialCom.SubscribeToMessages(watchdog.MessageReceived);

#if DEBUG
            Console.WriteLine("Initializing pca @1600Hz");
#endif
            displaySmall.Write("Initializing PWM @1600Hz");
            pwm1600 = new Pca9685(bus, 0x61, 1600);
            pwm1600.Initialize();
#if DEBUG
            Console.WriteLine("Initializing pca @50Hz");
#endif
            displaySmall.Write("Initializing PWM @50Hz");
            pwm50 = new Pca9685(bus, 0x60, 50);
            pwm50.Initialize();

#if DEBUG
            Console.WriteLine("Initializing expander 1");
#endif
            displaySmall.Write("Initializing expander 1");
            expander1 = new Mcp23x08(bus, 0x20, Device.CreateDigitalInputPort(Device.Pins.D02, InterruptMode.EdgeBoth));

#if DEBUG
            Console.WriteLine("Initializing expander 2");
#endif
            displaySmall.Write("Initializing expander 2");
            expander2 = new Mcp23x08(bus, 0x21, Device.CreateDigitalInputPort(Device.Pins.D06, InterruptMode.EdgeBoth));

#if DEBUG
            Console.WriteLine("Initializing fans");
#endif
            displaySmall.Write("Initializing fans");
            LEDsFans   = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP4), "LEDs' fans");
            motorsFans = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP5), "Motors' fans");
            inasFan    = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP6), "INAs fan");

#if DEBUG
            Console.WriteLine("Initializing buzzer");
#endif
            displaySmall.Write("Initializing buzzer");
            buzzer = new Buzzer(expander2.CreateDigitalOutputPort(expander2.Pins.GP3, false, OutputType.OpenDrain));
            watchdog.RegisterBuzzer(buzzer.Buzz);
#pragma warning disable CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
            buzzer.Buzz();
#pragma warning restore CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania

#if DEBUG
            Console.WriteLine("Initializing power sensors");
#endif
            displaySmall.Write("Initializing power sensors");
            INA219.INA219Configuration config = new INA219.INA219Configuration(INA219.BusVoltageRangeSettings.range32v,
                                                                               INA219.PGASettings.Gain320mV,
                                                                               INA219.ADCsettings.Samples128,
                                                                               INA219.ADCsettings.Samples128,
                                                                               INA219.ModeSettings.ShuntBusContinuous);
            ina219s = new INA219Array(new INA219[]
            {
                new INA219(3.2f, 0.1f, 1, bus, 0x41, config, "C"),
                new INA219(10f, 0.01f, 1, bus, 0x44, config, "L"),
                new INA219(10f, 0.01f, 1, bus, 0x45, config, "R")
            }, buzzer, displayBig, EmergencyDisable);
            ina219s.RegisterSender(com.SendMessage);
            ina219s.RegisterFan(inasFan.SetState);
            ina219s.RegisterFan(motorsFans.SetState);
            ina219s.StartMonitoringVoltage();

            //com = new ComCommunication(Device.CreateSerialMessagePort(Device.SerialPortNames.Com4, suffixDelimiter: new byte[] { 10 }, preserveDelimiter: true, 921600, 8, Parity.None, StopBits.One));

#if DEBUG
            Console.WriteLine("Initializing temperature sensor");
#endif
            displaySmall.Write("Initializing temperature sensor");
            tempPresSensor = new TempPressureSensor(bus);
            tempPresSensor.RegisterSender(com.SendMessage);
#if DEBUG
            Console.WriteLine("Initializing position sensor");
#endif
            displaySmall.Write("Initializing position sensor");
            positionSensor = new BNO055(bus, 0x28);
            positionSensor.RegisterSender(com.SendMessage);
            positionSensor.RegisterScreen(displaySmall.Write);

#if DEBUG
            Console.WriteLine("Initializing motor controller");
#endif
            displaySmall.Write("Initializing motor controller");
            motor = new MotorController(pwm1600.CreatePwmPort(3, 0),
                                        pwm1600.CreatePwmPort(2, 0),
                                        pwm1600.CreatePwmPort(1, 0),
                                        pwm1600.CreatePwmPort(0, 0),
                                        pwm50.CreatePwmPort(0),
                                        Device.CreateDigitalInputPort(Device.Pins.D03, InterruptMode.EdgeRising, ResistorMode.InternalPullDown, 20, 20),
                                        Device.CreateDigitalInputPort(Device.Pins.D04, InterruptMode.EdgeRising, ResistorMode.InternalPullDown, 20, 20),
                                        positionSensor, gimbal, queue.ClearQueue);

#if DEBUG
            Console.WriteLine("Initializing gimbal");
#endif
            displaySmall.Write("Initializing camera gimbal");
            gimbal = new CameraGimbal(pwm50.CreatePwmPort(2), pwm50.CreatePwmPort(1), positionSensor);

#if DEBUG
            Console.WriteLine("Initializing proximity sensors");
#endif
            displaySmall.Write("Initializing proximity sensors");
            proxSensors = new ProximitySensorsArray(new ProximitySensor[]
            {
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP0, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, right", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP1, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, left", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP2, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, center", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP3, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Backward, StopBehavior.Stop, "Back, center", queue, motor)
            });
            proxSensors.Register(com.SendMessage);
            //proxSensors.Register(displaySmall.Write);

#if DEBUG
            Console.WriteLine("Initializing lamps");
#endif
            displaySmall.Write("Initializing lamps");
            narrowLed = new LedLamp(pwm1600.CreatePwmPort(4, 0), LEDsFans, "Front, narrow");
            wideLed   = new LedLamp(pwm1600.CreatePwmPort(5, 0), LEDsFans, "Front, wide");

#if DEBUG
            Console.WriteLine("Initializing cameras");
#endif
            displaySmall.Write("Initializing cameras");
            camera = new Camera(expander2.CreateDigitalOutputPort(expander2.Pins.GP7));
            camera.SetCamera(true);

#if DEBUG
            Console.WriteLine("Finishing initialization");
#endif
            displaySmall.Write("Finishing initialization");
            RegisterMethods();
            //watchdog.StartCheckingMessages();
#if DEBUG
            Console.WriteLine("All hardware initialized!");
#endif
            displaySmall.Clear();
            displaySmall.Write("Ready!");
            com.SendMessage("Ready!");
#pragma warning disable CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
            buzzer.BuzzPulse(100, 100, 3);
#pragma warning restore CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
        }