public Relay(IDigitalWriteRead _digitalWriteRead, int gpioPin) { this._gpioPin = gpioPin; this._digitalWriteRead = _digitalWriteRead; this._state = PinState.Unknown; this.TurnOff(); }
/// <summary> /// Initialize this instance with standard settings. /// 9600:N:8:1, handshaking disabled. /// </summary> /// <param name="index">The port index - 1,2,...</param> public void Initialize(int index) { portName = "COM" + index.ToString() + ":"; baudRate = LineSpeed.Baud_9600; txFlowCTS = false; txFlowDSR = false; dtrControl = PinState.Disable; rxDSRsense = false; txContinue = true; txFlowXoff = false; rxFlowXoff = false; errReplace = false; nulDiscard = false; rtsControl = PinState.Disable; abortOnErr = false; xonLimit = 0; // 0=OS managed xoffLimit = 0; // 0=OS managed dataBits = ByteSize.Eight; parity = Parity.None; stopBits = StopBits.One; xonChar = (byte) CtrlChar.DC1; xoffChar = (byte) CtrlChar.DC3; errChar = (byte) '?'; eofChar = (byte) CtrlChar.SUB; evtChar = (byte) CtrlChar.NULL; handshake = Handshake.None; rxQueLen = 0; // 0=OS managed txQueLen = 0; // 0=OS managed txTmoMulti = 0; txTmoConst = 0; receiveMode = false; return; }
private void Arduino_DigitalPinUpdated(byte pin, PinState pinValue) { //Debug.WriteLine("IOConnector.Arduino_DigitalPinUpdated"); arduinoAlive = true; MachineStates state = MachineStates.UNDEFINED; switch (pin) { case STARTUP_PIN: state = MachineStates.STARTUP; break; case MANUAL_PIN: state = MachineStates.MANUAL; break; case LATCH_PIN: state = MachineStates.LATCH; break; case SPLIT_PIN: state = MachineStates.SPLIT; break; } if (pinValue == PinState.HIGH) machine.updateState(state, false); else machine.updateState(state, true); }
public MainPage() { this.InitializeComponent(); arduino = App.Arduino; App.Telemetry.TrackEvent( "RemoteBlinky_Windows10_SuccessfullyConnected" ); App.Arduino.DeviceConnectionLost += Arduino_OnDeviceConnectionLost; currentState = PinState.LOW; OnButton.IsEnabled = true; OffButton.IsEnabled = true; BlinkButton.IsEnabled = true; }
private void setup() { //Set the initial state of the led. ledState = PinState.LOW; //Set the pin mode of the led. arduino.pinMode(LED_PIN, PinMode.OUTPUT); //Set the timer to schedule blink() every one second. blinkTimer = new DispatcherTimer(); blinkTimer.Interval = TimeSpan.FromMilliseconds(1000); blinkTimer.Tick += blink; blinkTimer.Start(); }
private void blink(object sender, object e) { if (ledState == PinState.HIGH) //LED state is HIGH. { //Turn off the LED. arduino.digitalWrite(LED_PIN, PinState.LOW); //Show the message in the Output dialog. Debug.WriteLine("OFF"); //Set local LED state to Low. ledState = PinState.LOW; } else //LED state is LOW. { //Turn on the LED. arduino.digitalWrite(LED_PIN, PinState.HIGH); //Show the message in the Output dialog. Debug.WriteLine("ON"); //Set local LED state to Low. ledState = PinState.HIGH; } }
public async Task DigitalWrite(byte pin, PinState state) { pinData[pin].state = state; byte port = (byte)(pin / 8); int portValue = 0; for (var i = 0; i < 8; i++) { if (pinData[8 * port + i].state == PinState.High) { portValue |= (1 << i); } } byte[] commandBuffer = { (byte)(((byte)(FirmataCommand.DigitalWrite)) | port), (byte)(portValue & 0x7f), (byte)((portValue >> 7) & 0x7F) }; await WriteData(commandBuffer); }
public void DigitalWrite(int pin, PinState state) { if (state == PinState.High) { this.Values |= PowerOf2[pin]; } else { Values &= ~PowerOf2[pin]; } var result = LibMpsse.FT_WriteGPIO(_i2cHandle, (short)Directions, (short)Values); if (result != FtdiMpsseI2CResult.Ok) { if (Debugger.IsAttached) { Debugger.Break(); } throw new GpioException(result, nameof(DigitalWrite)); } }
public GpioCore(Pin newPinId, Direction newDirection = Direction.Out, PinState newPinState = PinState.Low) { pinId = newPinId; pinDirection = newDirection; pinState = newPinState; //Check if gpio pin is already open if (!Directory.Exists($"/sys/class/gpio/gpio{pinId}")) { Console.WriteLine($"Opening pin {pinId}"); File.WriteAllText("/sys/class/gpio/export", ((int)pinId).ToString()); } else if (!Directory.Exists($"/sys/class/gpio/gpio{((int)pinId).ToString()}")) { Console.WriteLine($"Pin {pinId} is already open"); } //Set direction if (pinDirection == Direction.Out) { Out(); } else if (pinDirection == Direction.In) { In(); } //Set value if (pinState == PinState.High) { High(); } else if (pinState == PinState.Low) { Low(); } }
public async Task TestDigitalPinWriteValueSuccess() { // Arrange RemoteDevice deviceUnderTest = null; RemoteDeviceHelper deviceHelper = new RemoteDeviceHelper(); var pinMode = PinMode.OUTPUT; byte pinUnderTest = 0; PinState expectedPinState = PinState.HIGH; var pin = new MockPin(pinUnderTest); pin.SupportedModes.Add(new KeyValuePair <PinMode, ushort>(PinMode.INPUT, 1)); pin.SupportedModes.Add(new KeyValuePair <PinMode, ushort>(PinMode.OUTPUT, 1)); var board = new MockBoard(new List <MockPin>() { pin }); // Act deviceUnderTest = deviceHelper.CreateDeviceUnderTestAndConnect(board); // Wait until the mock board is ready SpinWait.SpinUntil(() => { return(deviceHelper.DeviceState == DeviceState.Ready); }, 100000); deviceUnderTest.pinMode(pinUnderTest, pinMode); deviceUnderTest.digitalWrite(pinUnderTest, expectedPinState); // Wait for the mock board to recieve the state change await Task.Delay(100); var actualPinState = (PinState)board.Pins[pinUnderTest].CurrentValue; // Assert Assert.AreEqual(expectedPinState, actualPinState, "Pin state was incorrect"); }
void SwitchPinState(PinState desired) { // Enter desired. switch (desired) { case PinState.Entering: PrimeForEntering(); break; case PinState.Pinned: m_DisplayCountdown = m_DisplayDuration; break; case PinState.Wobbling: Wobble(); break; case PinState.Removing: // Pop pin out and have it fall away. Unpin(); break; } m_PinState = desired; }
// Update is called once per frame void FixedUpdate() { if (state == PinState.Out) { // 碰撞检测接触质点,进行穿刺 float dot = Vector3.Dot(head.transform.forward, head.LastMoveDir); if (dot <= 0) { return; } if (FindVertexToDeformer()) { state = PinState.Deformer; } } else if (state == PinState.Deformer) { float dot = Vector3.Dot(head.transform.forward, head.LastMoveDir); if (dot > 0) { return; } if (ReturnToOut()) { state = PinState.Out; } } else if (state == PinState.Puncture) { // 正在进行穿刺 } else if (state == PinState.Pass) { } }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ICoapContentFormat).GetTypeInfo().Assembly, typeof(IDtlsCredentials).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000); Database.Register(db); await db.RepairIfInproperShutdown(null); await db.Start(); DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += () => { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). PinState Pin8 = this.arduino.digitalRead(8); this.lastMotion = Pin8 == PinState.HIGH; MainPage.Instance.DigitalPinUpdated(8, Pin8); this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.arduino.digitalWrite(9, 0); // Relay set to 0 this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0")); this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000); }; this.arduino.AnalogPinUpdated += (pin, value) => { MainPage.Instance.AnalogPinUpdated(pin, value); }; this.arduino.DigitalPinUpdated += (pin, value) => { MainPage.Instance.DigitalPinUpdated(pin, value); if (pin == 8) { this.lastMotion = (value == PinState.HIGH); this.motionResource?.TriggerAll(); this.momentaryResource?.TriggerAll(); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); /************************************************************************************ * To create an unencrypted CoAP Endpoint on the default CoAP port: * * this.coapEndpoint = new CoapEndpoint(); * * To create an unencrypted CoAP Endpoint on the default CoAP port, * with a sniffer that outputs communication to the window: * * this.coapEndpoint = new CoapEndpoint(new LogSniffer()); * * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using * the users defined in the IUserSource users: * * this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users); * * To create a CoAP endpoint, that listens to both the default CoAP port, for * unencrypted communication, and the default CoAPS port, for encrypted, * authenticated and authorized communication, using * the users defined in the IUserSource users. Only users having the given * privilege (if not empty) will be authorized to access resources on the endpoint: * * this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, * new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false); * ************************************************************************************/ this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false); this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) => { string s; if (this.lastLight.HasValue) { s = ToString(this.lastLight.Value, 2) + " %"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, Notifications.Unacknowledged, "Light, in %.", null, null, new int[] { PlainText.ContentFormatCode }); this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5)); this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) => { string s; if (this.lastMotion.HasValue) { s = this.lastMotion.Value ? "true" : "false"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, Notifications.Acknowledged, "Motion detector.", null, null, new int[] { PlainText.ContentFormatCode }); this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0)); this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) => { if (req.IsAcceptable(Xml.ContentFormatCode)) { this.ReturnMomentaryAsXml(req, resp); } else if (req.IsAcceptable(Json.ContentFormatCode)) { this.ReturnMomentaryAsJson(req, resp); } else if (req.IsAcceptable(PlainText.ContentFormatCode)) { this.ReturnMomentaryAsPlainText(req, resp); } else if (req.Accept.HasValue) { throw new CoapException(CoapCode.NotAcceptable); } else { this.ReturnMomentaryAsPlainText(req, resp); } }, Notifications.Acknowledged, "Momentary values.", null, null, new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode }); this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5)); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
/// <summary> /// Write the specified value to the pin. /// </summary> /// <param name="value"> /// The value to write to the pin. /// </param> public override void Write(PinState value) { base.Write(value); Write(base.InnerPin, value); if (this._lastState != base.State) { this.OnStateChanged(new PinStateChangeEventArgs(this._lastState, base.State)); } }
/// <summary> /// Writes the specified value to the specified GPIO pin. /// </summary> /// <param name="pin"> /// The pin to write the value to. /// </param> /// <param name="value"> /// The value to write to the pin. /// </param> /// <param name="gpionum"> /// The GPIO number associated with the pin. /// </param> /// <param name="pinname"> /// The name of the pin. /// </param> private static void internal_Write(Int32 pin, PinState value, String gpionum, String pinname) { // GPIO_NONE is the same value for both Rev1 and Rev2 boards. if (pin == (Int32)GpioPins.GPIO_NONE) { return; } internal_ExportPin(pin, PinMode.OUT, gpionum, pinname); String val = ((Int32)value).ToString(); String path = GPIO_PATH + "gpio" + gpionum + "/value"; File.WriteAllText(path, val); Debug.WriteLine("Output to pin " + pinname + "/gpio" + pin.ToString() + ", value was " + val); }
/// <summary> /// Sets the state of the specified pin. /// </summary> /// <param name="pin"> /// The pin to alter. /// </param> /// <param name="state"> /// The state of the pin to set. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="pin"/> cannot be null. /// </exception> /// <exception cref="ObjectDisposedException"> /// This instance has been disposed and can no longer be used. /// </exception> /// <exception cref="ArgumentException"> /// The specified pin does not exist in the pin cache. /// </exception> /// <exception cref="System.IO.IOException"> /// Failed to write the new state to the device. /// </exception> public void SetPinState(IPCF8574Pin pin, PinState state) { if (pin == null) { throw new ArgumentNullException("pin"); } if (this._isDisposed) { throw new ObjectDisposedException("CyrusBuilt.MonoPi.IO.PCF.PCF8574GpioProvider"); } if (!this._pinCache.Contains(pin)) { throw new ArgumentException("Cannot set the state of a pin that does not exist in the pin cache.", "pin"); } // We only do this if the state is actually changing. PinState cstate = this._pinCache[this._pinCache.IndexOf(pin)].State; if (cstate != state) { Byte stateVal = this._currentStates.Empty ? (Byte)0 : this._currentStates.ToByteArray()[0]; this._currentStates.Set(pin.Address, (state == PinState.High)); this._device.WriteByte(this._busAddress, stateVal); this.OnPinStateChanged(new PinStateChangeEventArgs(pin.Address, cstate, state)); } }
// Method to setup an Overlapped object with with multiple buffers pinned. unsafe private void SetupOverlappedMultiple() { ArraySegment<byte>[] tempList = new ArraySegment<byte>[m_BufferList.Count]; m_BufferList.CopyTo(tempList, 0); // Alloc new Overlapped. m_Overlapped = new Overlapped(); // Number of things to pin is number of buffers. // Ensure we have properly sized object array. if(m_ObjectsToPin == null || (m_ObjectsToPin.Length != tempList.Length)) { m_ObjectsToPin = new object[tempList.Length]; } // Fill in object array. for(int i = 0; i < (tempList.Length); i++) { m_ObjectsToPin[i] = tempList[i].Array; } if(m_WSABufferArray == null || m_WSABufferArray.Length != tempList.Length) { m_WSABufferArray = new WSABuffer[tempList.Length]; } // Pin buffers and fill in WSABuffer descriptor pointers and lengths #if SOCKETTHREADPOOL m_Overlapped.AsyncResult = new DummyAsyncResult(CompletionPortCallback); m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(null, m_ObjectsToPin)); #else m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(CompletionPortCallback, m_ObjectsToPin)); #endif for(int i = 0; i < tempList.Length; i++) { ArraySegment<byte> localCopy = tempList[i]; ValidationHelper.ValidateSegment(localCopy); m_WSABufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset); m_WSABufferArray[i].Length = localCopy.Count; } m_PinState = PinState.MultipleBuffer; }
// Sets up an Overlapped object for SendPacketsAsync. unsafe private void SetupOverlappedSendPackets() { int index; // Alloc native descriptor. _sendPacketsDescriptor = new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount]; // Number of things to pin is number of buffers + 1 (native descriptor). // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1)) { _objectsToPin = new object[_sendPacketsElementsBufferCount + 1]; } // Fill in objects to pin array. Native descriptor buffer first and then user specified buffers. _objectsToPin[0] = _sendPacketsDescriptor; index = 1; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null && spe._buffer != null && spe._count > 0) { _objectsToPin[index] = spe._buffer; index++; } } // Pin buffers. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " + LoggingHash.HashString(_preAllocatedOverlapped)); } // Get pointer to native descriptor. _ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0); // Fill in native descriptor. int descriptorIndex = 0; int fileIndex = 0; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._buffer != null && spe._count > 0) { // This element is a buffer. _sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset); _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; descriptorIndex++; } else if (spe._filePath != null) { // This element is a file. _sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle(); _sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset; _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; fileIndex++; descriptorIndex++; } } } _pinState = PinState.SendPackets; }
/// <summary> /// Write the specified pin and value. /// </summary> /// <param name="pin"> /// The pin to write to. /// </param> /// <param name="value"> /// The value to write. /// </param> public static void Write(PiFacePins pin, PinState value) { String name = Enum.GetName(typeof(PiFacePins), pin); internal_Write((Int32)pin, value, name); }
/// <summary> /// Initializes a new instance of the <see cref="CyrusBuilt.MonoPi.IO.PinStateChangeEventArgs"/> /// class with the address of the pin and the old and new pin states. /// </summary> /// <param name="address"> /// The pin address. /// </param> /// <param name="oldState"> /// The previous state of the pin. /// </param> /// <param name="newState"> /// The new state of the pin. /// </param> public PinStateChangeEventArgs(Int32 address, PinState oldState, PinState newState) { this._pinAddress = address; this._oldState = oldState; this._newState = newState; }
private void SetupOverlappedSingle(bool pinSingleBuffer) { this.m_Overlapped = new Overlapped(); if (pinSingleBuffer) { if (this.m_Buffer != null) { this.m_PtrNativeOverlapped = new SafeNativeOverlapped(this.m_Overlapped.UnsafePack(new IOCompletionCallback(this.CompletionPortCallback), this.m_Buffer)); this.m_PinnedSingleBuffer = this.m_Buffer; this.m_PinnedSingleBufferOffset = this.m_Offset; this.m_PinnedSingleBufferCount = this.m_Count; this.m_PtrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_Buffer, this.m_Offset); this.m_PtrAcceptBuffer = IntPtr.Zero; this.m_WSABuffer.Pointer = this.m_PtrSingleBuffer; this.m_WSABuffer.Length = this.m_Count; this.m_PinState = PinState.SingleBuffer; } else { this.m_PtrNativeOverlapped = new SafeNativeOverlapped(this.m_Overlapped.UnsafePack(new IOCompletionCallback(this.CompletionPortCallback), null)); this.m_PinnedSingleBuffer = null; this.m_PinnedSingleBufferOffset = 0; this.m_PinnedSingleBufferCount = 0; this.m_PtrSingleBuffer = IntPtr.Zero; this.m_PtrAcceptBuffer = IntPtr.Zero; this.m_WSABuffer.Pointer = this.m_PtrSingleBuffer; this.m_WSABuffer.Length = this.m_Count; this.m_PinState = PinState.NoBuffer; } } else { this.m_PtrNativeOverlapped = new SafeNativeOverlapped(this.m_Overlapped.UnsafePack(new IOCompletionCallback(this.CompletionPortCallback), this.m_AcceptBuffer)); this.m_PinnedAcceptBuffer = this.m_AcceptBuffer; this.m_PtrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_AcceptBuffer, 0); this.m_PtrSingleBuffer = IntPtr.Zero; this.m_PinState = PinState.SingleAcceptBuffer; } }
public InputStateTrigger(String name, PinState triggerState) { this.Name = name; this.TriggerState = triggerState; }
private void OnEvtSampledState(MicroBitMessageReader reader) { // Copy the current state to the previous state. _prev = _curr; // Read the new current state. while (true) { short accX, accY, accZ; // int accPitch, accRoll; // int heading; int pinCount; int buttonA; int buttonB; PinState[] pins = new PinState[3]; // Read button states if (!reader.Consume('b')) { break; } if (!reader.ReadU8Hex(out buttonA)) { break; } if (!reader.ReadU8Hex(out buttonB)) { break; } // Read accelerometer if (!reader.Consume('a')) { break; } if (!reader.ReadSignedU16Hex(out accX)) { break; } if (!reader.ReadSignedU16Hex(out accY)) { break; } if (!reader.ReadSignedU16Hex(out accZ)) { break; } // if (!reader.ReadU16Hex(out accPitch)) break; // if (!reader.ReadU16Hex(out accRoll)) break; // Read compass // if (!reader.Consume('c')) break; // if (!reader.ReadU16Hex(out heading)) break; // Read input pins if (!reader.Consume('p')) { break; } if (!reader.ReadU8Hex(out pinCount)) { break; } int pinsRemaining = pinCount; // Make sure we're in range. if (pinsRemaining > 3) { break; } while (pinsRemaining > 0) { int pinId, pinValue; char pinMode; if (!reader.ReadU8Hex(out pinId)) { break; } if (pinId > 2) { break; } if (!reader.ReadChar(out pinMode)) { break; } if (pinMode != 'a' && pinMode != 'd') { break; } if (!reader.ReadU16Hex(out pinValue)) { break; } pins[pinId] = new PinState(pinId); pins[pinId].Direction = EPinDirection.Input; pins[pinId].Mode = pinMode == 'a' ? EPinOperatingMode.Analog : EPinOperatingMode.Digital; pins[pinId].Value = pinValue; pinsRemaining--; } // If we didn't read all the pins then something is wrong with the message. if (pinsRemaining > 0) { break; } // Apply button states _curr.Buttons[0].State = (EButtonState)buttonA; _curr.Buttons[1].State = (EButtonState)buttonB; // Apply accelerometer accX = MyMath.Clamp(accX, MinAccel, MaxAccel); accY = MyMath.Clamp(accY, MinAccel, MaxAccel); accZ = MyMath.Clamp(accZ, MinAccel, MaxAccel); Vector3 acc = new Vector3(accY, accX, accZ); acc.Normalize(); _curr.Acc = MyMath.NanProtect(acc, Vector3.Zero); // _curr.AccPitch = accPitch; // _curr.AccRoll = accRoll; // Apply compass // _curr.Heading = heading; // Apply pins for (int i = 0; i < pinCount; ++i) { _curr.Pins[pins[i].Id] = pins[i]; } // Inc generation _curr.Generation += 1; break; } }
private void SetPinState(PinState state) { SetPinState(state == PinState.High); }
public void DigitalWrite(int pin, PinState state) { this._DigitalWriteRead.DigitalWrite(pin, state); }
public override void Pin_ValueChanged(PinState NewState) { Gateway.NewMomentaryValues(this, new BooleanField(this, DateTime.Now, "Value", NewState == PinState.HIGH, FieldType.Momentary, FieldQoS.AutomaticReadout, typeof(Module).Namespace, 13)); }
// Sets up an Overlapped object with either _buffer or _acceptBuffer pinned. unsafe private void SetupOverlappedSingle(bool pinSingleBuffer) { // Pin buffer, get native pointers, and fill in WSABuffer descriptor. if (pinSingleBuffer) { if (_buffer != null) { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = _buffer; _pinnedSingleBufferOffset = _offset; _pinnedSingleBufferCount = _count; _ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset); _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.SingleBuffer; } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; _ptrSingleBuffer = IntPtr.Zero; _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.NoBuffer; } } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedAcceptBuffer = _acceptBuffer; _ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0); _ptrSingleBuffer = IntPtr.Zero; _pinState = PinState.SingleAcceptBuffer; } }
// Method to clean up any existing Overlapped object and related state variables. private void FreeOverlapped(bool checkForShutdown) { if (!checkForShutdown || !NclUtilities.HasShutdownStarted) { // Free the overlapped object if(m_PtrNativeOverlapped != null && !m_PtrNativeOverlapped.IsInvalid) { m_PtrNativeOverlapped.Dispose(); m_PtrNativeOverlapped = null; m_Overlapped = null; m_PinState = PinState.None; m_PinnedAcceptBuffer = null; m_PinnedSingleBuffer = null; m_PinnedSingleBufferOffset = 0; m_PinnedSingleBufferCount = 0; } // Free any alloc'd GCHandles if(m_SocketAddressGCHandle.IsAllocated) { m_SocketAddressGCHandle.Free(); } if(m_WSAMessageBufferGCHandle.IsAllocated) { m_WSAMessageBufferGCHandle.Free(); } if(m_WSARecvMsgWSABufferArrayGCHandle.IsAllocated) { m_WSARecvMsgWSABufferArrayGCHandle.Free(); } if(m_ControlBufferGCHandle.IsAllocated) { m_ControlBufferGCHandle.Free(); } } }
/// <summary> /// Write the specified value to the pin. /// </summary> /// <param name="value"> /// If set to <c>true</c> value. /// </param> public virtual void Write(Boolean value) { this._state = value ? PinState.High : PinState.Low; }
/// <summary> /// Write a value to the pin /// </summary> /// <param name="pinState"></param> public void Write(PinState pinState) { Write(pinState == PinState.High); }
private void SetupOverlappedSendPackets() { this.m_Overlapped = new Overlapped(); this.m_SendPacketsDescriptor = new UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElement[this.m_SendPacketsElementsFileCount + this.m_SendPacketsElementsBufferCount]; if ((this.m_ObjectsToPin == null) || (this.m_ObjectsToPin.Length != (this.m_SendPacketsElementsBufferCount + 1))) { this.m_ObjectsToPin = new object[this.m_SendPacketsElementsBufferCount + 1]; } this.m_ObjectsToPin[0] = this.m_SendPacketsDescriptor; int index = 1; foreach (SendPacketsElement element in this.m_SendPacketsElementsInternal) { if ((element.m_Buffer != null) && (element.m_Count > 0)) { this.m_ObjectsToPin[index] = element.m_Buffer; index++; } } this.m_PtrNativeOverlapped = new SafeNativeOverlapped(this.m_Overlapped.UnsafePack(new IOCompletionCallback(this.CompletionPortCallback), this.m_ObjectsToPin)); this.m_PtrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_SendPacketsDescriptor, 0); int num2 = 0; int num3 = 0; foreach (SendPacketsElement element2 in this.m_SendPacketsElementsInternal) { if (element2 != null) { if ((element2.m_Buffer != null) && (element2.m_Count > 0)) { this.m_SendPacketsDescriptor[num2].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(element2.m_Buffer, element2.m_Offset); this.m_SendPacketsDescriptor[num2].length = (uint) element2.m_Count; this.m_SendPacketsDescriptor[num2].flags = element2.m_Flags; num2++; } else if ((element2.m_FilePath != null) && (element2.m_FilePath.Length != 0)) { this.m_SendPacketsDescriptor[num2].fileHandle = this.m_SendPacketsFileHandles[num3].DangerousGetHandle(); this.m_SendPacketsDescriptor[num2].fileOffset = element2.m_Offset; this.m_SendPacketsDescriptor[num2].length = (uint) element2.m_Count; this.m_SendPacketsDescriptor[num2].flags = element2.m_Flags; num3++; num2++; } } } this.m_PinState = PinState.SendPackets; }
public static void WritePin(GPIOPins pin, PinState pinState) { bcm2835_gpio_write(pin, pinState); }
/// <summary> /// Initializes a new instance of the <see cref="CyrusBuilt.MonoPi.IO.PinStateChangeEventArgs"/> /// class with the old and new pin states. /// </summary> /// <param name="oldState"> /// The previous state of the pin. /// </param> /// <param name="newState"> /// The new state of the pin. /// </param> public PinStateChangeEventArgs(PinState oldState, PinState newState) : base() { this._oldState = oldState; this._newState = newState; }
protected static extern void bcm2835_gpio_write(GPIOPins pin, PinState pinState);
public void SendDigitalUpdateMessage(byte pinNumber, PinState state) { sendMessage(prepareDigitalUpdateMessage(pinNumber, state)); }
static void SimpelTest(ISerialConnection connection) { var session = new ArduinoSession(connection, timeOut: 2500); IFirmataProtocol firmata = session; firmata.AnalogStateReceived += Session_OnAnalogStateReceived; firmata.DigitalStateReceived += Session_OnDigitalStateReceived; Firmware firm = firmata.GetFirmware(); Console.WriteLine(); Console.WriteLine("Firmware: {0} {1}.{2}", firm.Name, firm.MajorVersion, firm.MinorVersion); Console.WriteLine(); ProtocolVersion version = firmata.GetProtocolVersion(); Console.WriteLine(); Console.WriteLine("Protocol version: {0}.{1}", version.Major, version.Minor); Console.WriteLine(); BoardCapability cap = firmata.GetBoardCapability(); Console.WriteLine(); Console.WriteLine("Board Capability:"); foreach (var pin in cap.Pins) { Console.WriteLine("Pin {0}: Input: {1}, Output: {2}, Analog: {3}, Analog-Res: {4}, PWM: {5}, PWM-Res: {6}, Servo: {7}, Servo-Res: {8}, Serial: {9}, Encoder: {10}, Input-pullup: {11}", pin.PinNumber, pin.DigitalInput, pin.DigitalOutput, pin.Analog, pin.AnalogResolution, pin.Pwm, pin.PwmResolution, pin.Servo, pin.ServoResolution, pin.Serial, pin.Encoder, pin.InputPullup); } Console.WriteLine(); var analogMapping = firmata.GetBoardAnalogMapping(); Console.WriteLine("Analog channel mappings:"); foreach (var mapping in analogMapping.PinMappings) { Console.WriteLine("Channel {0} is mapped to pin {1}.", mapping.Channel, mapping.PinNumber); } firmata.ResetBoard(); Console.WriteLine(); Console.WriteLine("Digital port states:"); foreach (var pincap in cap.Pins.Where(c => (c.DigitalInput || c.DigitalOutput) && !c.Analog)) { var pinState = firmata.GetPinState(pincap.PinNumber); Console.WriteLine("Pin {0}: Mode = {1}, Value = {2}", pincap.PinNumber, pinState.Mode, pinState.Value); } Console.WriteLine(); firmata.SetDigitalPort(0, 0x04); firmata.SetDigitalPort(1, 0xff); firmata.SetDigitalPinMode(10, PinMode.DigitalOutput); firmata.SetDigitalPinMode(11, PinMode.ServoControl); firmata.SetDigitalPin(11, 90); Thread.Sleep(500); int hi = 0; for (int a = 0; a <= 179; a += 1) { firmata.SetDigitalPin(11, a); Thread.Sleep(100); firmata.SetDigitalPort(1, hi); hi ^= 4; Console.Write("{0};", a); } Console.WriteLine(); Console.WriteLine(); firmata.SetDigitalPinMode(6, PinMode.DigitalInput); //firmata.SetDigitalPortState(2, 255); //firmata.SetDigitalPortState(3, 255); firmata.SetSamplingInterval(500); firmata.SetAnalogReportMode(0, true); Console.WriteLine("Setting digital report modes:"); firmata.SetDigitalReportMode(0, true); firmata.SetDigitalReportMode(1, true); firmata.SetDigitalReportMode(2, true); Console.WriteLine(); foreach (var pinCap in cap.Pins.Where(c => (c.DigitalInput || c.DigitalOutput) && !c.Analog)) { PinState state = firmata.GetPinState(pinCap.PinNumber); Console.WriteLine("Digital {1} pin {0}: {2}", state.PinNumber, state.Mode, state.Value); } Console.WriteLine(); Console.ReadLine(); firmata.SetAnalogReportMode(0, false); firmata.SetDigitalReportMode(0, false); firmata.SetDigitalReportMode(1, false); firmata.SetDigitalReportMode(2, false); Console.WriteLine("Ready."); }
/// <summary> /// Initializes a new instance of the <see cref="CyrusBuilt.MonoPi.IO.PiFaceDigitalGPIO"/> /// class with the PiFace pin to control and the initial value to write. /// </summary> /// <param name="pin"> /// The PiFace pin to control. /// </param> /// <param name="initialValue"> /// The initial value to write. /// </param> public PiFaceDigitalGPIO(PiFacePins pin, PinState initialValue) : base(pin, initialValue) { }
static void Main(string [] args) { /*string assemblyFolder = Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location); * NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration (assemblyFolder + "/NLog/NLog.config", true);*/ Console.Title = "Trigger Device By Ali Deym and Biftor (C) 2017-2018"; WriteLineNoLog("Creating logger instance..."); logger = new FileLogger() { FileNameTemplate = "main-########.log" }; WriteLine("Logger instance created."); WriteLine("Trigger device (C) 2017 - 2018 by:"); WriteLine("Ali Deym, Biftor (Parham Abedi)."); WriteLine(""); WriteLine(""); WriteLine("Initializing device..."); WriteLine(""); WriteLine(""); WriteLine("Trigger Program v" + triggerDeviceVersion.X + "." + triggerDeviceVersion.Y + "." + triggerDeviceVersion.Z); WriteLine(""); WriteLine("Device info: "); var OS = Environment.OSVersion; WriteLine("Device: " + Environment.MachineName); WriteLine("Username: "******"OS: " + OS.VersionString + " (" + Enum.GetName(typeof(PlatformID), OS.Platform) + ")"); WriteLine("CPU Cores: " + Environment.ProcessorCount + " Cores."); WriteLine(""); WriteLine(""); WriteLine("Checking for GPIO config..."); try { if (File.Exists(".gpio")) { var content = File.ReadAllText(".gpio").Trim(); //if (int.TryParse (content, out int result)) { if (Enum.TryParse(content, out GPIOPins configuredPin)) { interruptPin = configuredPin; WriteLine("Changing GPIO pin to: " + content + "."); } //} } else { WriteLine("Creating default GPIO configuration..."); File.WriteAllText(".gpio", "GPIO_17"); } if (File.Exists(".ledgpio")) { var content = File.ReadAllText(".ledgpio").Trim(); if (Enum.TryParse(content, out GPIOPins configuredPin)) { ledPin = configuredPin; WriteLine("Changing LED GPIO pin to: " + content + "."); } } else { WriteLine("Creating default LED GPIO configuration..."); File.WriteAllText(".ledgpio", "GPIO_23"); } if (File.Exists(".flashgpio")) { var content = File.ReadAllText(".flashgpio").Trim(); if (Enum.TryParse(content, out GPIOPins configuredPin)) { flashPin = configuredPin; WriteLine("Changing Flash GPIO pin to: " + content + "."); } } else { WriteLine("Creating default Flash GPIO configuration..."); File.WriteAllText(".flashgpio", "GPIO_21"); } } catch (Exception ex) { WriteLine("GPIO config ERROR: " + ex.ToString()); } WriteLine("Initializing GPIO Pin: " + Enum.GetName(typeof(GPIOPins), interruptPin) + "..."); LEDTimer = DateTime.Now; /* Initialize GPIO Pin: */ pin = new GPIOMem(interruptPin, GPIODirection.In); flash = new GPIOMem(flashPin, GPIODirection.Out); led = new GPIOMem(ledPin, GPIODirection.Out); lastInterruptState = PinState.High; interruptThread = new Thread(interruptCheck); interruptThread.Priority = ThreadPriority.AboveNormal; /* Network manager */ WriteLine("Listening network on IP: (" + IPAddress + ")"); /* Bifler listener */ WriteLine("Starting libBifler listener..."); netManager = new NetworkManager(IPAddress, true); netManager.Initialize(triggerDeviceVersion); WriteLine("Successfully listening libBifler."); /* Radio listener */ WriteLine("Starting radio listener..."); radioManager = new NetworkManager(IPAddress, true, true); radioManager.Initialize(triggerDeviceVersion); WriteLine("Successfully listening radio."); WriteLine("Registering methods..."); /* Register netManager packet's read methods into their origins. */ RegisterMethods(); RegisterRadioMethods(); WriteLine("Started listening network successfully."); WriteLine("Initializing GPS Device..."); /*var ports = SerialPort.GetPortNames (); * WriteLine ("COM Ports (" + ports.Length + "): "); * * foreach (var port in ports) { * WriteLine ("\t" + port); * } * * * if (ports.Length == 1) { * WriteLine ("Creating GPS device on Port: " + ports [0] + "..."); * * gpsDevice = new GPSHandler (ports [0], sendGPSData); * * WriteLine ("SerialPort running for GPS."); * } */ /* Run GPIO Scheduler. */ WriteLine("Starting GPIO Interrupt."); interruptThread.Start(); }
/// <summary> /// Load the message definition list from a text file. /// </summary> public void Load(string fName) { // Quit if file doesn't exist. FileInfo fi = new FileInfo(fName); if (fi.Exists == false) { return; } // Open text definitions file in read-only mode. FileStream fs = new FileStream(fName, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); // Set file pointer to beginning of file. sr.BaseStream.Seek(0, SeekOrigin.Begin); string line = ""; string data = ""; while ((line = sr.ReadLine()) != null) { data = line.Substring(line.IndexOf(":") + 1); if (line.StartsWith("<Port Name>")) { this.portName = data; } else if (line.StartsWith("<Baud Rate>")) { this.baudRate = (LineSpeed)int.Parse(data); } else if (line.StartsWith("<CTS Flow>")) { this.txFlowCTS = bool.Parse(data); } else if (line.StartsWith("<DSR Flow>")) { this.txFlowDSR = bool.Parse(data); } else if (line.StartsWith("<DTR Ctrl>")) { this.dtrControl = (PinState)byte.Parse(data); } else if (line.StartsWith("<DSR Sense>")) { this.rxDSRsense = bool.Parse(data); } else if (line.StartsWith("<TX Continue>")) { this.txContinue = bool.Parse(data); } else if (line.StartsWith("<TX Xoff Flow>")) { this.txFlowXoff = bool.Parse(data); } else if (line.StartsWith("<RX Xoff Flow>")) { this.rxFlowXoff = bool.Parse(data); } else if (line.StartsWith("<Error Replace>")) { this.errReplace = bool.Parse(data); } else if (line.StartsWith("<Null Discard>")) { this.nulDiscard = bool.Parse(data); } else if (line.StartsWith("<RTS Control>")) { this.rtsControl = (PinState)byte.Parse(data); } else if (line.StartsWith("<Abort On Error>")) { this.abortOnErr = bool.Parse(data); } else if (line.StartsWith("<Xon Limit>")) { this.xonLimit = short.Parse(data); } else if (line.StartsWith("<Xoff Limit>")) { this.xoffLimit = short.Parse(data); } else if (line.StartsWith("<Bits/Byte>")) { this.dataBits = (ByteSize)byte.Parse(data); } else if (line.StartsWith("<Parity>")) { this.parity = (Parity)byte.Parse(data); } else if (line.StartsWith("<Stop Bits>")) { this.stopBits = (StopBits)byte.Parse(data); } else if (line.StartsWith("<Xon Char>")) { this.xonChar = byte.Parse(data); } else if (line.StartsWith("<Xoff Char>")) { this.xoffChar = byte.Parse(data); } else if (line.StartsWith("<Error Char>")) { this.errChar = byte.Parse(data); } else if (line.StartsWith("<EOF Char>")) { this.eofChar = byte.Parse(data); } else if (line.StartsWith("<Event Char>")) { this.evtChar = byte.Parse(data); } else if (line.StartsWith("<Handshaking>")) { this.handshake = (Handshake)byte.Parse(data); } else if (line.StartsWith("<RX Q Length>")) { this.rxQueLen = int.Parse(data); } else if (line.StartsWith("<TX Q Length>")) { this.txQueLen = int.Parse(data); } else if (line.StartsWith("<TX Timeout(M)>")) { this.txTmoMulti = uint.Parse(data); } else if (line.StartsWith("<TX Timeout(C)>")) { this.txTmoConst = uint.Parse(data); } else if (line.StartsWith("<Receive Mode>")) { this.receiveMode = bool.Parse(data); } else if (line.StartsWith("<Startup>")) { this.startup = uint.Parse(data); } } // FClose. fs.Close(); return; }
/// <summary> /// Initializes a new instance of the <see cref="CyrusBuilt.MonoPi.IO.PiFaceGpioBase"/> /// class with the physical pin represented by this class. /// </summary> /// <param name="pin"> /// The physical pin being wrapped by this class. /// </param> /// <param name="initialValue"> /// Initial value. /// </param> protected PiFaceGpioBase(PiFacePins pin, PinState initialValue) : this(pin) { this._initValue = initialValue; }
// Method to setup an Overlapped object with either m_Buffer or m_AcceptBuffer pinned. unsafe private void SetupOverlappedSingle(bool pinSingleBuffer) { // Alloc new Overlapped. m_Overlapped = new Overlapped(); // Pin buffer, get native pointers, and fill in WSABuffer descriptor. if(pinSingleBuffer) { if(m_Buffer != null) { #if SOCKETTHREADPOOL m_Overlapped.AsyncResult = new DummyAsyncResult(CompletionPortCallback); m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(null, m_Buffer)); #else m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(CompletionPortCallback, m_Buffer)); #endif m_PinnedSingleBuffer = m_Buffer; m_PinnedSingleBufferOffset = m_Offset; m_PinnedSingleBufferCount = m_Count; m_PtrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(m_Buffer, m_Offset); m_PtrAcceptBuffer = IntPtr.Zero; m_WSABuffer.Pointer = m_PtrSingleBuffer; m_WSABuffer.Length = m_Count; m_PinState = PinState.SingleBuffer; } else { #if SOCKETTHREADPOOL m_Overlapped.AsyncResult = new DummyAsyncResult(CompletionPortCallback); m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(null, null)); #else m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(CompletionPortCallback, null)); #endif m_PinnedSingleBuffer = null; m_PinnedSingleBufferOffset = 0; m_PinnedSingleBufferCount = 0; m_PtrSingleBuffer = IntPtr.Zero; m_PtrAcceptBuffer = IntPtr.Zero; m_WSABuffer.Pointer = m_PtrSingleBuffer; m_WSABuffer.Length = m_Count; m_PinState = PinState.NoBuffer; } } else { #if SOCKETTHREADPOOL m_Overlapped.AsyncResult = new DummyAsyncResult(CompletionPortCallback); m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(null, m_AcceptBuffer)); #else m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(CompletionPortCallback, m_AcceptBuffer)); #endif m_PinnedAcceptBuffer = m_AcceptBuffer; m_PtrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(m_AcceptBuffer, 0); m_PtrSingleBuffer = IntPtr.Zero; m_PinState = PinState.SingleAcceptBuffer; } }
/// <summary> /// Write the specified value to the pin. /// </summary> /// <param name="value"> /// If set to <c>true</c> value. /// </param> public virtual void Write(PinState value) { this._state = value; }
// Method to setup an Overlapped object for SendPacketsAsync. unsafe private void SetupOverlappedSendPackets() { int index; // Alloc new Overlapped. m_Overlapped = new Overlapped(); // Alloc native descriptor. m_SendPacketsDescriptor = new UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElement[m_SendPacketsElementsFileCount + m_SendPacketsElementsBufferCount]; // Number of things to pin is number of buffers + 1 (native descriptor). // Ensure we have properly sized object array. if(m_ObjectsToPin == null || (m_ObjectsToPin.Length != m_SendPacketsElementsBufferCount + 1)) { m_ObjectsToPin = new object[m_SendPacketsElementsBufferCount + 1]; } // Fill in objects to pin array. Native descriptor buffer first and then user specified buffers. m_ObjectsToPin[0] = m_SendPacketsDescriptor; index = 1; foreach(SendPacketsElement spe in m_SendPacketsElementsInternal) { if(spe != null && spe.m_Buffer != null && spe.m_Count > 0) { m_ObjectsToPin[index] = spe.m_Buffer; index++; } } // Pin buffers #if SOCKETTHREADPOOL m_Overlapped.AsyncResult = new DummyAsyncResult(CompletionPortCallback); m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(null, m_ObjectsToPin)); #else m_PtrNativeOverlapped = new SafeNativeOverlapped(m_Overlapped.UnsafePack(CompletionPortCallback, m_ObjectsToPin)); #endif // Get pointer to native descriptor. m_PtrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(m_SendPacketsDescriptor, 0); // Fill in native descriptor. int descriptorIndex = 0; int fileIndex = 0; foreach(SendPacketsElement spe in m_SendPacketsElementsInternal) { if (spe != null) { if(spe.m_Buffer != null && spe.m_Count > 0) { // a buffer m_SendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe.m_Buffer, spe.m_Offset); m_SendPacketsDescriptor[descriptorIndex].length = (uint)spe.m_Count; m_SendPacketsDescriptor[descriptorIndex].flags = spe.m_Flags; descriptorIndex++; } else if (spe.m_FilePath != null) { // a file m_SendPacketsDescriptor[descriptorIndex].fileHandle = m_SendPacketsFileHandles[fileIndex].DangerousGetHandle(); m_SendPacketsDescriptor[descriptorIndex].fileOffset = spe.m_Offset; m_SendPacketsDescriptor[descriptorIndex].length = (uint)spe.m_Count; m_SendPacketsDescriptor[descriptorIndex].flags = spe.m_Flags; fileIndex++; descriptorIndex++; } } } m_PinState = PinState.SendPackets; }
private async void StartActuator() { try { Log.Informational("Starting application."); SimpleXmppConfiguration xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. FormSignatureKey, FormSignatureSecret, typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = xmppConfiguration.GetClient("en", typeof(App).GetTypeInfo().Assembly, false); xmppClient.AllowRegistration(FormSignatureKey, FormSignatureSecret); if (xmppConfiguration.Sniffer && MainPage.Sniffer != null) xmppClient.Add(MainPage.Sniffer); if (!string.IsNullOrEmpty(xmppConfiguration.Events)) Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, xmppConfiguration.Events, false)); if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, xmppConfiguration.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair<string, object>("Public", e.IsPublic)); this.RaiseOwnershipChanged(); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; this.Register(); // Will call this.OwnershipChanged() after successful registration. }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } if (!string.IsNullOrEmpty(xmppConfiguration.Provisioning)) provisioningClient = new ProvisioningClient(xmppClient, xmppConfiguration.Provisioning); Timer ConnectionTimer = new Timer((P) => { if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating) { try { Log.Informational("Reconnecting."); xmppClient.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); xmppClient.OnStateChanged += (sender, NewState) => { Log.Informational(NewState.ToString()); switch (NewState) { case XmppState.Connected: connected = true; if (!registered && this.thingRegistryClient != null) this.Register(); break; case XmppState.Offline: immediateReconnect = connected; connected = false; if (immediateReconnect) xmppClient.Reconnect(); break; } }; xmppClient.OnPresenceSubscribe += (sender, e) => { Log.Informational("Subscription request received from " + e.From + "."); e.Accept(); // TODO: Provisioning RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID); if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) xmppClient.RequestPresenceSubscription(e.FromBareJID); xmppClient.SetPresence(Availability.Chat); }; xmppClient.OnPresenceUnsubscribe += (sender, e) => { Log.Informational("Unsubscription request received from " + e.From + "."); e.Accept(); }; xmppClient.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) xmppClient.RemoveRosterItem(e.BareJid); }; gpio = GpioController.GetDefault(); if (gpio != null) { int c = gpio.PinCount; int i; for (i = 0; i < c; i++) { if (gpio.TryOpenPin(i, GpioSharingMode.Exclusive, out GpioPin Pin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { gpioPins[i] = new KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>>(Pin, MainPage.Instance.AddPin("GPIO" + i.ToString(), Pin.GetDriveMode(), Pin.Read().ToString())); Pin.ValueChanged += async (sender, e) => { if (!this.gpioPins.TryGetValue(sender.PinNumber, out KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>> P)) return; PinState Value = e.Edge == GpioPinEdge.FallingEdge ? PinState.LOW : PinState.HIGH; if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { DateTime TP = DateTime.Now; string s = "GPIO" + sender.PinNumber.ToString(); this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, Value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Value.Text = Value.ToString()); }; } } } DeviceInformationCollection Devices = await Microsoft.Maker.Serial.UsbSerial.listAvailableDevicesAsync(); foreach (DeviceInformation DeviceInfo in Devices) { if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino")) { Log.Informational("Connecting to " + DeviceInfo.Name); arduinoUsb = new UsbSerial(DeviceInfo); arduinoUsb.ConnectionEstablished += () => { Log.Informational("USB connection established."); }; arduino = new RemoteDevice(arduinoUsb); arduino.DeviceReady += async () => { Log.Informational("Device ready."); Dictionary<int, bool> DisabledPins = new Dictionary<int, bool>(); Dictionary<string, KeyValuePair<Enum, string>> Values = new Dictionary<string, KeyValuePair<Enum, string>>(); PinMode Mode; PinState State; string s; ushort Value; foreach (byte PinNr in arduino.DeviceHardwareProfile.DisabledPins) DisabledPins[PinNr] = true; foreach (byte PinNr in arduino.DeviceHardwareProfile.AnalogPins) { if (DisabledPins.ContainsKey(PinNr)) continue; s = "A" + (PinNr - arduino.DeviceHardwareProfile.AnalogOffset).ToString(); if (arduino.DeviceHardwareProfile.isAnalogSupported(PinNr)) arduino.pinMode(s, PinMode.ANALOG); Mode = arduino.getPinMode(s); Value = arduino.analogRead(s); Values[s] = new KeyValuePair<Enum, string>(Mode, Value.ToString()); } foreach (byte PinNr in arduino.DeviceHardwareProfile.DigitalPins) { if (DisabledPins.ContainsKey(PinNr) || (PinNr > 6 && PinNr != 13)) // Not sure why this limitation is necessary. Without it, my Arduino board (or the Microsoft Firmata library) stops providing me with pin update events. continue; if (PinNr == 13) { arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. arduino.digitalWrite(13, PinState.HIGH); } else { if (arduino.DeviceHardwareProfile.isDigitalInputSupported(PinNr)) arduino.pinMode(PinNr, PinMode.INPUT); } s = "D" + PinNr.ToString(); Mode = arduino.getPinMode(PinNr); State = arduino.digitalRead(PinNr); Values[s] = new KeyValuePair<Enum, string>(Mode, State.ToString()); } await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (arduinoPins) { foreach (KeyValuePair<string, KeyValuePair<Enum, string>> P in Values) arduinoPins[P.Key] = MainPage.Instance.AddPin(P.Key, P.Value.Key, P.Value.Value); } }); this.SetupControlServer(); }; arduino.AnalogPinUpdated += async (pin, value) => { KeyValuePair<TextBlock, TextBlock> P; DateTime TP = DateTime.Now; lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue(pin, out P)) return; } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new Int32Field(ThingReference.Empty, TP, pin + ", Raw", value, FieldType.Momentary, FieldQoS.AutomaticReadout), new QuantityField(ThingReference.Empty, TP, pin, value / 10.24, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduino.DigitalPinUpdated += async (pin, value) => { KeyValuePair<TextBlock, TextBlock> P; DateTime TP = DateTime.Now; string s = "D" + pin.ToString(); lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue("D" + pin.ToString(), out P)) return; } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); break; } } sensorServer = new SensorServer(xmppClient, provisioningClient, true); sensorServer.OnExecuteReadoutRequest += (Sender, Request) => { DateTime Now = DateTime.Now; LinkedList<Field> Fields = new LinkedList<Field>(); DateTime TP = DateTime.Now; string s; bool ReadMomentary = Request.IsIncluded(FieldType.Momentary); bool ReadStatus = Request.IsIncluded(FieldType.Status); Log.Informational("Readout requested", string.Empty, Request.Actor); foreach (KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>> Pin in gpioPins.Values) { if (ReadMomentary && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString())) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.Read(), FieldType.Momentary, FieldQoS.AutomaticReadout)); } if (ReadStatus && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString() + ", Mode")) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.GetDriveMode(), FieldType.Status, FieldQoS.AutomaticReadout)); } } if (arduinoPins != null) { foreach (KeyValuePair<string, KeyValuePair<TextBlock, TextBlock>> Pin in arduinoPins) { byte i; if (ReadMomentary && Request.IsIncluded(s = Pin.Key)) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.digitalRead(i), FieldType.Momentary, FieldQoS.AutomaticReadout)); } else { ushort Raw = arduino.analogRead(s); double Percent = Raw / 10.24; Fields.AddLast(new Int32Field(ThingReference.Empty, TP, s + ", Raw", Raw, FieldType.Momentary, FieldQoS.AutomaticReadout)); Fields.AddLast(new QuantityField(ThingReference.Empty, TP, s, Percent, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } } if (ReadStatus && Request.IsIncluded(s = Pin.Key + ", Mode")) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(i), FieldType.Status, FieldQoS.AutomaticReadout)); } else { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(s), FieldType.Status, FieldQoS.AutomaticReadout)); } } } } Request.ReportFields(true, Fields); }; if (arduino == null) this.SetupControlServer(); xmppClient.Connect(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await Dialog.ShowAsync(); } }
/// <summary> /// Write a value to the pin /// </summary> /// <param name="value">The value to write to the pin</param> public void Write(PinState value) { Write(value == PinState.High); }
private async void Init() { try { Log.Informational("Starting application."); instance = this; Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ImageCodec).GetTypeInfo().Assembly, typeof(MarkdownDocument).GetTypeInfo().Assembly, typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly, typeof(JwsAlgorithm).GetTypeInfo().Assembly, typeof(Expression).GetTypeInfo().Assembly, typeof(Graph).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); Database.Register(new FilesProvider(ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000)); DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += () => { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). PinState Pin8 = this.arduino.digitalRead(8); this.lastMotion = Pin8 == PinState.HIGH; MainPage.Instance.DigitalPinUpdated(8, Pin8); this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.arduino.digitalWrite(9, 0); // Relay set to 0 this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0")); this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000); }; this.arduino.AnalogPinUpdated += (pin, value) => { MainPage.Instance.AnalogPinUpdated(pin, value); }; this.arduino.DigitalPinUpdated += (pin, value) => { MainPage.Instance.DigitalPinUpdated(pin, value); if (pin == 8) { this.lastMotion = (value == PinState.HIGH); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory); this.httpServer = new HttpServer(); //this.httpServer = new HttpServer(new LogSniffer()); StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico")); string Root = File.Path; Root = Root.Substring(0, Root.Length - 11); this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true)); this.httpServer.Register("/", (req, resp) => { throw new TemporaryRedirectException("/Index.md"); }); this.httpServer.Register("/Momentary", (req, resp) => { resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store"); if (req.Header.Accept != null) { switch (req.Header.Accept.GetBestContentType("text/xml", "application/xml", "application/json", "image/png", "image/jpeg", "image/webp")) { case "text/xml": case "application/xml": this.ReturnMomentaryAsXml(req, resp); break; case "application/json": this.ReturnMomentaryAsJson(req, resp); break; case "image/png": this.ReturnMomentaryAsPng(req, resp); break; case "image/jpg": this.ReturnMomentaryAsJpg(req, resp); break; case "image/webp": this.ReturnMomentaryAsWebp(req, resp); break; default: throw new NotAcceptableException(); } } else { this.ReturnMomentaryAsXml(req, resp); } }, this.tokenAuthentication); this.httpServer.Register("/MomentaryPng", (req, resp) => { IUser User; if (!req.Session.TryGetVariable("User", out Variable v) || (User = v.ValueObject as IUser) is null) { throw new ForbiddenException(); } resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store"); this.ReturnMomentaryAsPng(req, resp); }, true, false, true); this.httpServer.Register("/Login", null, (req, resp) => { if (!req.HasData || req.Session is null) { throw new BadRequestException(); } object Obj = req.DecodeData(); if (!(Obj is Dictionary <string, string> Form) || !Form.TryGetValue("UserName", out string UserName) || !Form.TryGetValue("Password", out string Password)) { throw new BadRequestException(); } string From = null; if (req.Session.TryGetVariable("from", out Variable v)) { From = v.ValueObject as string; } if (string.IsNullOrEmpty(From)) { From = "/Index.md"; } IUser User = this.Login(UserName, Password); if (User != null) { Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor); req.Session["User"] = User; req.Session.Remove("LoginError"); throw new SeeOtherException(From); } else { Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor); req.Session["LoginError"] = "Invalid login credentials provided."; } throw new SeeOtherException(req.Header.Referer.Value); }, true, false, true); this.httpServer.Register("/GetSessionToken", null, (req, resp) => { IUser User; if (!req.Session.TryGetVariable("User", out Variable v) || (User = v.ValueObject as IUser) is null) { throw new ForbiddenException(); } string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName)); resp.ContentType = JwtCodec.ContentType; resp.Write(Token); }, true, false, true); }
/// <summary> /// Writes the specified value to the specified GPIO pin. /// </summary> /// <param name="pin"> /// The pin to write the value to. /// </param> /// <param name="value"> /// The value to write to the pin. /// </param> public static void Write(GpioPins pin, PinState value) { String num = GetGpioPinNumber(pin); String name = Enum.GetName(typeof(GpioPins), pin); internal_Write((Int32)pin, value, num, name); }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ICoapContentFormat).GetTypeInfo().Assembly, typeof(IDtlsCredentials).GetTypeInfo().Assembly, typeof(Lwm2mClient).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000)); DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); foreach (DeviceInformation DeviceInfo in Devices) { if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino")) { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += () => { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(0, PinMode.INPUT); // PIR sensor (motion detection). PinState Pin0 = this.arduino.digitalRead(0); this.lastMotion = Pin0 == PinState.HIGH; MainPage.Instance.DigitalPinUpdated(0, Pin0); this.arduino.pinMode(1, PinMode.OUTPUT); // Relay. this.arduino.digitalWrite(1, 0); // Relay set to 0 this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0")); this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000); }; this.arduino.AnalogPinUpdated += (pin, value) => { MainPage.Instance.AnalogPinUpdated(pin, value); }; this.arduino.DigitalPinUpdated += (pin, value) => { MainPage.Instance.DigitalPinUpdated(pin, value); if (pin == 0) { bool Input = (value == PinState.HIGH); this.lastMotion = Input; this.digitalInput0?.Set(Input); this.presenceSensor0?.Set(Input); this.genericSensor0?.Set(Input ? 1.0 : 0.0); this.motionResource?.TriggerAll(); this.momentaryResource?.TriggerAll(); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); break; } } this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); /************************************************************************************ * To create an unencrypted CoAP Endpoint on the default CoAP port: * * this.coapEndpoint = new CoapEndpoint(); * * To create an unencrypted CoAP Endpoint on the default CoAP port, * with a sniffer that outputs communication to the window: * * this.coapEndpoint = new CoapEndpoint(new LogSniffer()); * * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using * the users defined in the IUserSource users: * * this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users); * * To create a CoAP endpoint, that listens to both the default CoAP port, for * unencrypted communication, and the default CoAPS port, for encrypted, * authenticated and authorized communication, using * the users defined in the IUserSource users. Only users having the given * privilege (if not empty) will be authorized to access resources on the endpoint: * * this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, * new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false); * ************************************************************************************/ //this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, // new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false); this.coapEndpoint = new CoapEndpoint(new int[] { 5783 }, new int[] { 5784 }, null, null, false, false); this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) => { string s; if (this.lastLight.HasValue) { s = ToString(this.lastLight.Value, 2) + " %"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, Notifications.Unacknowledged, "Light, in %.", null, null, new int[] { PlainText.ContentFormatCode }); this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5)); this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) => { string s; if (this.lastMotion.HasValue) { s = this.lastMotion.Value ? "true" : "false"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, Notifications.Acknowledged, "Motion detector.", null, null, new int[] { PlainText.ContentFormatCode }); this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0)); this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) => { if (req.IsAcceptable(Xml.ContentFormatCode)) { this.ReturnMomentaryAsXml(req, resp); } else if (req.IsAcceptable(Json.ContentFormatCode)) { this.ReturnMomentaryAsJson(req, resp); } else if (req.IsAcceptable(PlainText.ContentFormatCode)) { this.ReturnMomentaryAsPlainText(req, resp); } else if (req.Accept.HasValue) { throw new CoapException(CoapCode.NotAcceptable); } else { this.ReturnMomentaryAsPlainText(req, resp); } }, Notifications.Acknowledged, "Momentary values.", null, null, new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode }); this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5)); this.lwm2mClient = new Lwm2mClient("MIoT:Sensor:" + this.deviceId, this.coapEndpoint, new Lwm2mSecurityObject(), new Lwm2mServerObject(), new Lwm2mAccessControlObject(), new Lwm2mDeviceObject("Waher Data AB", "SensorLwm2m", this.deviceId, "1.0", "Sensor", "1.0", "1.0"), new DigitalInput(this.digitalInput0 = new DigitalInputInstance(0, this.lastMotion, "Motion Detector", "PIR")), new AnalogInput(this.analogInput0 = new AnalogInputInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor", "%")), new GenericSensor(this.genericSensor0 = new GenericSensorInstance(0, null, string.Empty, 0, 1, "Motion Detector", "PIR"), this.genericSensor1 = new GenericSensorInstance(1, this.lastLight, "%", 0, 100, "Ambient Light Sensor", "%")), new IlluminanceSensor(this.illuminanceSensor0 = new IlluminanceSensorInstance(0, this.lastLight, "%", 0, 100)), new PresenceSensor(this.presenceSensor0 = new PresenceSensorInstance(0, this.lastMotion, "PIR")), new PercentageSensor(this.percentageSensor0 = new PercentageSensorInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor"))); await this.lwm2mClient.LoadBootstrapInfo(); this.lwm2mClient.OnStateChanged += (sender, e) => { Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + "."); }; this.lwm2mClient.OnBootstrapCompleted += (sender, e) => { Log.Informational("Bootstrap procedure completed."); }; this.lwm2mClient.OnBootstrapFailed += (sender, e) => { Log.Error("Bootstrap procedure failed."); this.coapEndpoint.ScheduleEvent(async(P) => { try { await this.RequestBootstrap(); } catch (Exception ex) { Log.Critical(ex); } }, DateTime.Now.AddMinutes(15), null); }; this.lwm2mClient.OnRegistrationSuccessful += (sender, e) => { Log.Informational("Server registration completed."); }; this.lwm2mClient.OnRegistrationFailed += (sender, e) => { Log.Error("Server registration failed."); }; this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) => { Log.Informational("Server deregistration completed."); }; this.lwm2mClient.OnDeregistrationFailed += (sender, e) => { Log.Error("Server deregistration failed."); }; this.lwm2mClient.OnRebootRequest += async(sender, e) => { Log.Warning("Reboot is requested."); try { await this.RequestBootstrap(); } catch (Exception ex) { Log.Critical(ex); } }; await this.RequestBootstrap(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
/// <summary> /// Initializes a new instance of the <see cref="CyrusBuilt.MonoPi.IO.GpioFile"/> /// class with the Rev1 pin to access, the I/O direction, and the initial value. /// </summary> /// <param name="pin"> /// The pin on the board to access. /// </param> /// <param name="mode"> /// The I/0 mode of the pin. /// </param> /// <param name="initialValue"> /// The pin's initial value. /// </param> public GpioFile(GpioPins pin, PinMode mode, PinState initialValue) : base(pin, mode, initialValue) { }
private async void SampleValues(object State) { try { ushort A0 = this.arduino.analogRead("A0"); PinState D8 = this.arduino.digitalRead(8); if (this.windowA0[0].HasValue) { this.sumA0 -= this.windowA0[0].Value; this.nrA0--; } Array.Copy(this.windowA0, 1, this.windowA0, 0, windowSize - 1); this.windowA0[windowSize - 1] = A0; this.sumA0 += A0; this.nrA0++; double AvgA0 = ((double)this.sumA0) / this.nrA0; int? v; if (this.nrA0 >= windowSize - 2) { int NrLt = 0; int NrGt = 0; foreach (int?Value in this.windowA0) { if (Value.HasValue) { if (Value.Value < AvgA0) { NrLt++; } else if (Value.Value > AvgA0) { NrGt++; } } } if (NrLt == 1 || NrGt == 1) { v = this.windowA0[spikePos]; if (v.HasValue) { if ((NrLt == 1 && v.Value < AvgA0) || (NrGt == 1 && v.Value > AvgA0)) { this.sumA0 -= v.Value; this.nrA0--; this.windowA0[spikePos] = null; AvgA0 = ((double)this.sumA0) / this.nrA0; Log.Informational("Spike removed.", new KeyValuePair <string, object>("A0", v.Value)); } } } } int i, n; for (AvgA0 = i = n = 0; i < spikePos; i++) { if ((v = this.windowA0[i]).HasValue) { n++; AvgA0 += v.Value; } } if (n > 0) { AvgA0 /= n; double Light = (100.0 * AvgA0) / 1024; this.lastLight = Light; MainPage.Instance.LightUpdated(Light, 2, "%"); this.sumLight += Light; this.sumMotion += (D8 == PinState.HIGH ? 1 : 0); this.nrTerms++; DateTime Timestamp = DateTime.Now; if (!this.minLight.HasValue || Light < this.minLight.Value) { this.minLight = Light; this.minLightAt = Timestamp; } if (!this.maxLight.HasValue || Light > this.maxLight.Value) { this.maxLight = Light; this.maxLightAt = Timestamp; } if (!this.lastMinute.HasValue) { this.lastMinute = Timestamp.Minute; } else if (this.lastMinute.Value != Timestamp.Minute) { this.lastMinute = Timestamp.Minute; LastMinute Rec = new LastMinute() { Timestamp = Timestamp, Light = Light, Motion = D8, MinLight = this.minLight, MinLightAt = this.minLightAt, MaxLight = this.maxLight, MaxLightAt = this.maxLightAt, AvgLight = (this.nrTerms == 0 ? (double?)null : this.sumLight / this.nrTerms), AvgMotion = (this.nrTerms == 0 ? (double?)null : (this.sumMotion * 100.0) / this.nrTerms) }; await Database.Insert(Rec); this.minLight = null; this.minLightAt = DateTime.MinValue; this.maxLight = null; this.maxLightAt = DateTime.MinValue; this.sumLight = 0; this.sumMotion = 0; this.nrTerms = 0; foreach (LastMinute Rec2 in await Database.Find <LastMinute>(new FilterFieldLesserThan("Timestamp", Timestamp.AddMinutes(-100)))) { await Database.Delete(Rec2); } if (Timestamp.Minute == 0) { DateTime From = new DateTime(Timestamp.Year, Timestamp.Month, Timestamp.Day, Timestamp.Hour, 0, 0).AddHours(-1); DateTime To = From.AddHours(1); int NLight = 0; int NMotion = 0; LastHour HourRec = new LastHour() { Timestamp = Timestamp, Light = Light, Motion = D8, MinLight = Rec.MinLight, MinLightAt = Rec.MinLightAt, MaxLight = Rec.MaxLight, MaxLightAt = Rec.MaxLightAt, AvgLight = 0, AvgMotion = 0 }; foreach (LastMinute Rec2 in await Database.Find <LastMinute>(0, 60, new FilterAnd( new FilterFieldLesserThan("Timestamp", To), new FilterFieldGreaterOrEqualTo("Timestamp", From)))) { if (Rec2.AvgLight.HasValue) { HourRec.AvgLight += Rec2.AvgLight.Value; NLight++; } if (Rec2.AvgMotion.HasValue) { HourRec.AvgMotion += Rec2.AvgMotion.Value; NMotion++; } if (Rec2.MinLight < HourRec.MinLight) { HourRec.MinLight = Rec2.MinLight; HourRec.MinLightAt = Rec.MinLightAt; } if (Rec2.MaxLight < HourRec.MaxLight) { HourRec.MaxLight = Rec2.MaxLight; HourRec.MaxLightAt = Rec.MaxLightAt; } } if (NLight == 0) { HourRec.AvgLight = null; } else { HourRec.AvgLight /= NLight; } if (NMotion == 0) { HourRec.AvgMotion = null; } else { HourRec.AvgMotion /= NMotion; } await Database.Insert(HourRec); foreach (LastHour Rec2 in await Database.Find <LastHour>(new FilterFieldLesserThan("Timestamp", Timestamp.AddHours(-100)))) { await Database.Delete(Rec2); } if (Timestamp.Hour == 0) { From = new DateTime(Timestamp.Year, Timestamp.Month, Timestamp.Day, 0, 0, 0).AddDays(-1); To = From.AddDays(1); NLight = 0; NMotion = 0; LastDay DayRec = new LastDay() { Timestamp = Timestamp, Light = Light, Motion = D8, MinLight = HourRec.MinLight, MinLightAt = HourRec.MinLightAt, MaxLight = HourRec.MaxLight, MaxLightAt = HourRec.MaxLightAt, AvgLight = 0, AvgMotion = 0 }; foreach (LastHour Rec2 in await Database.Find <LastHour>(0, 24, new FilterAnd( new FilterFieldLesserThan("Timestamp", To), new FilterFieldGreaterOrEqualTo("Timestamp", From)))) { if (Rec2.AvgLight.HasValue) { DayRec.AvgLight += Rec2.AvgLight.Value; NLight++; } if (Rec2.AvgMotion.HasValue) { DayRec.AvgMotion += Rec2.AvgMotion.Value; NMotion++; } if (Rec2.MinLight < DayRec.MinLight) { DayRec.MinLight = Rec2.MinLight; DayRec.MinLightAt = Rec.MinLightAt; } if (Rec2.MaxLight < DayRec.MaxLight) { DayRec.MaxLight = Rec2.MaxLight; DayRec.MaxLightAt = Rec.MaxLightAt; } } if (NLight == 0) { DayRec.AvgLight = null; } else { DayRec.AvgLight /= NLight; } if (NMotion == 0) { DayRec.AvgMotion = null; } else { DayRec.AvgMotion /= NMotion; } await Database.Insert(DayRec); foreach (LastDay Rec2 in await Database.Find <LastDay>(new FilterFieldLesserThan("Timestamp", Timestamp.AddDays(-100)))) { await Database.Delete(Rec2); } } } } } } catch (Exception ex) { Log.Critical(ex); } }
public abstract void SetdigitalPinState(int pin, PinState state);
// Cleans up any existing Overlapped object and related state variables. private void FreeOverlapped(bool checkForShutdown) { if (!checkForShutdown || !Environment.HasShutdownStarted) { // Free the overlapped object. if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid) { _ptrNativeOverlapped.Dispose(); _ptrNativeOverlapped = null; } // Free the preallocated overlapped object. This in turn will unpin // any pinned buffers. if (_preAllocatedOverlapped != null) { _preAllocatedOverlapped.Dispose(); _preAllocatedOverlapped = null; _pinState = PinState.None; _pinnedAcceptBuffer = null; _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; } // Free any allocated GCHandles. if (_socketAddressGCHandle.IsAllocated) { _socketAddressGCHandle.Free(); _pinnedSocketAddress = null; } if (_wsaMessageBufferGCHandle.IsAllocated) { _wsaMessageBufferGCHandle.Free(); _ptrWSAMessageBuffer = IntPtr.Zero; } if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated) { _wsaRecvMsgWSABufferArrayGCHandle.Free(); _ptrWSARecvMsgWSABufferArray = IntPtr.Zero; } if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); _ptrControlBuffer = IntPtr.Zero; } } }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000)); DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo == null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += () => { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). PinState Pin8 = this.arduino.digitalRead(8); this.lastMotion = Pin8 == PinState.HIGH; MainPage.Instance.DigitalPinUpdated(8, Pin8); this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.arduino.digitalWrite(9, 0); // Relay set to 0 this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0")); this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000); }; this.arduino.AnalogPinUpdated += (pin, value) => { MainPage.Instance.AnalogPinUpdated(pin, value); }; this.arduino.DigitalPinUpdated += (pin, value) => { MainPage.Instance.DigitalPinUpdated(pin, value); if (pin == 8) { this.PublishMotion(value == PinState.HIGH); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty); //this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty, new LogSniffer()); this.mqttClient.OnStateChanged += (sender, state) => Log.Informational("MQTT client state changed: " + state.ToString()); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
// Sets up an Overlapped object with with multiple buffers pinned. unsafe private void SetupOverlappedMultiple() { ArraySegment<byte>[] tempList = new ArraySegment<byte>[_bufferList.Count]; _bufferList.CopyTo(tempList, 0); // Number of things to pin is number of buffers. // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != tempList.Length)) { _objectsToPin = new object[tempList.Length]; } // Fill in object array. for (int i = 0; i < (tempList.Length); i++) { _objectsToPin[i] = tempList[i].Array; } if (_wsaBufferArray == null || _wsaBufferArray.Length != tempList.Length) { _wsaBufferArray = new WSABuffer[tempList.Length]; } // Pin buffers and fill in WSABuffer descriptor pointers and lengths. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." + LoggingHash.HashString(_preAllocatedOverlapped)); } for (int i = 0; i < tempList.Length; i++) { ArraySegment<byte> localCopy = tempList[i]; RangeValidationHelpers.ValidateSegment(localCopy); _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset); _wsaBufferArray[i].Length = localCopy.Count; } _pinState = PinState.MultipleBuffer; }
/// <summary> /// This function is called when the Windows Remote Arduino library reports that an input value has changed for a digital pin. /// </summary> /// <param name="pin">The pin whose value has changed</param> /// <param name="state">the new state of the pin, either HIGH or LOW</param> private void Arduino_OnDigitalPinUpdated( byte pin, PinState state ) { //we must dispatch the change to the UI thread to change the indicator image var action = Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler( () => { UpdateDigitalPinIndicators( pin ); } ) ); }
static void SetHeatingPin(PinState state) { GPIOMem heatingPin = new GPIOMem(GPIOPins.GPIO_14); heatingPin.PinDirection = GPIODirection.Out; heatingPin.Write(state); }
private void FreeOverlapped(bool checkForShutdown) { if (!checkForShutdown || !NclUtilities.HasShutdownStarted) { if ((this.m_PtrNativeOverlapped != null) && !this.m_PtrNativeOverlapped.IsInvalid) { this.m_PtrNativeOverlapped.Dispose(); this.m_PtrNativeOverlapped = null; this.m_Overlapped = null; this.m_PinState = PinState.None; this.m_PinnedAcceptBuffer = null; this.m_PinnedSingleBuffer = null; this.m_PinnedSingleBufferOffset = 0; this.m_PinnedSingleBufferCount = 0; } if (this.m_SocketAddressGCHandle.IsAllocated) { this.m_SocketAddressGCHandle.Free(); } if (this.m_WSAMessageBufferGCHandle.IsAllocated) { this.m_WSAMessageBufferGCHandle.Free(); } if (this.m_WSARecvMsgWSABufferArrayGCHandle.IsAllocated) { this.m_WSARecvMsgWSABufferArrayGCHandle.Free(); } if (this.m_ControlBufferGCHandle.IsAllocated) { this.m_ControlBufferGCHandle.Free(); } } }
/// <summary> /// Determine device I2C address based on the configuration pin states. /// </summary> /// <param name="adr0">The adr0 pin state</param> /// <param name="adr1">The adr1 pin state</param> /// <returns>System.Int32.</returns> public static int I2CAddressFromPins(PinState adr0, PinState adr1) { return(Helpers.I2CAddressFromPins(adr0, adr1)); }
private void SetupOverlappedMultiple() { this.m_Overlapped = new Overlapped(); ArraySegment<byte>[] array = new ArraySegment<byte>[this.m_BufferList.Count]; this.m_BufferList.CopyTo(array, 0); if ((this.m_ObjectsToPin == null) || (this.m_ObjectsToPin.Length != array.Length)) { this.m_ObjectsToPin = new object[array.Length]; } for (int i = 0; i < array.Length; i++) { this.m_ObjectsToPin[i] = array[i].Array; } if ((this.m_WSABufferArray == null) || (this.m_WSABufferArray.Length != array.Length)) { this.m_WSABufferArray = new WSABuffer[array.Length]; } this.m_PtrNativeOverlapped = new SafeNativeOverlapped(this.m_Overlapped.UnsafePack(new IOCompletionCallback(this.CompletionPortCallback), this.m_ObjectsToPin)); for (int j = 0; j < array.Length; j++) { ArraySegment<byte> segment = array[j]; ValidationHelper.ValidateSegment(segment); this.m_WSABufferArray[j].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(segment.Array, segment.Offset); this.m_WSABufferArray[j].Length = segment.Count; } this.m_PinState = PinState.MultipleBuffer; }