public void Start() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Loopback, SocketWorker.Port); SocketWorker.StartNew(socket); }
/// <summary> /// Send the data of the alarm to the arduino. /// </summary> /// <param name="command">The command we want to execute, (Add, edit or remove)</param> /// <param name="alarm">The alarm we want to send.</param> private void SendAlarmToArduino(string command, Alarm alarm) { SocketWorker.Send( command, alarm.Id.ToString(), alarm.Time.ToAgnosticString() ); }
/// <summary> /// Disconnect to whatever we are connected to. /// Also forget the previous connection details. /// </summary> private async void Disconnect() { SocketWorker.Disconnect(); await IOWorker.ClearFile(AppFiles.Connection, AppFileExtension.JSON); SetConnectionDetails(); Toast.MakeText(this, Resource.String.toast_disconnected, ToastLength.Long).Show(); }
/// <summary> /// Tell the arduino to sync with the time we've set from the app. /// </summary> private void SyncDateTime() { DateTime time = new DateTime( dpDate.DateTime.Year, dpDate.DateTime.Month, dpDate.DateTime.Day, npTimeHour.Value, npTimeMinute.Value, 0 ); //Sync time with arduino. SocketWorker.Send(Commands.SyncTime, time.ToAgnosticString()); }
public void Start() { //Слушаем порт var listener = new TcpListener(IPAddress.Any, SocketWorker.Port); listener.Start(); //Принимаем подключения клиентов while (true) { var socket = listener.AcceptSocket(); SocketWorker.StartNew(socket, true); } }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); base.SetContentView(Resource.Layout.main); //TODO, REMOVE: Debug code. await IOWorker.ClearFile(AppFiles.Alarm, AppFileExtension.JSON); await IOWorker.ClearFile(AppFiles.LightSocket, AppFileExtension.JSON); //await IOWorker.ClearFile(AppFiles.Connection, AppFileExtension.JSON); //Fetch the buttons. buttonSnoozeAlarms = FindViewById <Button>(Resource.Id.btn_quick_snooze); buttonStopAlarms = FindViewById <Button>(Resource.Id.btn_quick_stop); buttonAlarmActivity = FindViewById <Button>(Resource.Id.btn_alarm_management); buttonConnectionActivity = FindViewById <Button>(Resource.Id.btn_connection_management); buttonKakuActivity = FindViewById <Button>(Resource.Id.btn_light_management); buttonTimeActivity = FindViewById <Button>(Resource.Id.btn_time_management); textStatus = FindViewById <TextView>(Resource.Id.text_status); //Tell each button to start a different activity. buttonAlarmActivity.Click += (o, s) => StartActivity(typeof(AlarmActivity)); buttonConnectionActivity.Click += (o, s) => StartActivity(typeof(ConnectionActivity)); buttonKakuActivity.Click += (o, s) => StartActivity(typeof(KakuActivity)); buttonTimeActivity.Click += (o, s) => StartActivity(typeof(TimeActivity)); buttonSnoozeAlarms.Click += (o, s) => SnoozeAlarms(); buttonStopAlarms.Click += (o, s) => StopAlarms(); SetUI(SocketWorker.IsConnected); //Check if we previously connected and try those connection details. ConnectionData data = await IOWorker.ReadFile <ConnectionData>(AppFiles.Connection); //Try to connect to connections details we used earlier. if (!data.Equals(default(ConnectionData))) { if (!SocketWorker.IsConnected) { SockErr err = SocketWorker.Connect(data.IP, data.Port); //If we do not have an error, notify the user we connected successfully if (err == SockErr.None) { Toast.MakeText(this, Resource.String.toast_connected, ToastLength.Long).Show(); SetUI(SocketWorker.IsConnected); } } } }
/// <summary> /// Make a connection to the arduino. /// Parse the user inputs and try to connect. /// </summary> private void Connect() { //Get user input string ip = editTextIp.Text; string port = editTextPort.Text; //Sanitize the user input. if (!IsValidIP(ip)) { Toast.MakeText(this, Resource.String.error_invalid_ip, ToastLength.Long).Show(); return; } if (!IsValidPort(port)) { Toast.MakeText(this, Resource.String.error_invalid_port, ToastLength.Long).Show(); return; } SockErr err = SocketWorker.Connect(ip, int.Parse(port)); //Handle possible states after connecting. switch (err) { case SockErr.None: SetConnectionDetails(); SaveConnectionDetails(ip); break; case SockErr.ConnectionDuplicate: Toast.MakeText(this, Resource.String.sockerr_duplicate, ToastLength.Long).Show(); break; case SockErr.ConnectionTimeout: Toast.MakeText(this, Resource.String.sockerr_timeout, ToastLength.Long).Show(); break; default: Toast.MakeText(this, Resource.String.sockerr_failed, ToastLength.Long).Show(); break; } }
public bool StartServer() { if (running) { return(false); } Console.Write("* - required parameter. \nInput <[IP-address*] [port*]> for start: "); var inputData = Console.ReadLine(); var startParameters = inputData.Split(' '); var ip = IPAddress.Parse(startParameters[0]); var port = int.Parse(startParameters[1]); socketWorker = new SocketWorker(); workerThread = new Thread(this.MonitorPort); workerThread.Start(new TripleEndPointModel() { EndPoint = new IPEndPoint(ip, port), EndPointUDPRead = new IPEndPoint(ip, port + 1), EndPointUDPWrite = new IPEndPoint(ip, port + 2) }); running = true; return(true); }
/// <summary> /// Called when any of the 5 light sockets checkboxes change. /// Required to sync up with the arduino. /// </summary> /// <param name="id">The id of the light socket we are changing.</param> private async void OnLightSocketChanged(int id) { bool state = false; //Check which kaku was edited, set the state accordingly switch (id) { case 1: state = cbLightSocket1.Checked; socketStates[0] = state; break; case 2: state = cbLightSocket2.Checked; socketStates[1] = state; break; case 3: state = cbLightSocket3.Checked; socketStates[2] = state; break; case 4: state = cbLightSocket4.Checked; socketStates[3] = state; break; case 5: state = cbLightSocket5.Checked; socketStates[4] = state; break; } //Save the changes to disk. await IOWorker.SaveFile(AppFiles.LightSocket, AppFileExtension.JSON, socketStates); //Disable the checkboxes for 1/3 of a second. //This could lead to the disk and arduino being spammed //by the users, so we want to protect them from doing to. await Task.Run(async() => { cbLightSocket1.Enabled = false; cbLightSocket2.Enabled = false; cbLightSocket3.Enabled = false; cbLightSocket4.Enabled = false; cbLightSocket5.Enabled = false; await Task.Delay(333); }).ContinueWith((task) => { cbLightSocket1.Enabled = true; cbLightSocket2.Enabled = true; cbLightSocket3.Enabled = true; cbLightSocket4.Enabled = true; cbLightSocket5.Enabled = true; }); //Syncronize arduino from app. string s = state ? "1" : "0"; SocketWorker.Send(Commands.SyncKaku, id.ToString(), s); }
/// <summary> /// 线程处理函数 如果登陆成功后用来接收行情 /// </summary> /// <param name="obj"></param> public static void ReceiveThread(object obj) { SocketWorker sw = ((SocketWorker)obj); Socket sock = sw.getSocket(); byte[] bufferArr = new byte[2 * 1024]; //包体 byte[] PDUHeadArr = new byte[PDUHead.PDU_HEAD_LEN]; //数据长度 int totalLen = 0; //实际数据长度,初始为0 int readLen = 0; //读取的长度 try { for (; sock.Connected;) { //初始化缓存 Array.Clear(PDUHeadArr, 0, PDUHeadArr.Length); Array.Clear(bufferArr, 0, bufferArr.Length); //接收包头数据 int headBuf = PDUHead.PDU_HEAD_LEN; int headLeft = PDUHead.PDU_HEAD_LEN; int headOffset = 0; while (sock.Connected && headLeft > 0) { readLen = sock.Receive(PDUHeadArr, headOffset, headLeft, SocketFlags.None); if (readLen < 0) { throw new MarketException("接收行情包头数据异常!"); } if (readLen == 0) { break; } headOffset += readLen; headLeft -= readLen; } //判断接收的数据长度是否有误 readLen = headBuf - headLeft; //抛出异常 if (readLen != PDUHead.PDU_HEAD_LEN) { throw new MarketException("接收行情包头数据异常!"); } //解析头信息 PDUHead phed = PDUHead.byteToPDUHead(PDUHeadArr); //查看缓存区大小是否够用。 totalLen = phed.totalLength; if (totalLen > bufferArr.Length) { bufferArr = new byte[totalLen]; } //接收包体数据 int bodyBuf = totalLen - PDUHead.PDU_HEAD_LEN; int bodyLeft = totalLen - PDUHead.PDU_HEAD_LEN; int bodyOffset = 0; while (sock.Connected && bodyLeft > 0) { readLen = sock.Receive(bufferArr, bodyOffset, bodyLeft, SocketFlags.None);//读取socket数据 if (readLen < 0) { throw new MarketException("接收行情包体数据异常!"); } if (readLen == 0) { break; } bodyLeft -= readLen; bodyOffset += readLen; } readLen = bodyBuf - bodyLeft; //抛出异常 if (readLen != totalLen - PDUHead.PDU_HEAD_LEN) { throw new MarketException("接收行情包体数据异常!"); } //查看接收数据是否是行情数据 if (phed.commandId == PDUHead.JH_REALTRADEINFO) { Tick tck = Tick.byteToTick(bufferArr); if (tck == null) { throw new MarketException("解析行情数据包异常!"); } sw.GetJHMarket().ReturnTick(tck); sw.GetJHMarket().OnHeartTest(phed.svrTime); continue; } //查看数据是否是心跳数据 if (phed.commandId == PDUHead.JH_ACTIVETEST) { sw.GetJHMarket().OnHeartTest(phed.svrTime); continue; } } //异常 }catch (MarketException me) { sw.GetJHMarket().OnError("error@" + "Socket Worker Thread," + me.Message); JHLog.forMarketLog("Socket Worker Thread," + me.ToString()); return; } catch (Exception ex) { JHLog.forMarketLog("Socket Worker Thread," + ex.ToString()); return; } }
/// <summary> /// Send the stop all command to the arduino. /// </summary> private void StopAlarms() { SocketWorker.Send(Commands.AlarmStop); }
/// <summary> /// Send the command to snooze all alarms on the arduino. /// </summary> private void SnoozeAlarms() { SocketWorker.Send(Commands.AlarmSnooze); }
private void tmr_scoreUpdate_Tick(object sender, EventArgs e) { settime -= tmr_scoreUpdate.Interval; if (SocketWorker.IsBusy == false) { SocketWorker.RunWorkerAsync(); } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * lsb_info.Items.Add("WAITING FOR CONNECTION..."); * lsb_info.Items.Add("Client local IpAddress is :" + IPAddress.Parse(((IPEndPoint)server.LocalEndPoint).Address.ToString())); * lsb_info.Items.Add("Client connected with port number " + ((IPEndPoint)server.LocalEndPoint).Port.ToString()); * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ try { if (client != null) { byte[] rcvBuffer = new byte[32]; // buffer to store inputs in bytes lsb_info.Items.Add("Accept client - " + client.RemoteEndPoint); client.Receive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None); // encode byte to string and then convert to int var parts = Encoding.UTF8.GetString(rcvBuffer).Split(' '); // split input string into two parts string player_id = parts[0]; // convert scores from string to int int score_temp = Convert.ToInt32(parts[1]); lsb_info.Items.Add("Recieved from client - " + player_id); lsb_info.Items.Add("Client Score: " + score_temp); // keep the listbox scroll to the bottom automatically lsb_info.SelectedIndex = lsb_info.Items.Count - 1; // store player_id as key into another dictionary name_score_dic.Add(player_id, score_temp); // add client's score to sorted score dictionary score_sortdic.Add(score_temp, player_id); // increment number of connections lbl_numConn.Text = name_score_dic.Count.ToString(); client.Close(); } } catch (Exception ex) { //lsb_info.Items.Add(ex.Message); client.Close(); } // if time is up, stop the timer and generate a winner if (settime <= 0) { // increment number of connections lbl_numConn.Text = name_score_dic.Count.ToString(); // stop the timer tmr_scoreUpdate.Enabled = false; // find out the winner dataanalysis(ref score_sortdic, ref name_score_dic); // kill the server connection server.Close(); } // increment timer lblTimerSec.Text = ((settime / 1000) % 60).ToString().PadLeft(2, '0'); lblTimerMin.Text = (((settime / 1000) - (settime / 1000) % 60) / 60).ToString().PadLeft(2, '0'); }
/// <summary> /// 构造函数 /// </summary> public JHMarket() { socketWorker = new SocketWorker(this); }
/// <summary> /// Send the remove alarm command to the arduino. /// </summary> /// <param name="alarm">The alarm we want to remove.</param> private void SendRemoveAlarm(Alarm alarm) { SocketWorker.Send( Commands.AlarmRemove, alarm.Id.ToString() ); }