/// <summary> /// send a given message to Server. /// if sending didn't succeed - the connection is closed. /// </summary> /// <param name="msg">message to send to Server</param> public void SendDataToServer(CommunicationProtocol msg) { try { string jsonCommand = JsonConvert.SerializeObject(msg); NetworkStream stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); try { mutex.WaitOne(); writer.Write(jsonCommand); } catch (Exception e) { throw e; } finally { mutex.ReleaseMutex(); } } catch (Exception) { ConnectionIsBroken(this, null); CloseClient(); } }
/// <summary> /// listens to Server /// </summary> public void RecieveDataFromServer() { new Task(() => { NetworkStream stream = this.client.GetStream(); BinaryReader reader = new BinaryReader(stream); while (!stop) { try { string response = reader.ReadString(); // Wait for response from serve CommunicationProtocol msg = JsonConvert.DeserializeObject <CommunicationProtocol>(response); MsgRecievedFromServer(this, ClientServerArgsParser.Parse(msg)); //Thread.Sleep(1000); // Update information every 1 second } catch (Exception) { ConnectionIsBroken(this, null); CloseClient(); } } CloseClient(); }).Start(); }
public ServiceProcessInfo(RunnerMode mode, CommunicationProtocol protocol, bool debugMode, params string[] assemblies) { FilePath = "AxoCover.Runner.exe".ToAbsolutePath(); var assemblyArgs = string.Join(" ", assemblies.Select(p => "\"" + p + "\"")); Arguments = string.Join(" ", mode, Process.GetCurrentProcess().Id, protocol.ToString(), debugMode.ToString(), assemblyArgs); }
/// <summary> /// send to Server a command to close the given directory handler /// </summary> /// <param name="handlers">a directory handler to close</param> public void CloseHandler(List <string> handlers) { CommunicationProtocol msg = new CommunicationProtocol( (int)CommandEnum.CloseHandlerCommand, handlers.ToArray()); SendDataToServer(msg); }
/// <summary> /// informing the Server the GUI window is being closed, and closing /// the connection. /// </summary> public void StartClosingWindow() { CommunicationProtocol closeWindow = new CommunicationProtocol((int)CommandEnum.CloseGUICommand, null); SendDataToServer(closeWindow); CloseClient(); }
/// <summary> /// Constructor for Tlc1543 /// </summary> /// <param name="ADDR">Address</param> /// <param name="CS">Chip Select</param> /// <param name="DOUT">Data Out</param> /// <param name="IOCLK">I/O Clock</param> /// <param name="EOC">End of Conversion</param> /// <param name="connectionSettings">Software or Hardware SPI connection settings</param> public Tlc1543(int ADDR = -1, int CS = -1, int DOUT = -1, int IOCLK = -1, int EOC = -1, SpiConnectionSettings connectionSettings = null) { _address = ADDR; _chipSelect = CS; _dataOut = DOUT; _inputOutputClock = IOCLK; _endOfConversion = EOC; if (connectionSettings != null) { _spi = new SoftwareSpi(11, 9, 10, 8, connectionSettings); _protocol = CommunicationProtocol.SoftSpi; } if (connectionSettings != null & ADDR == -1) { _spi = SpiDevice.Create(connectionSettings); _protocol = CommunicationProtocol.HardSpi; } else { _digital.OpenPin(_address, PinMode.Output); _digital.OpenPin(_chipSelect, PinMode.Output); _digital.OpenPin(_dataOut, PinMode.InputPullUp); _digital.OpenPin(_inputOutputClock, PinMode.Output); if (_endOfConversion > -1) { _digital.OpenPin(_endOfConversion, PinMode.InputPullUp); } _protocol = CommunicationProtocol.Gpio; } }
public ModbusTCP() : base() { communicationProtocol = new CommunicationProtocol() { Name = "ModbusTCP" }; }
/// <summary> /// Initializes a new instance of the ServerManager class. /// </summary> /// <param name="protocol">The CommunicationProtocol for the current server.</param> /// <param name="serverUri">The URI of the server.</param> /// <param name="authKey">The token used to validate the current user on the server.</param> /// <param name="port">The port to use with the Sockets protocol.</param> public CommunicationManager(CommunicationProtocol protocol, Uri serverUri, string authKey, int socketPort) { this.Protocol = protocol; this.AuthKey = authKey; this.ServerUri = serverUri; this.SocketPort = socketPort; Init(); }
public override void SetDriverAllDevicesDisconnected() { CommunicationProtocol _protocol = new CommunicationProtocol() { ID = 0, Name = "ModbusTCP" }; DBHelper.SetDriverDevicesDisconnected(_protocol); }
/// <summary> /// waits for message from server /// added for synchronic comunication. /// the function also updates everyone via event about the information from server. /// </summary> /// <returns>the message from server</returns> private ServiceInfoEventArgs GetAnswer() { NetworkStream stream = this.client.GetStream(); BinaryReader reader = new BinaryReader(stream); string response = reader.ReadString(); // Wait for response from serve CommunicationProtocol msg = JsonConvert.DeserializeObject <CommunicationProtocol>(response); ServiceInfoEventArgs answer = ClientServerArgsParser.Parse(msg); return(answer); }
/// <summary> /// Create a DHT sensor /// </summary> /// <param name="pin">The pin number (GPIO number)</param> /// <param name="pinNumberingScheme">The GPIO pin numbering scheme</param> public DhtBase(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical) { _protocol = CommunicationProtocol.OneWire; _controller = new GpioController(pinNumberingScheme); _pin = pin; _controller.OpenPin(_pin); // delay 1s to make sure DHT stable Thread.Sleep(1000); }
/// <summary> /// listening to the client and answering it's requests. /// stops listening(stops the connection) if: Server shut down, client /// had disconnected, or if something went wrong and exception was thrown. /// </summary> /// <param name="client">a client to listen to</param> public void HandleClient(TcpClient client) { new Task(() => { BinaryWriter writer; BinaryReader reader; try { NetworkStream stream = client.GetStream(); reader = new BinaryReader(stream); writer = new BinaryWriter(stream); SendInitialInfo(writer); m_logging.Log(Messages.ServerGotNewClientConnection(), MessageTypeEnum.INFO); } catch (Exception e) { Console.WriteLine(e); m_logging.Log(Messages.ErrorSendingConfigAndLogDataToClient(e), MessageTypeEnum.FAIL); return; } { while (serverIsOn) { try { string requset = reader.ReadString(); // Wait for Client to send request CommunicationProtocol msg = JsonConvert.DeserializeObject <CommunicationProtocol>(requset); if (msg != null) { if (msg.Command_Id == (int)CommandEnum.CloseGUICommand) { ClientClosedConnectionEvent(this, new ClientEventArgs(client)); break; } else { HandleRequest(msg); } } else { m_logging.Log(Messages.ErrorRecievingMessageFromClient(), MessageTypeEnum.FAIL); } } catch (Exception) { m_logging.Log(Messages.ErrorHandlingClient(), MessageTypeEnum.FAIL); break; } } client.Close(); } }).Start(); }
/// <summary> /// /// </summary> /// <param name="maxConn"></param> /// <param name="receiveBufferSize"></param> /// <param name="getIp"></param> public void setListener(int maxConn, int receiveBufferSize, ClientConnectedHandler getIp) { ServerState = WorkStatus.ServerInitialing; connCount = 0; MaxClient = maxConn; Clients = new SocketPool(); SemaphoreAcceptedClients = new Semaphore(ConnectionCount, MaxClient); SocketBuffer = new BufferManager(receiveBufferSize * maxConn, receiveBufferSize); CommProtocol = new CommunicationProtocol(); ClientConnected = getIp; }
/// <summary> /// Create a DHT sensor /// </summary> /// <param name="pin">The pin number (GPIO number)</param> /// <param name="pinNumberingScheme">The GPIO pin numbering scheme</param> /// <param name="gpioController"><see cref="GpioController"/> related with operations on pins</param> /// <param name="shouldDispose">True to dispose the Gpio Controller</param> public DhtBase(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical, GpioController gpioController = null, bool shouldDispose = true) { _protocol = CommunicationProtocol.OneWire; _shouldDispose = gpioController == null ? true : shouldDispose; _controller = gpioController ?? new GpioController(pinNumberingScheme); _pin = pin; _controller.OpenPin(_pin); // delay 1s to make sure DHT stable Thread.Sleep(1000); }
private static void RunTestService(RunnerMode runnerMode, int parentPid, CommunicationProtocol protocol, string[] assemblyPaths) { AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; foreach (var assemblyPath in assemblyPaths) { Console.Write($"Loading {assemblyPath}... "); Assembly.LoadFrom(assemblyPath); Console.WriteLine("Done."); } Process parentProcess = null; try { parentProcess = Process.GetProcessById(parentPid); parentProcess.EnableRaisingEvents = true; parentProcess.Exited += OnParentProcessExited; } catch (Exception e) { throw new Exception("Cannot open parent process.", e); } Type serviceInterface; Type serviceImplementation; GetService(runnerMode, out serviceInterface, out serviceImplementation); Console.WriteLine("AxoCover.Runner"); Console.WriteLine("Copyright (c) 2016-2017 Péter Major"); Console.WriteLine(); Console.WriteLine($"Starting {runnerMode} service..."); var serviceAddress = NetworkingExtensions.GetServiceAddress(protocol); var serviceBinding = NetworkingExtensions.GetServiceBinding(protocol); var serviceHost = new ServiceHost(serviceImplementation, new[] { serviceAddress }); serviceHost.AddServiceEndpoint(serviceInterface, serviceBinding, serviceAddress); serviceHost.Open(); ServiceProcess.PrintServiceStarted(serviceAddress); _isFinished.WaitOne(); Console.WriteLine("Exiting..."); try { serviceHost.Close(_closeTimeout); } catch { } //Make sure to kill leftover non-background threads started by tests Environment.Exit(0); }
/// <summary> /// this is an event handler: when a handler is being closed this function /// will be called and remove HandlerIsBeingClosed from the handler's event, /// and remove OnCommandRecieved(handler's function) from CommandRecieved /// event. /// </summary> /// <param name="sender">who called the func HandlerIsBeingClosed </param> /// <param name="e">arguments</param> public void HandlerIsBeingClosed(object sender, DirectoryCloseEventArgs e) //HANDLER TELLING ME IT IS BEING CLOSED - TELL CLIENT HANDLER { if (sender is IDirectoryHandler) { // inform all clients handler is being closed string[] path = { e.DirectoryPath }; CommunicationProtocol msg = new CommunicationProtocol((int)CommandEnum.CloseHandlerCommand, path); InformClients(msg); ((IDirectoryHandler)sender).DirectoryClose -= HandlerIsBeingClosed; this.CommandRecieved -= ((IDirectoryHandler)sender).OnCommandRecieved; } }
public Mcp3008(int clk, int miso, int mosi, int cs) { _controller = new GpioController(); _clk = clk; _miso = miso; _mosi = mosi; _cs = cs; _controller.OpenPin(_clk, PinMode.Output); _controller.OpenPin(_miso, PinMode.Input); _controller.OpenPin(_mosi, PinMode.Output); _controller.OpenPin(_cs, PinMode.Output); _protocol = CommunicationProtocol.Gpio; }
public static Binding GetServiceBinding(CommunicationProtocol protocol) { switch (protocol) { case CommunicationProtocol.Tcp: return(GetTcpBinding()); case CommunicationProtocol.MemoryPipe: return(GetMemoryTypeBinding()); default: throw new NotImplementedException(); } }
/// <summary> /// send to Server a command to close the given directory handler /// </summary> /// <param name="handlers">a directory handler to close</param> public ServiceInfoEventArgs CloseHandler(List <string> handlers) { CommunicationProtocol msg = new CommunicationProtocol( (int)CommandEnum.CloseHandlerCommand, handlers.ToArray()); ServiceInfoEventArgs ret = SendDataToServer(msg); // wait for deletion confirmation while (ret.RemovedHandlers == null) { ret = GetAnswer(); } return(ret); }
public static Uri GetServiceAddress(CommunicationProtocol protocol) { switch (protocol) { case CommunicationProtocol.Tcp: return(GetTcpAddress()); case CommunicationProtocol.MemoryPipe: return(GetMemoryTypeAddress()); default: throw new NotImplementedException(); } }
public Mcp3008(int CLK, int MISO, int MOSI, int CS) { _controller = new GpioController(); _CLK = CLK; _MISO = MISO; _MOSI = MOSI; _CS = CS; _controller.OpenPin(_CLK, PinMode.Output); _controller.OpenPin(_MISO, PinMode.Input); _controller.OpenPin(_MOSI, PinMode.Output); _controller.OpenPin(_CS, PinMode.Output); _protocol = CommunicationProtocol.Gpio; }
public AnalogSignal_BasicValues(CommunicationProtocol protocol, AbstractDBHelper dbHelper) { Protocol = protocol; DBHelper = dbHelper; InitializeComponent(); var stations = GetStations(); if (stations != null) { cbx_StationName.Items.AddRange(stations.ToArray()); } }
public TappyReader(CommunicationProtocol protocol, Bluegiga.BLE.Events.Connection.DisconnectedEventHandler disconnectCallback) { if (protocol == CommunicationProtocol.Usb) { conn = new UsbConnection(); } else if (protocol == CommunicationProtocol.Bluetooth) { conn = new BluetoothConnection(disconnectCallback); } buffer = new List <byte>(); conn.DataReceived += new EventHandler(DataReceivedHandler); DeviceName = null; }
/// <summary> /// /// </summary> /// <param name="protocol">Which protocol the driver should communicate over</param> public TappyReader(CommunicationProtocol protocol) { if (protocol == CommunicationProtocol.Usb) { conn = new UsbConnection(); } else if (protocol == CommunicationProtocol.Bluetooth) { conn = new BluetoothConnection(); } buffer = new List <byte>(); conn.DataReceived += new EventHandler(DataReceivedHandler); DeviceName = null; }
public TestProcess(IProcessInfo processInfo, IOptions options) : base(processInfo) { _protocol = options.TestProtocol; _startupTimeout = TimeSpan.FromSeconds(options.StartupTimeout); Exited += OnExited; if (!_serviceStartedEvent.WaitOne(_startupTimeout)) { throw new Exception("Service creation timed out."); } if (TestService == null) { throw new RemoteException("Could not create service.", _failReason); } }
/// <summary> /// Switch between USB or Bluetooth modes /// </summary> /// <param name="protocol"></param> public void SwitchProtocol(CommunicationProtocol protocol) { conn?.Disconnect(); if (protocol == CommunicationProtocol.Usb) { conn = new UsbConnection(); } else if (protocol == CommunicationProtocol.Bluetooth) { conn = new BluetoothConnection(); } FlushBuffer(); conn.DataReceived += new EventHandler(DataReceivedHandler); }
/// <summary> /// sends a message to all clients in clients list. if sending a message to one of the clients fails- /// the connection with the Client closes and the Client is removed from clients list. /// </summary> /// <param name="msg">a message to sent to all clients</param> private void InformClients(CommunicationProtocol msg) { List <TcpClient> clients = new List <TcpClient>(this.allClients); foreach (TcpClient client in clients) { try { ch.InformClient(client, msg); } catch (Exception ex) { CloseAndRemoveClient(client); m_logging.Log(Messages.CanNotCommunicate_ClientRemoved(ex), MessageTypeEnum.FAIL); } } }
/// <summary> /// Temperature, humidity, pressure and gas resistance sensor Bme680. /// </summary> /// <param name="i2cDevice">The used I2c communication device.</param> // ReSharper disable once UnusedMember.Global // ReSharper disable once InconsistentNaming public Bme680(I2cDevice i2cDevice) { _i2cDevice = i2cDevice; _calibrationData = new CalibrationData(); _protocol = CommunicationProtocol.I2C; // Check device signature which should be the same for all Bme680 sensors var readSignature = Read8BitsFromRegister((byte)Register.CHIP_ID); if (readSignature != DeviceId) { throw new Exception($"Device ID {readSignature} is not the same as expected {DeviceId}. Please check if you are using the right device."); } _calibrationData.ReadFromDevice(this); TriggerSoftReset(); }
/// <summary> /// returns all existing logs since Service had started. /// </summary> /// <param name="args">not in use. can be null</param> /// <param name="result">whether reading the logs went successful or not</param> /// <returns>all existing logs since Service had started</returns> public string Execute(string[] args, out bool result) { bool stopGetLogs = false; string[] logsArray; List <string> logsList = new List <string>(); string logName = ConfigurationManager.AppSettings["LogName"]; EventLog log = new EventLog(logName, "."); // "." is the local computer EventLogEntryCollection entries = log.Entries; int size = entries.Count; int i; // iterate from end to beggining. for (i = size - 1; i > 0; i--) { EventLogEntry entry = entries[i]; if (stopGetLogs) { break; } string msg = entry.Message; //TODO: change "In OnStart" to a parameter. if (msg.Contains("In OnStart")) { stopGetLogs = true; } logsList.Add("" + msg); } string convertEachString = JsonConvert.SerializeObject(logsList); if (convertEachString == null || !logsList.Any()) { result = false; return(null); } // if list is not empty logsArray = logsList.ToArray(); CommunicationProtocol commandSendArgs = new CommunicationProtocol( (int)CommandEnum.GetLogCommand, logsArray); result = true; return(JsonConvert.SerializeObject(commandSendArgs)); }
/// <summary> /// send a given message to Server. /// if sending didn't succeed - the connection is closed. /// </summary> /// <param name="msg">message to send to Server</param> public ServiceInfoEventArgs SendDataToServer(CommunicationProtocol msg) { try { string jsonCommand = JsonConvert.SerializeObject(msg); NetworkStream stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); mutex.WaitOne(); writer.Write(jsonCommand); mutex.ReleaseMutex(); // waits for server's answer - synchronic communication. return(GetAnswer()); } catch (Exception) { ConnectionIsBroken(this, null); CloseClient(); return(null); } }