public async void TestTimeOutExceptionThrow()
        {
            //Stopwatch sw = Stopwatch.StartNew();
            var Thrown = false;

            try
            {
                await TimeOut.Execute(() => Task.Delay(5000), TimeSpan.FromMilliseconds(1000));
            }
            catch (OperationCanceledException)
            {
                Thrown = true;
            }
            //sw.Stop();

            //Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1000));

            Assert.True(Thrown);
        }
Exemplo n.º 2
0
        public bool Create(uint idNewMapItem, Map map, Point pos, Item pInfo, uint idOwner)
        {
            if (map == null || pInfo == null)
            {
                return(false);
            }

            int nAliveSecs = _MAPITEM_USERMAX_ALIVESECS;

            if (pInfo.Itemtype != null)
            {
                nAliveSecs = (int)(pInfo.Itemtype.Price / _MAPITEM_ALIVESECS_PERPRICE + _MAPITEM_USERMIN_ALIVESECS);
            }
            if (nAliveSecs > _MAPITEM_USERMAX_ALIVESECS)
            {
                nAliveSecs = _MAPITEM_USERMAX_ALIVESECS;
            }

            m_tAlive = new TimeOut(nAliveSecs);
            m_tAlive.Update();

            Map         = map;
            MapIdentity = map.Identity;
            MapX        = (ushort)pos.X;
            MapY        = (ushort)pos.Y;

            m_pItem                = pInfo;
            m_dwIdentity           = idNewMapItem;
            m_pPacket.Identity     = idNewMapItem;
            m_pItemtype            = pInfo.Itemtype;
            m_pItem.OwnerIdentity  = 0;
            m_pItem.PlayerIdentity = idOwner;

            m_pItem.Position = (ItemPosition)254;

            m_pPacket.ItemColor = 3;
            m_pPacket.DropType  = 1;
            m_pPacket.Itemtype  = Type = pInfo.Type;
            Map.AddItem(this);

            return(true);
        }
Exemplo n.º 3
0
        public static DateTimeOffset GetTimeOutEndDate(TimeOut timeOutType, DateTimeOffset startDate)
        {
            switch (timeOutType)
            {
            case TimeOut._24Hrs:
                return(startDate.AddDays(1));

            case TimeOut.Week:
                return(startDate.AddDays(7));

            case TimeOut.Month:
                return(startDate.AddMonths(1));

            case TimeOut._6Weeks:
                return(startDate.AddDays(42));

            default:
                return(DateTimeOffset.MinValue);
            }
        }
Exemplo n.º 4
0
        private void _timer_Tick(object sender, EventArgs e)
        {
            if (_timeOut <= 0)
            {
                _timer.Stop();
                _cronometro = 0;
            }

            _cronometro++;

            if (_cronometro >= _timeOut)
            {
                FecharDropDown();
                _timer.Stop();
                _cronometro = 0;
                if (TimeOut != null)
                {
                    TimeOut.Invoke(this, new EventArgs());
                }
            }
        }
Exemplo n.º 5
0
        private void init()
        {
            //数据配置
            pointMetaData = new List <PointMetadata>();

            //Meu窗口配置
            searchWin = new SearchWindow()
            {
                SignalDisplayList = signalList, ClientAsync = clientAsync
            };
            connectWindow = new ConnectWindow();
            SignalMeItem.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(signalMeItemMouseLeftButtonDown), true);
            ConnectMeItem.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(ConnectMeItemMouseLeftButtonDown), true);


            ///连接到服务端配置
            EthernetSetUp setUp   = new EthernetSetUp("127.0.0.1", 9527);
            ILog          log     = new DefaultLog("SignalMonitor");
            TimeOut       timeOut = new TimeOut("SignalMonitor", 1000, log);

            clientAsync = new FreedomClientAsync(setUp, timeOut, log);


            //读服务器元数据
            clientAsync.AsyncReadMetaData += asyncReadMetaData;

            //订阅client操作事件
            clientAsync.AsyncReadOrSubsEvent += asyncReadOrSubsEvent;
            clientAsync.AsyncWriteEvent      += ayncWriteEvent;
            clientAsync.DisconnectEvent      += disconnectEvent;

            //断线重连事件
            reTime          = new System.Timers.Timer(3000);
            reTime.Elapsed += ReTime_Elapsed;

            if (clientAsync.Connect())
            {
                clientAsync.ReadMetaData();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Convert to specification in server format
        /// </summary>
        /// <returns>The specification for the group</returns>
        override public String ToString()
        {
            String subgroupsView = String.Empty;

            if (SubGroups != null)
            {
                for (int idx = 0; idx < SubGroups.Count; idx++)
                {
                    subgroupsView += String.Format("\t{0}\r\n", SubGroups[idx]);
                }
            }
            String ownersView = String.Empty;

            if (OwnerNames != null)
            {
                for (int idx = 0; idx < OwnerNames.Count; idx++)
                {
                    ownersView += String.Format("\t{0}\r\n", OwnerNames[idx]);
                }
            }
            String usersView = String.Empty;

            if (UserNames != null)
            {
                for (int idx = 0; idx < UserNames.Count; idx++)
                {
                    usersView += String.Format("\t{0}\r\n", UserNames[idx]);
                }
            }
            String value = String.Format(GroupSpecFormat, Id,
                                         (MaxResults > 0) ? MaxResults.ToString() : string.Empty,
                                         (MaxScanRows > 0) ? MaxScanRows.ToString() : string.Empty,
                                         (MaxLockTime > 0) ? MaxLockTime.ToString() : string.Empty,
                                         (MaxOpenFiles > 0) ? MaxOpenFiles.ToString() : string.Empty,
                                         (TimeOut > 0) ? TimeOut.ToString() : string.Empty,
                                         (PasswordTimeout > 0) ? "PasswordTimeout:\t" + PasswordTimeout.ToString() + "\r\n" + "\r\n" : string.Empty,
                                         subgroupsView, ownersView, usersView);

            return(value);
        }
Exemplo n.º 7
0
        public bool Create(uint idNewMapItem, Map map, Point pos, DbItemtype idType, uint idOwner, byte nPlus, byte nDmg,
                           short nDura)
        {
            if (map == null || idType == null)
            {
                return(false);
            }

            m_tAlive = new TimeOut(_DISAPPEAR_TIME);
            m_tAlive.Startup(_DISAPPEAR_TIME);

            Map         = map;
            MapIdentity = map.Identity;
            MapX        = (ushort)pos.X;
            MapY        = (ushort)pos.Y;

            m_nPlus = nPlus;
            m_nDmg  = nDmg;
            m_nDura = nDura;

            m_pItemtype        = idType;
            Type               = m_pItemtype.Type;
            m_dwIdentity       = idNewMapItem;
            m_pPacket.Identity = idNewMapItem;

            if (idOwner != 0)
            {
                m_idOwner = idOwner;
                m_tPriv   = new TimeOut(_MAPITEM_PRIV_SECS);
                m_tPriv.Startup(_MAPITEM_PRIV_SECS);
                m_tPriv.Update();
            }

            m_pPacket.DropType  = 1;
            m_pPacket.ItemColor = 3;
            Map.AddItem(this);

            return(true);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            //EthernetSetUp _setup  = new EthernetSetUp("127.0.0.1", 502);
            SerialportSetUp _setup   = new SerialportSetUp("com3", 9600, 8, StopBits.One);
            ILog            _log     = new DefaultLog("ModbusTCPClient");
            TimeOut         _timeout = new TimeOut("ModbusTCPClient", 1000, _log);
            //ModbusTCPClient _client = new ModbusTCPClient(_setup,_timeout,_log);
            var _client = new ModbusRTUMaster(_setup, _timeout, _log);

            if (_client.Connect())//先判断是否能连接到客户端
            {
                //var boolvalue = _client.ReadBool(new DeviceAddress(1, 00001));
                //var boolvalues = _client.ReadBools(new DeviceAddress(1, 00001),10);

                //var boolvalue1 = _client.ReadBool(new DeviceAddress(1, 10001));
                //var boolvalue1s = _client.ReadBools(new DeviceAddress(1, 10001), 10);

                //var shortvalue = _client.ReadShort(new DeviceAddress(1, 30001));
                //var shortvalues = _client.ReadShorts(new DeviceAddress(1, 30001), 10);

                //var shortvalue1 = _client.ReadUShort(new DeviceAddress(1, 40001));
                //var ushortvalue1s = _client.ReadUShorts(new DeviceAddress(1, 40001), 10);

                //var intvalue = _client.ReadInt(new DeviceAddress(1, 30001));
                //var intvalues = _client.ReadInts(new DeviceAddress(1, 30001), 10);

                var intvalue1  = _client.ReadInt(new DeviceAddress(1, 40001, byteOrder: ByteOrder.BigEndian));
                var intvalue1s = _client.ReadInts(new DeviceAddress(1, 40001, byteOrder: ByteOrder.BigEndian), 5);

                //var floatvalue = _client.Readfloat(new DeviceAddress(1, 30001));
                //var floatvalues = _client.Readfloats(new DeviceAddress(1, 30001),10);

                //var floatvalue1 = _client.Readfloat(new DeviceAddress(1, 40001));
                //var floatvalue1s = _client.Readfloats(new DeviceAddress(1, 40001), 10);
            }

            Console.ReadKey();
        }
Exemplo n.º 9
0
        public DataSet GetDataSet(string Sql)
        {
            DataSet oDS = new DataSet();

            try {
                using (var connection = new MySqlConnection(this.ConnectionString)) {
                    connection.Open();
                    MySqlCommand command = new MySqlCommand(Sql, connection);
                    if (TimeOut != 0 || !string.IsNullOrEmpty(TimeOut.ToString()))
                    {
                        command.CommandTimeout = TimeOut;
                    }
                    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
                    dataAdapter.Fill(oDS);
                    command.Dispose();
                    dataAdapter.Dispose();
                    connection.Close();
                }
                return(oDS);
            } catch (Exception ex) {
                throw ex;
            }
        }
Exemplo n.º 10
0
 public bool OnInit()
 {
     _log.NormalLog(string.Format("ModbusServerHanderTask:Init=>Initing"));
     try
     {
         _config = ReaderXMLUtil.ReadXMLConfig <ModbusServerConfig>("../../../../conf/Configuration.xml", ModbusServerConfig.ReadConfig, "setup", "ModbusTCPServerHandlerTask")[0];
         if (_config.SignalListFilePath == "")
         {
             _log.ErrorLog("ModbusServerHanderTask Init fail: signal file path is null!");
             return(false);
         }
         _workbook = XmlSerialiaztion.XmlDeserial <XMLWorkbook>(_config.SignalListFilePath, _log);
         if (_workbook == default(XMLWorkbook))
         {
             _log.ErrorLog("ModbusServerHanderTask Init fail:Read signal file fail!");
             return(false);
         }
         _points = PointsCollcetCreate.CreateMoudbus(_workbook, _log);
         ModbusPointsRegister.Register(_points, _log);
         _timeout = new TimeOut("ModbusServerHanderTask", _config.TimeOut, _log);
         _server  = new ModbusTCPServer(new EthernetSetUp(_config.IpAddress, _config.Port), _timeout, _log, _config.MaxConnect, _config.SalveId, SocketServers.SocketServerType.SaeaServer);
         if (_server.Init())
         {
             _log.NormalLog(string.Format("ModbusServerHanderTask:Initing=>Inited"));
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         _log.ErrorLog(string.Format("ModbusServerHanderTask Init fail:{0}", e.Message));
         return(false);
     }
 }
        public bool TryGet <T>(string key, string region, out T value)
        {
            var hash = CalcSlotIndex(key, region);
            T   cachedValue;

            if (TryGetCachedValue(key, region, out cachedValue))
            {
                value = cachedValue;
                return(true);
            }

            // Spin while we wait for the lock to become available
            uint t = TimeOut.GetTime();

            while (Interlocked.CompareExchange(ref _slots[hash], 0, 0) != 0)
            {
                if (TryGetCachedValue(key, region, out cachedValue))
                {
                    value = cachedValue;
                    return(true);
                }
                if (TimeOut.UpdateTimeOut(t, ReadTimeout) <= 0)
                {
                    break;
                }
            }

            // Try again since another thread may of finished with this bucket
            if (TryGetCachedValue(key, region, out cachedValue))
            {
                value = cachedValue;
                return(true);
            }
            value = default(T);
            return(false);
        }
Exemplo n.º 12
0
        /// <summary>
        /// https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
        /// </summary>
        /// <param name="callBackFunction"></param>
        /// <param name="delay"></param>
        /// <returns></returns>
        private int __setTimeout__(Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, double delay)
        {
            _timeoutID++;

            TimeOut _to = new TimeOut();

            _to.Delay    = delay;
            _to.Function = callBackFunction;
            _to.ID       = _timeoutID;

            TimeOutList.Add(_to);

            if (_dt == null)
            {
                _dt          = new Windows.UI.Xaml.DispatcherTimer();
                _dt.Interval = TimeSpan.FromMilliseconds(100);
                _dt.Tick    += _dt_Tick;
                _dt.Start();
            }

            return(_timeoutID);

            // return this._eventQueue.Enqueue(new CallBackEvent(callBackFunction, delay, CallBackType.TimeOut)).Id;
        }
        /// <summary>
        /// 从串口接收一串数据信息,可以指定是否一定要接收到数据
        /// </summary>
        /// <param name="socket">串口对象</param>
        /// <param name="awaitData">是否必须要等待数据返回</param>
        /// <returns>结果数据对象</returns>
        protected OperateResult <byte[]> ReceiveSolo(Socket socket, bool awaitData)
        {
            //if (!Authorization.nzugaydgwadawdibbas())
            //{
            //	return new OperateResult<byte[]>(StringResources.Language.AuthorizationFailed);
            //}
            byte[]       buffer       = new byte[1024];
            MemoryStream memoryStream = new MemoryStream();
            DateTime     now          = DateTime.Now;
            TimeOut      hslTimeOut   = new TimeOut
            {
                DelayTime  = base.ReceiveTimeOut,
                WorkSocket = socket
            };

            if (base.ReceiveTimeOut > 0)
            {
                ThreadPool.QueueUserWorkItem(base.ThreadPoolCheckTimeOut, hslTimeOut);
            }
            try
            {
                Thread.Sleep(sleepTime);
                socket.ReceiveTimeout = 500;
                int count = socket.Receive(buffer);
                hslTimeOut.IsSuccessful = true;
                memoryStream.Write(buffer, 0, count);
            }
            catch (Exception ex)
            {
                memoryStream.Dispose();
                return(new OperateResult <byte[]>(ex.Message));
            }
            byte[] value = memoryStream.ToArray();
            memoryStream.Dispose();
            return(OperateResult.CreateSuccessResult(value));
        }
        /// <summary>
        /// 创建一个新的socket对象并连接到远程的地址
        /// </summary>
        /// <param name="endPoint">连接的目标终结点</param>
        /// <param name="timeOut">连接的超时时间</param>
        /// <returns>返回套接字的封装结果对象</returns>
        /// <example>
        /// <code lang="cs" source="Communication_Net45.Test\Documentation\Samples\Core\NetworkBase.cs" region="CreateSocketAndConnectExample" title="创建连接示例" />
        /// </example>
        protected OperateResult <Socket> CreateSocketAndConnect(IPEndPoint endPoint, int timeOut)
        {
            if (UseSynchronousNet)//使用同步网络
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    TimeOut connectTimeout = new TimeOut()
                    {
                        WorkSocket = socket,
                        DelayTime  = timeOut
                    };
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);
                    socket.Connect(endPoint);
                    connectTimeout.IsSuccessful = true;

                    return(OperateResult.CreateSuccessResult(socket));
                }
                catch (Exception ex)
                {
                    socket?.Close();
                    LogNet?.WriteException("CreateSocketAndConnect", ex);
                    return(new OperateResult <Socket>(ex.Message));
                }
            }
            else
            {
                OperateResult <Socket> result      = new OperateResult <Socket>();
                ManualResetEvent       connectDone = null;
                StateObject            state       = null;
                try
                {
                    connectDone = new ManualResetEvent(false);
                    state       = new StateObject();
                }
                catch (Exception ex)
                {
                    return(new OperateResult <Socket>(ex.Message));
                }


                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 超时验证的信息
                TimeOut connectTimeout = new TimeOut()
                {
                    WorkSocket = socket,
                    DelayTime  = timeOut
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);

                try
                {
                    state.WaitDone   = connectDone;
                    state.WorkSocket = socket;
                    socket.BeginConnect(endPoint, new AsyncCallback(ConnectCallBack), state);// 当连接的结果返回
                }
                catch (Exception ex)
                {
                    // 直接失败
                    connectTimeout.IsSuccessful = true;                                     // 退出线程池的超时检查
                    LogNet?.WriteException(ToString(), ex);                                 // 记录错误日志
                    socket.Close();                                                         // 关闭网络信息
                    connectDone.Close();                                                    // 释放等待资源
                    result.Message = StringResources.Language.ConnectedFailed + ex.Message; // 传递错误消息
                    return(result);
                }



                // 等待连接完成
                connectDone.WaitOne();
                connectDone.Close();
                connectTimeout.IsSuccessful = true;

                if (state.IsError)
                {
                    // 连接失败
                    result.Message = StringResources.Language.ConnectedFailed + state.ErrerMsg;
                    socket?.Close();
                    return(result);
                }


                result.Content   = socket;
                result.IsSuccess = true;
                state.Clear();
                state = null;
                return(result);
            }
        }
Exemplo n.º 15
0
 public DateTimeOffset GetTimeOutEndDate(TimeOut timeOutType, DateTimeOffset startDate)
 {
     return(ExclusionDateHelper.GetTimeOutEndDate(timeOutType, startDate));
 }
Exemplo n.º 16
0
 private void buttonStart_Click(object sender, EventArgs e)
 {
     if (buttonStart.Text == "&Start")//开始
     {
         IPEndPoint iep = GetEndPoint(comboBoxServer.Text);
         if (iep != null)
         {
             if (Config.WorkPath.Length == 0)
             {
                 MessageBox.Show(this, "Path can not be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
             }
             Config.ServerIP = comboBoxServer.Text;
             Config.SaveServerList(comboBoxServer.Text);
             SetButtonEnabled(buttonUninstall, false);
             SetControlText(buttonStart, "&Cancel");
             SetControlText(labelInfo, "Connect to server");
             SetProgressBarValue(progressBarDetail, 0);
             SetProgressBarValue(progressBarTotal, 0);
     #if !Remoting
             client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             time = new TimeOut(Config.TimeOutInterval, new TimeOut.TimeOutCallBack(TimeOut), client);
             time.Start();//开始计时
             client.BeginConnect(iep, new AsyncCallback(Connect), iep);
     #else
             td = new Thread(new ParameterizedThreadStart(Connect));
             td.Start(iep);
     #endif
         }
     }
     else                      //取消
     {
         SetControlText(buttonStart, "&Start");
         SetButtonEnabled(buttonUninstall, true);
     #if !Remoting
         if (client != null)
         {
             client.Close();
         }
     #else
         if (td != null && td.ThreadState != ThreadState.Stopped)
         {
             td.Abort();
         }
     #endif
     }
 }
Exemplo n.º 17
0
        private bool setUp()
        {
            //bool flag;
            _configs = ReaderXMLUtil.ReadXMLConfig <TaskConfig>(_configFath, ConfigUtilly.ReadConfig, _nodeElement, _handler);
            if (_configs != null)
            {
                _log.NormalLog(string.Format("{0}:Down=>Creating", "SetUp()"));

                //创建外部task
                var taskFactory = new ts.TaskFactory(_configFath);
                //task类型配置
                foreach (var config in _configs)
                {
                    ILog log = new DefaultLog(config.TaskName)
                    {
                        Handle = LogHandle.debug, ByteSteamLogSwicth = true
                    };
                    //根据task类型配置创建具体的task列表
                    var tasks = taskFactory.CreateTasks(config, log);
                    foreach (var task in tasks)
                    {
                        if (task != null)
                        {
                            task.InitLevel = config.InitLevel;
                            _log.NormalLog(string.Format("{0}:Task<{1}>,Creating=>Created", "SetUp()", config.TaskName));
                            addTask(task);
                        }
                    }
                }

                //创建内部Task

                //自定义协议,用于信号监控及界面通讯
                string            freeTaskName   = "FreedomServerTaskHandler";
                ILog              freelog        = new DefaultLog(freeTaskName);
                TimeOut           freeTimeout    = new TimeOut(freeTaskName, 1000, freelog);
                EthernetSetUp     freeSetup      = new EthernetSetUp("127.0.0.1", 9527);
                FreedomServerTask freeServerTask = new FreedomServerTask(freeTaskName, freelog, freeTimeout, freeSetup);
                _log.NormalLog(string.Format("{0}:Task<{1}>,Creating=>Created", "SetUp()", freeServerTask.TaskName));
                addTask(freeServerTask);

                sortTasks();
                foreach (var t in _tasks)
                {
                    ChangInitLevel(t.InitLevel);
                    if (t.OnInit())
                    {
                        continue;
                    }
                    else
                    {
                        _log.ErrorLog(string.Format("Task<{0}> Inited failed!", t.TaskName));
                        return(false);
                    }
                }
            }
            else
            {
                _log.ErrorLog("Tasks config Error!");
                return(false);
            }
            return(true);
        }
Exemplo n.º 18
0
 public void ExecuteReachCommand()
 {
     IsReachflyoutOpen = true;
     timeOut           = new TimeOut(20, CloseFlyout);
 }
Exemplo n.º 19
0
 protected override void MFOnDestroy()
 {
     mTimeOut = null;
     mTimeOutEventHandler = null;
 }
Exemplo n.º 20
0
 public override void Initialize(TimeOut timeout)
 {
     base.Initialize(timeout);
     renderer = timeout.GetComponent <Renderer>();
 }
Exemplo n.º 21
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (buttonStart.Text == labelStart.Text)//开始
            {
                if (treeViewSolution.SelectedNode == null || treeViewSolution.SelectedNode.Level == 0)
                {
                    MessageBox.Show(this, "Select a solution first", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Config.WorkPath.Length == 0)
                {
                    MessageBox.Show(this, "Path can not be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int port = Config.ServerPort;
                IPAddress ip = IPAddress.None;

                Solution sol = (Solution)treeViewSolution.SelectedNode.Tag;
                IPEndPoint iep = GetEndPoint(string.Format("{0}:{1}", sol.IP, sol.Port));
                if (iep != null)
                {
                    SetState(State.Downloading);
                    CurrentSolution = sol;
                    SetControlText(labelInfo, labelConnecting.Text);
            #if !Remoting
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    time = new TimeOut(Config.TimeOutInterval, new TimeOut.TimeOutCallBack(TimeOut), client);
                    time.Start();//开始计时
                    client.BeginConnect(iep, new AsyncCallback(Download), iep);
            #else
                    td = new Thread(new ParameterizedThreadStart(DownLoad));
                    td.Start(iep);
            #endif
                }
            }
            else                      //取消
            {
                SetState(State.Idle);
            #if !Remoting
                if (client != null)
                {
                    client.Close();
                }
            #else
                if (td != null && td.ThreadState != ThreadState.Stopped)
                {
                    td.Abort();
                }
            #endif
            }
        }
Exemplo n.º 22
0
    /* The TimeOut sandal is another copy of the reference to the TimeOut script used for the powerups.  It allows the subclass SNDL_PU
     * to read the type variable and timeractive variable from the TimeOut script.  These variables indicate to the SNDL_PU class whether or not
     * it should act and if so for how long it should change the transparency of the powerup sprite.
     */


    // Start is called before the first frame update
    void Start()
    {
        sandal        = FindObjectOfType <TimeOut>();
        powerUp.color = new Color(1f, 1f, 1f, 0.0f);
        timer.color   = Color.clear;
    }
Exemplo n.º 23
0
 void Start()
 {
     to = GameObject.FindObjectOfType <TimeOut>();
 }
Exemplo n.º 24
0
 public void Init(float timeOut,DownloadTimeOutEventHandler timeOutEventHandler)
 {
     mTimeOut = new TimeOut();
     mTimeOut.SetTimeOut(timeOut);
     mTimeOutEventHandler = timeOutEventHandler;
 }
Exemplo n.º 25
0
        /// <summary>
        /// Load preferences object
        /// </summary>
        private void LoadPrefs(UserPrefs p)
        {
            SetProject(p.LanguageCode, p.Project, p.CustomProject);

            FindAndReplace.Clear();
            chkFindandReplace.Checked      = p.FindAndReplace.Enabled;
            FindAndReplace.IgnoreLinks     = p.FindAndReplace.IgnoreSomeText;
            FindAndReplace.IgnoreMore      = p.FindAndReplace.IgnoreMoreText;
            FindAndReplace.AppendToSummary = p.FindAndReplace.AppendSummary;
            FindAndReplace.AfterOtherFixes = p.FindAndReplace.AfterOtherFixes;
            FindAndReplace.AddNew(p.FindAndReplace.Replacements);

            RplcSpecial.Clear();
            RplcSpecial.AddNewRule(p.FindAndReplace.AdvancedReps);

            SubstTemplates.Clear();
            SubstTemplates.TemplateList      = p.FindAndReplace.SubstTemplates;
            SubstTemplates.ExpandRecursively = p.FindAndReplace.ExpandRecursively;
            SubstTemplates.IgnoreUnformatted = p.FindAndReplace.IgnoreUnformatted;
            SubstTemplates.IncludeComments   = p.FindAndReplace.IncludeComments;

            FindAndReplace.MakeList();

            listMaker.SourceText     = p.List.ListSource;
            listMaker.SelectedSource = p.List.SourceIndex;

            SaveArticleList = p.General.SaveArticleList;

            IgnoreNoBots = p.General.IgnoreNoBots;

            listMaker.Add(p.List.ArticleList);

            chkGeneralFixes.Checked   = p.Editprefs.GeneralFixes;
            chkAutoTagger.Checked     = p.Editprefs.Tagger;
            chkUnicodifyWhole.Checked = p.Editprefs.Unicodify;

            cmboCategorise.SelectedIndex = p.Editprefs.Recategorisation;
            txtNewCategory.Text          = p.Editprefs.NewCategory;
            txtNewCategory2.Text         = p.Editprefs.NewCategory2;

            cmboImages.SelectedIndex = p.Editprefs.ReImage;
            txtImageReplace.Text     = p.Editprefs.ImageFind;
            txtImageWith.Text        = p.Editprefs.Replace;

            chkSkipNoCatChange.Checked = p.Editprefs.SkipIfNoCatChange;
            chkRemoveSortKey.Checked   = p.Editprefs.RemoveSortKey;
            chkSkipNoImgChange.Checked = p.Editprefs.SkipIfNoImgChange;

            chkAppend.Checked     = p.Editprefs.AppendText;
            rdoAppend.Checked     = p.Editprefs.Append;
            rdoPrepend.Checked    = !p.Editprefs.Append;
            txtAppendMessage.Text = p.Editprefs.Text;
            udNewlineChars.Value  = p.Editprefs.Newlines;

            nudBotSpeed.Value      = p.Editprefs.AutoDelay;
            chkSuppressTag.Checked = p.Editprefs.SupressTag;

            chkRegExTypo.Checked = p.Editprefs.RegexTypoFix;

            radSkipNonExistent.Checked       = p.SkipOptions.SkipNonexistent;
            radSkipExistent.Checked          = p.SkipOptions.Skipexistent;
            chkSkipNoChanges.Checked         = p.SkipOptions.SkipWhenNoChanges;
            chkSkipSpamFilter.Checked        = p.SkipOptions.SkipSpamFilterBlocked;
            chkSkipIfInuse.Checked           = p.SkipOptions.SkipInuse;
            chkSkipWhitespace.Checked        = p.SkipOptions.SkipWhenOnlyWhitespaceChanged;
            chkSkipCasing.Checked            = p.SkipOptions.SkipOnlyCasingChanged;
            chkSkipGeneralFixes.Checked      = p.SkipOptions.SkipOnlyGeneralFixChanges;
            chkSkipMinorGeneralFixes.Checked = p.SkipOptions.SkipOnlyMinorGeneralFixChanges;
            chkSkipIfRedirect.Checked        = p.SkipOptions.SkipIfRedirect;
            chkSkipIfNoAlerts.Checked        = p.SkipOptions.SkipIfNoAlerts;

            chkSkipIfContains.Checked    = p.SkipOptions.SkipDoes;
            chkSkipIfNotContains.Checked = p.SkipOptions.SkipDoesNot;

            txtSkipIfContains.Text    = p.SkipOptions.SkipDoesText;
            txtSkipIfNotContains.Text = p.SkipOptions.SkipDoesNotText;

            chkSkipIsRegex.Checked       = p.SkipOptions.Regex;
            chkSkipCaseSensitive.Checked = p.SkipOptions.CaseSensitive;

            chkSkipWhenNoFAR.Checked     = p.SkipOptions.SkipNoFindAndReplace;
            chkSkipIfNoRegexTypo.Checked = p.SkipOptions.SkipNoRegexTypoFix;
            Skip.SelectedItems           = p.SkipOptions.GeneralSkipList;
            chkSkipNoDab.Checked         = p.SkipOptions.SkipNoDisambiguation;
            chkSkipNoPageLinks.Checked   = p.SkipOptions.SkipNoLinksOnPage;

            cmboEditSummary.Items.Clear();

            if (p.General.Summaries.Count == 0)
            {
                LoadDefaultEditSummaries();
            }
            else
            {
                foreach (string s in p.General.Summaries)
                {
                    cmboEditSummary.Items.Add(s);
                }
            }

            chkLock.Checked    = p.General.LockSummary;
            EditToolBarVisible = p.General.EditToolbarEnabled;

            cmboEditSummary.Text = p.General.SelectedSummary;

            if (chkLock.Checked)
            {
                lblSummary.Text = p.General.SelectedSummary;
            }

            PasteMore1.Text  = p.General.PasteMore[0];
            PasteMore2.Text  = p.General.PasteMore[1];
            PasteMore3.Text  = p.General.PasteMore[2];
            PasteMore4.Text  = p.General.PasteMore[3];
            PasteMore5.Text  = p.General.PasteMore[4];
            PasteMore6.Text  = p.General.PasteMore[5];
            PasteMore7.Text  = p.General.PasteMore[6];
            PasteMore8.Text  = p.General.PasteMore[7];
            PasteMore9.Text  = p.General.PasteMore[8];
            PasteMore10.Text = p.General.PasteMore[9];

            txtFind.Text                 = p.General.FindText;
            chkFindRegex.Checked         = p.General.FindRegex;
            chkFindCaseSensitive.Checked = p.General.FindCaseSensitive;

            wordWrapToolStripMenuItem1.Checked = p.General.WordWrap;
            EnableToolBar = p.General.ToolBarEnabled;
            bypassRedirectsToolStripMenuItem.Checked            = p.General.BypassRedirect;
            autoSaveSettingsToolStripMenuItem.Checked           = p.General.AutoSaveSettings;
            preParseModeToolStripMenuItem.Checked               = p.General.PreParseMode;
            noSectionEditSummaryToolStripMenuItem.Checked       = p.General.noSectionEditSummary;
            restrictDefaultsortChangesToolStripMenuItem.Checked = p.General.restrictDefaultsortAddition;
            noMOSComplianceFixesToolStripMenuItem.Checked       = p.General.noMOSComplianceFixes;
            syntaxHighlightEditBoxToolStripMenuItem.Checked     = p.General.syntaxHighlightEditBox;
            automaticallyDoAnythingToolStripMenuItem.Checked    = !p.General.NoAutoChanges;
            toolStripComboOnLoad.SelectedIndex = p.General.OnLoadAction;
            chkMinor.Checked = p.General.Minor;
            addAllToWatchlistToolStripMenuItem.Checked  = p.General.Watch;
            dontAddToWatchlistToolStripMenuItem.Checked = p.General.DoNotWatch;
            ShowMovingAverageTimer = p.General.TimerEnabled;

            sortAlphabeticallyToolStripMenuItem.Checked          = p.General.SortListAlphabetically;
            displayfalsePositivesButtonToolStripMenuItem.Checked = p.General.AddIgnoredToLog;

            AutoSaveEditBoxEnabled = p.General.AutoSaveEdit.Enabled;
            AutoSaveEditBoxPeriod  = p.General.AutoSaveEdit.SavePeriod;
            AutoSaveEditBoxFile    = p.General.AutoSaveEdit.SaveFile;

            SuppressUsingAWB           = p.General.SuppressUsingAWB;
            AddUsingAWBOnArticleAction = p.General.AddUsingAWBToActionSummaries;

            filterOutNonMainSpaceToolStripMenuItem.Checked = p.General.filterNonMainSpace;
            removeDuplicatesToolStripMenuItem.Checked      = p.General.AutoFilterDuplicates;

            alphaSortInterwikiLinksToolStripMenuItem.Checked    = p.General.SortInterWikiOrder;
            replaceReferenceTagsToolStripMenuItem.Checked       = p.General.ReplaceReferenceTags;
            focusAtEndOfEditTextBoxToolStripMenuItem.Checked    = p.General.FocusAtEndOfEditBox;
            scrollToUnbalancedBracketsToolStripMenuItem.Checked = p.General.scrollToUnbalancedBrackets;

            txtEdit.Font = new System.Drawing.Font(p.General.TextBoxFont, p.General.TextBoxSize);

            LowThreadPriority = p.General.LowThreadPriority;
            Flash             = p.General.Flash;
            Beep = p.General.Beep;

            Minimize = p.General.Minimize;
            TimeOut  = p.General.TimeOutLimit;
            webBrowserEdit.TimeoutLimit = int.Parse(TimeOut.ToString());

            chkEnableDab.Checked = p.Disambiguation.Enabled;
            txtDabLink.Text      = p.Disambiguation.Link;
            txtDabVariants.Lines = p.Disambiguation.Variants;
            udContextChars.Value = p.Disambiguation.ContextChars;

            listMaker.SpecialFilterSettings = p.Special;

            loggingSettings1.SerialisableSettings = p.Logging;

            CModule.ModuleEnabled = p.Module.Enabled;
            CModule.Language      = p.Module.Language;
            CModule.Code          = p.Module.Code.Replace("\n", "\r\n");
            if (CModule.ModuleEnabled)
            {
                CModule.MakeModule();
            }
            else
            {
                CModule.SetModuleNotBuilt();
            }

            ExtProgram.Settings = p.ExternalProgram;

            foreach (PluginPrefs pp in p.Plugin)
            {
                if (Plugin.Items.ContainsKey(pp.Name))
                {
                    Plugin.Items[pp.Name].LoadSettings(pp.PluginSettings);
                }
            }
        }
Exemplo n.º 26
0
        public Potentiometer(IDigitalWriteRead digitalWriteRead, int inPin, int outPin, int minCalibratedValue, int maxCalibratedValue, int sampleFrequencySeconds = 500, bool reversePercentageValue = false, int timeOutMaxValue = 2000)
        {
            this._timeOut                = new TimeOut(sampleFrequencySeconds);
            this._inPin                  = inPin;
            this._outPin                 = outPin;
            this._digitalWriteRead       = digitalWriteRead;
            this._minCalibratedValue     = minCalibratedValue;
            this._maxCalibratedValue     = maxCalibratedValue;
            this._rangeCalibratedValue   = maxCalibratedValue - minCalibratedValue;
            this._timeOutMaxValue        = timeOutMaxValue;
            this._reversePercentageValue = reversePercentageValue;

            

            this._digitalWriteRead.SetPinMode(_outPin, PinMode.Output);
        }
Exemplo n.º 27
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("Nusbio not detected");
                return;
            }

            using (var nusbio = new Nusbio(serialNumber))
            {
                Cls(nusbio);
                var halfSeconds = new TimeOut(500);
                /*
                    Mcp300X - SPI Config
                    gpio 0 - CLOCK
                    gpio 1 - MOSI
                    gpio 2 - MISO
                    gpio 3 - SELECT
                */
                ad = new Mcp3008(nusbio, 
                    selectGpio: NusbioGpio.Gpio3, mosiGpio:  NusbioGpio.Gpio1, 
                     misoGpio:  NusbioGpio.Gpio2, clockGpio: NusbioGpio.Gpio0);
                ad.Begin();

                var analogTempSensor = new Tmp36AnalogTemperatureSensor(nusbio);
                analogTempSensor.Begin();

                var analogMotionSensor = new AnalogMotionSensor(nusbio, 4);
                analogMotionSensor.Begin();

                var lightSensor      = new AnalogLightSensor(nusbio);
                lightSensor.AddCalibarationValue("Dark", 0, 100);
                lightSensor.AddCalibarationValue("Office Night", 101, 299);
                lightSensor.AddCalibarationValue("Office Day", 300, 400);
                lightSensor.AddCalibarationValue("Outdoor Sun Light", 401, 1000);
                lightSensor.Begin();

                while(nusbio.Loop())
                {
                    if (halfSeconds.IsTimeOut())
                    {
                        const int lightSensorAnalogPort       = 7;
                        const int motionSensorAnalogPort      = 6;
                        const int temperatureSensorAnalogPort = 5;


                        ConsoleEx.WriteLine(0, 2, string.Format("{0,-20}", DateTime.Now, lightSensor.AnalogValue), ConsoleColor.Cyan);

                        lightSensor.SetAnalogValue(ad.Read(lightSensorAnalogPort));
                        ConsoleEx.WriteLine(0, 4, string.Format("Light Sensor      : {0} (ADValue:{1:000.000})", lightSensor.CalibratedValue.PadRight(18), lightSensor.AnalogValue), ConsoleColor.Cyan);

                        analogTempSensor.SetAnalogValue(ad.Read(temperatureSensorAnalogPort));
                        ConsoleEx.WriteLine(0, 6, string.Format("Temperature Sensor: {0:00.00}C, {1:00.00}F     (ADValue:{2:0000})    ",  analogTempSensor.GetTemperature(AnalogTemperatureSensor.TemperatureType.Celsius), analogTempSensor.GetTemperature(AnalogTemperatureSensor.TemperatureType.Fahrenheit), analogTempSensor.AnalogValue), ConsoleColor.Cyan);

                        analogMotionSensor.SetAnalogValue(ad.Read(motionSensorAnalogPort));
                        var motionType = analogMotionSensor.MotionDetected();
                        if (motionType == MotionSensorPIR.MotionDetectedType.MotionDetected || motionType == MotionSensorPIR.MotionDetectedType.None)
                        {
                            ConsoleEx.Write(0, 8, string.Format("Motion Sensor     : {0,-20} (ADValue:{1:000})", motionType, analogMotionSensor.AnalogValue), ConsoleColor.Cyan);
                        }
                    }

                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;

                        if (k == ConsoleKey.C)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.Q) {
                            
                            break;
                        }
                        Cls(nusbio);
                    }
                }
            }
            Console.Clear();
        }
Exemplo n.º 28
0
 public LightSensorWithCapacitor(Nusbio nusbio, NusbioGpio gpio, int sampleFrequencySeconds = 2000)
 {
     _timeOut = new TimeOut(sampleFrequencySeconds);
     this._gpio              = gpio;
     this._nusbio           = nusbio;
 }
Exemplo n.º 29
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();
            
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("nusbio not detected");
                return;
            }

            var clockPin           = NusbioGpio.Gpio5; 
            var dataOutPin         = NusbioGpio.Gpio6; 
            var motionSensorPin    = NusbioGpio.Gpio0; 

            using (var nusbio = new Nusbio(serialNumber))
            {
                _MCP9808_TemperatureSensor = new MCP9808_TemperatureSensor(nusbio, dataOutPin, clockPin);
                if (!WaitForSensorsToBeReady(_MCP9808_TemperatureSensor))
                    Environment.Exit(1);

                var motionSensor = new MotionSensorPIR(nusbio, motionSensorPin, 3);

                Cls(nusbio);
                var every5Seconds  = new TimeOut(1000*5);
                var everyHalfSecond = new TimeOut(500);

                ReceiveCommands(AzureIoTHubDevices.TemperatureDevice);

                while(nusbio.Loop())
                {
                    if (everyHalfSecond.IsTimeOut())
                    {
                        var motionType = motionSensor.MotionDetected();
                        if (motionType == MotionSensorPIR.MotionDetectedType.MotionDetected)
                        {
                            ConsoleEx.WriteLine(0, 4, string.Format("[{0}] MotionSensor:{1,-20}", DateTime.Now, motionType), ConsoleColor.DarkCyan);
                            AzureIoTHubDevices.MotionSensorDevice.Update(DateTime.UtcNow);
                        }
                        else if (motionType == MotionSensorPIR.MotionDetectedType.None)
                        {
                            ConsoleEx.Write(0, 4, string.Format("[{0}] MotionSensor:{1,-20}", DateTime.Now, motionType), ConsoleColor.DarkCyan);
                        }
                    }
                    if (every5Seconds.IsTimeOut(isFirstTime:true)) 
                    {
                        double celsius = _MCP9808_TemperatureSensor.GetTemperature(MCP9808_TemperatureSensor.TemperatureType.Celsius);
                        ConsoleEx.WriteLine(0, 5, string.Format("[{0}]Temperature {1:000.00}C, {2:000.00}F, {3:00000.00}K",  DateTime.Now, celsius, _MCP9808_TemperatureSensor.CelsiusToFahrenheit(celsius), _MCP9808_TemperatureSensor.CelsiusToKelvin(celsius) ), ConsoleColor.Cyan);
                        if(AzureIoTHubDevices.TemperatureDevice.ShouldUpdate(celsius))
                            AzureIoTHubDevices.TemperatureDevice.Update(celsius);
                    }
                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;
                        if (k == ConsoleKey.T)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.D0)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.C)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.Q) break;
                        Cls(nusbio);
                    }
                }
            }
            Console.Clear();
        }
Exemplo n.º 30
0
        private void RaiseTimeOut()
        {
#pragma warning disable 618
            TimeOut?.Invoke();
#pragma warning restore 618
        }
Exemplo n.º 31
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();
            //var serialNumber = "LD2Ub9pAg";
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("nusbio not detected");
                return;
            }
            
            var clockPin           = NusbioGpio.Gpio6; // White, Arduino A5
            var dataOutPin         = NusbioGpio.Gpio5; // Green, Arduino A4

            using (var nusbio = new Nusbio(serialNumber))
            {
                _MCP9808_TemperatureSensor = new MCP9808_TemperatureSensor(nusbio, dataOutPin, clockPin);
                if (!_MCP9808_TemperatureSensor.Begin())
                {
                    Console.WriteLine("MCP9808 not detected on I2C bus");
                    return;
                }

                Cls(nusbio);

                var everySecond = new TimeOut(1000);

                while(nusbio.Loop())
                {
                    if (everySecond.IsTimeOut())
                    {
                        double celsius = 0;
                        for (var i = 0; i < 3; i++)
                        {
                            celsius = _MCP9808_TemperatureSensor.GetTemperature(MCP9808_TemperatureSensor.TemperatureType.Celsius);
                        }

                        ConsoleEx.WriteLine(1, 2, 
                            string.Format("Temperature Celsius:{0:000.00}, Fahrenheit:{1:000.00}, Kelvin:{2:00000.00}", 
                            celsius,
                            _MCP9808_TemperatureSensor.CelsiusToFahrenheit(celsius),
                            _MCP9808_TemperatureSensor.CelsiusToKelvin(celsius)
                            ), ConsoleColor.Cyan);
                    }
                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;
                        if (k == ConsoleKey.T)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.D0)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.C)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.Q) break;
                        Cls(nusbio);
                    }
                }
            }
            Console.Clear();
        }
Exemplo n.º 32
0
 private void RaiseTimeOut()
 {
     TimeOut.SafeInvoke();
 }
Exemplo n.º 33
0
 //-------------------------------------------
 // life cycle
 //-------------------------------------------
 void Awake()
 {
     requests = new Queue <Request> ();
     timeout  = new TimeOut();
 }
Exemplo n.º 34
0
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            if (buttonRefresh.Text == labelRefresh.Text)
            {
                if (Config.ServerIP.Length == 0)
                {

                }
                IPEndPoint iep = GetEndPoint(string.Format("{0}:{1}", Config.ServerIP, Config.ServerPort));
                if (iep != null)
                {
                    SetState(State.Refreshing);
                    SetControlText(labelInfo, labelConnecting.Text);
            #if !Remoting
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    time = new TimeOut(Config.TimeOutInterval, new TimeOut.TimeOutCallBack(TimeOut), client);
                    time.Start();//开始计时
                    client.BeginConnect(iep, new AsyncCallback(Refresh), iep);
            #else
                    td = new Thread(new ParameterizedThreadStart(Refresh));
                    td.Start(iep);
            #endif
                }
            }
            else
            {
                SetState(State.Idle);
            #if !Remoting
                if (client != null)
                {
                    client.Close();
                }
            #else
                if (td != null && td.ThreadState != ThreadState.Stopped)
                {
                    td.Abort();
                }
            #endif
            }
        }
Exemplo n.º 35
0
 /// <summary> Invoke TimeOut event </summary>
 /// <param name="sender"> Sender </param>
 /// <param name="e"> Arguments </param>
 private void OnTimeOut(object sender, ClockEventArgs e)
 {
     TimeOut?.Invoke(sender, e);
 }
Exemplo n.º 36
0
 private void RaiseTimeOut()
 {
     TimeOut?.Invoke();
 }
Exemplo n.º 37
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("Nusbio not detected");
                return;
            }

            using (var nusbio = new Nusbio(serialNumber))
            {
                Cls(nusbio);

                int counter       = 0;
                _machineInfo      = new MachineInfo();
                var secondTimeOut = new TimeOut(1000);
                _liquidCrystal    = new LiquidCrystal(nusbio, rs:0, enable:1, d0:2, d1:3, d2:4, d3:5);

                _liquidCrystal.Begin(16, 2);
                _liquidCrystal.Clear();

                while(nusbio.Loop())
                {
                    if (secondTimeOut.IsTimeOut())
                    {
                        counter++;
                        DisplayTime(_liquidCrystal);
                        if(counter % 5 ==0)
                            NusbioRocks(_liquidCrystal);
                        if(counter % 8 ==0)
                            ProgressBarDemo(_liquidCrystal);
                    }

                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;
                        if (k == ConsoleKey.D)
                        {
                            DisplaySpeedTest(_liquidCrystal);
                            _liquidCrystal.Clear();
                        }
                        if (k == ConsoleKey.A)
                        {
                            ApiDemo(_liquidCrystal);
                            _liquidCrystal.Clear();
                        }
                        if (k == ConsoleKey.C)
                        {
                            CustomCharDemo(_liquidCrystal);
                            _liquidCrystal.Clear();
                        }
                        
                        if (k == ConsoleKey.F)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.Q) {
                            _liquidCrystal.Clear();
                            break;
                        }
                        Cls(nusbio);
                    }
                }
            }

            Console.Clear();
        }
Exemplo n.º 38
0
 public virtual void Initialize(TimeOut timeout)
 {
     this.timeout = timeout;
 }
Exemplo n.º 39
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio Initializing");
            var serialNumber = Nusbio.Detect();
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("Nusbio not detected");
                return;
            }

            var halfSecondTimeOut = new TimeOut(20);

            using (var nusbio = new Nusbio(serialNumber: serialNumber, webServerPort: 1964))
            {
                nusbio.UrlEvent += NusbioUrlEvent;
                Cls(nusbio);
                while (nusbio.Loop(20))
                {
                    if (Console.KeyAvailable)
                    {
                        var kk        = Console.ReadKey(true);
                        var blinkMode = kk.Modifiers == ConsoleModifiers.Shift;
                        var key       = kk.Key;

                        if (key == ConsoleKey.Q) break;
                        if (key == ConsoleKey.C) Cls(nusbio);

                        if (nusbio.IsAsynchronousSequencerOn) // If background sequencer for animation is on then turn it off if we receive any key
                        {
                            nusbio.CancelAsynchronousSequencer();
                            continue;
                        }

                        if (blinkMode)
                        {
                            if (key == ConsoleKey.D0) nusbio.GPIOS[NusbioGpio.Gpio0].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D1) nusbio.GPIOS[NusbioGpio.Gpio1].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D2) nusbio.GPIOS[NusbioGpio.Gpio2].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D3) nusbio.GPIOS[NusbioGpio.Gpio3].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D4) nusbio.GPIOS[NusbioGpio.Gpio4].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D5) nusbio.GPIOS[NusbioGpio.Gpio5].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D6) nusbio.GPIOS[NusbioGpio.Gpio6].AsLed.SetBlinkMode(1000, 80);
                            if (key == ConsoleKey.D7) nusbio.GPIOS[NusbioGpio.Gpio7].AsLed.SetBlinkMode(1000, 80);
                        }
                        else
                        {
                            if (key == ConsoleKey.F1) AnimateBlocking1(nusbio);
                            if (key == ConsoleKey.F2) AnimateNonBlocking2(nusbio);
                            if (key == ConsoleKey.F3) AnimateBlocking3(nusbio);
                            if (key == ConsoleKey.F4) AnimateBlocking4(nusbio);

                            if (key == ConsoleKey.D0) ReverseGpio(NusbioGpio.Gpio0, nusbio);
                            if (key == ConsoleKey.D1) ReverseGpio(NusbioGpio.Gpio1, nusbio);
                            if (key == ConsoleKey.D2) ReverseGpio(NusbioGpio.Gpio2, nusbio);
                            if (key == ConsoleKey.D3) ReverseGpio(NusbioGpio.Gpio3, nusbio);
                            if (key == ConsoleKey.D4) ReverseGpio(NusbioGpio.Gpio4, nusbio);
                            if (key == ConsoleKey.D5) ReverseGpio(NusbioGpio.Gpio5, nusbio);
                            if (key == ConsoleKey.D6) ReverseGpio(NusbioGpio.Gpio6, nusbio);
                            if (key == ConsoleKey.D7) ReverseGpio(NusbioGpio.Gpio7, nusbio);

                            if (key == ConsoleKey.A) nusbio.SetAllGpioOutputState(PinState.Low);
                            if (key == ConsoleKey.W) System.Diagnostics.Process.Start(nusbio.GetWebServerUrl());
                        }
                        ShowNusbioState(nusbio);
                    }
                    else { 
                        if(halfSecondTimeOut.IsTimeOut()) ShowNusbioState(nusbio);
                    }
                }
            }            
            Console.Clear();
        }
Exemplo n.º 40
0
 public string ToJoin()
 {
     return(Secret + "," + TimeOut.ToString("yyyy-MM-dd HH:mm:ss"));
 }
Exemplo n.º 41
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();
            //var serialNumber = "LD2Ub9pAg";
            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("nusbio not detected");
                return;
            }
                        
            using (var nusbio = new Nusbio(serialNumber)) // , 
            {
                Cls(nusbio);

                var _4DIGITS7SEGMENTS_ADDR = 0x70 + 2;
                var clockPin               = NusbioGpio.Gpio0; // White
                var dataOutPin             = NusbioGpio.Gpio1; // Green
                _4digits                   = new _4Digits7Segments(nusbio, dataOutPin, clockPin);
                _4digits.Begin(_4DIGITS7SEGMENTS_ADDR);
                _4digits.Clear(true);
                
                var oneSecondTimeOut = new TimeOut(1000);

                while(nusbio.Loop())
                {
                    if(oneSecondTimeOut.IsTimeOut()) { // Make the colon blink at a 1 second rate
                        
                        var t = DateTime.Now;

                        _4digits.Clear();
                        _4digits.Write(string.Format("{0}{1}", t.Minute.ToString("00"), t.Second.ToString("00")));

                        //if(twoSecondTimeOut.Counter % 2 == 0) 
                        //    _4digits.Write(string.Format("{0}{1}", t.Minute.ToString("00"), t.Second.ToString("00")));
                        //else
                        //    _4digits.Write(string.Format("{0}{1}", t.Hour.ToString("00"), t.Minute.ToString("00")));

                        _4digits.WriteDisplay();
                        _4digits.DrawColon(!_4digits.ColonOn);
                    }

                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;
                        if (k == ConsoleKey.D1)
                        {
                            Demo1();
                        }
                        if (k == ConsoleKey.D2)
                        {
                            Demo1To100();
                        }
                        if (k == ConsoleKey.D3)
                        {
                            DemoScrollNumber();
                        }
                        if (k == ConsoleKey.D4)
                        {
                            Demo1To10000();
                        }
                        if (k == ConsoleKey.C)
                        {
                            Cls(nusbio);
                            _4digits.Clear(true);
                        }
                        if (k == ConsoleKey.Q) {
                            _4digits.Clear(true);
                            break;
                        }
                        Cls(nusbio);
                    }
                }
            }
            Console.Clear();
        }
Exemplo n.º 42
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Nusbio initialization");
            var serialNumber = Nusbio.Detect();

            if (serialNumber == null) // Detect the first Nusbio available
            {
                Console.WriteLine("Nusbio not detected");
                return;
            }

            var lightSensorAnalogPort  = 2;
            var motionSensorAnalogPort = 0;
            var buttonSensorAnalogPort = 1;
            var ledGpio = NusbioGpio.Gpio5;

            using (var nusbio = new Nusbio(serialNumber))
            {
                Cls(nusbio);

                var halfSeconds = new TimeOut(333);

                // Mcp300X Analog To Digital - SPI Config
                ad = new MCP3008(nusbio,
                                 selectGpio: NusbioGpio.Gpio3,
                                 mosiGpio:   NusbioGpio.Gpio1,
                                 misoGpio:   NusbioGpio.Gpio2,
                                 clockGpio:  NusbioGpio.Gpio0);
                ad.Begin();

                var analogMotionSensor = new AnalogMotionSensor(nusbio, 4);
                analogMotionSensor.Begin();

                var button = new AnalogButton(nusbio);

                var lightSensor = CalibrateLightSensor(new AnalogLightSensor(nusbio), AnalogLightSensor.LightSensorType.CdsPhotoCell_3mm_45k_140k);
                lightSensor.Begin();

                // Analog Port 5, 6, 7 are only available in
                // Analog Extension PCBv2
                const int    multiButtonPort = 5;
                AnalogSensor multiButton     = null;
                //multiButton = new AnalogSensor(nusbio, multiButtonPort);
                //multiButton.Begin();

                // TC77 Temperature Sensor SPI
                var tc77 = new TC77(nusbio,
                                    clockGpio:  NusbioGpio.Gpio0,
                                    mosiGpio:   NusbioGpio.Gpio1,
                                    misoGpio:   NusbioGpio.Gpio2,
                                    selectGpio: NusbioGpio.Gpio4
                                    );
                tc77.Begin();

                if (nusbio.Type == NusbioType.NusbioType1_Light)
                {
                    tc77._spi.SoftwareBitBangingMode     = true;
                    ad._spiEngine.SoftwareBitBangingMode = true;
                }

                while (nusbio.Loop())
                {
                    if (halfSeconds.IsTimeOut())
                    {
                        nusbio[ledGpio].AsLed.ReverseSet();

                        ConsoleEx.WriteLine(0, 2, string.Format("{0,-15}", DateTime.Now), ConsoleColor.Cyan);

                        lightSensor.SetAnalogValue(ad.Read(lightSensorAnalogPort));
                        ConsoleEx.WriteLine(0, 4, string.Format("Light Sensor       : {0,-18} (ADValue:{1:000.000}, Volt:{2:0.00})       ",
                                                                lightSensor.CalibratedValue.PadRight(18), lightSensor.AnalogValue, lightSensor.Voltage), ConsoleColor.Cyan);

                        analogMotionSensor.SetAnalogValue(ad.Read(motionSensorAnalogPort));
                        var motionType = analogMotionSensor.MotionDetected();
                        if (motionType == DigitalMotionSensorPIR.MotionDetectedType.MotionDetected || motionType == DigitalMotionSensorPIR.MotionDetectedType.None)
                        {
                            ConsoleEx.Write(0, 6, string.Format("Motion Sensor      : {0,-18} (ADValue:{1:000.000}, Volt:{2:0.00})    ",
                                                                motionType, analogMotionSensor.AnalogValue, analogMotionSensor.Voltage), ConsoleColor.Cyan);
                        }

                        ConsoleEx.WriteLine(0, 8, string.Format("Temperature Sensor : {0:0.00}C {1:0.00}F    ", tc77.GetTemperature(),
                                                                tc77.GetTemperature(AnalogTemperatureSensor.TemperatureType.Fahrenheit)), ConsoleColor.Cyan);

                        button.SetAnalogValue(ad.Read(buttonSensorAnalogPort));
                        ConsoleEx.WriteLine(0, 10, string.Format("Button             : {0,-18} [{1:0000}, {2:0.00}V]   ",
                                                                 button.Down ? "Down" : "Up", button.AnalogValue, button.Voltage), ConsoleColor.Cyan);

                        if (multiButton != null)
                        {
                            multiButton.SetAnalogValue(ad.Read(multiButtonPort));
                            ConsoleEx.Write(0, 12, string.Format("Multi Button       : {0,-18} (ADValue:{1:000.000}, Volt:{2:000.000})",
                                                                 multiButton.AnalogValue > 2 ? "Down" : "Up  ",
                                                                 multiButton.AnalogValue,
                                                                 multiButton.Voltage), ConsoleColor.Cyan);
                        }
                    }

                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey(true).Key;

                        if (k == ConsoleKey.C)
                        {
                            Cls(nusbio);
                        }
                        if (k == ConsoleKey.Q)
                        {
                            break;
                        }
                        Cls(nusbio);
                    }
                }
            }
            Console.Clear();
        }
Exemplo n.º 43
0
        /// <summary>
        /// 获取指纹
        /// </summary>
        /// <param name="buffer">指纹在设备中临时存放位置 1 2</param>
        /// <returns></returns>
        int GetFinger(int buffer)
        {
            TimeOut = 20;
            int ret = 0;

            byte[] ImgData = new byte[ImageSize];
            int[]  ImgLen  = new int[1];
            int    iBuffer = buffer;

BEIG1:
            ret = Fingerdll.ZAZGetImage(hHandle, nDevAddr);              //获取图象
            if (ret == 0)
            {
                ShowInfomation("获取图像成功...");
            }
            else if (ret == 2)
            {
                //超时判断
                ShowInfomation("等待手指平放在传感器上-" + TimeOut.ToString() + "秒");
                if (TimeOut < 0)
                {
                    ShowInfomation("等待超时");
                    return(0);
                }
                TimeOut--;
                Thread.Sleep(1000);
                goto BEIG1;
            }
            else
            {
                ShowInfomation(Fingerdll.ZAZErr2Strt(ret));
                return(0);
            }

            //////////////////////////////////////////////////////////////////////////
            //不涉及图像,下面可以省略
            /****************上传图像*********/

            ShowInfomation("正在上传图像请等待...");
            ret = Fingerdll.ZAZUpImage(hHandle, nDevAddr, ImgData, ImgLen);              //上传图象
            if (ret != 0)
            {
                ShowInfomation(Fingerdll.ZAZErr2Strt(ret));
                return(0);
            }
            //strFile = System.Windows.Forms.Application.StartupPath + "\\ZAZFinger.bmp";
            strFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZAZFinger.bmp");
            ret     = Fingerdll.ZAZImgData2BMP(ImgData, strFile);
            if (ret != 0)
            {
                ShowInfomation(Fingerdll.ZAZErr2Strt(ret));
                return(0);
            }
            ShowImage(strFile);
            //ret = Fingerdll.ZAZShowFingerData(fpbmp.Handle, ref ImgData[0]);
            //////////////////////////////////////////////////////////////////////////
            /****************生成特征 *********/
            ret = Fingerdll.ZAZGenChar(hHandle, nDevAddr, iBuffer);              //生成模板
            if (ret != 0)
            {
                ShowInfomation(Fingerdll.ZAZErr2Strt(ret));
                return(0);
            }
            else
            {
                ShowInfomation("生成指纹特征" + buffer.ToString());
            }
            Thread.Sleep(10);
BEIG2:
            if (ret == 0)
            {
                ret = Fingerdll.ZAZGetImage(hHandle, nDevAddr);                  //获取图象
                ShowInfomation("等待手指拿开-");
                goto BEIG2;
            }
            else if (ret == 1)
            {
                ShowInfomation(Fingerdll.ZAZErr2Strt(ret));
                return(0);
            }
            return(1);
        }