RoboidControl-csharp/src/Things/DigitalSensor.cs

74 lines
3.0 KiB
C#

using System;
namespace RoboidControl {
/// <summary>
/// A sensor which can detect touches
/// </summary>
public class DigitalSensor : Thing {
/// <summary>
/// Create a digital sensor without communication abilities
/// </summary>
/// <param name="invokeEvent">Invoke a OnNewThing event when the thing has been created</param>
public DigitalSensor(bool invokeEvent = true) : base(Type.Switch, invokeEvent) { }
/// <summary>
/// Create a digital sensor for a participant
/// </summary>
/// <param name="owner">The owning participant</param>
/// <param name="thingId">The ID of the thing, leave out or set to zero to generate an ID</param>
/// <param name="invokeEvent">Invoke a OnNewThing event when the thing has been created</param>
public DigitalSensor(Participant owner, byte thingId = 0, bool invokeEvent = true) : base(owner, Type.Switch, thingId, invokeEvent) { }
/// <summary>
/// Create a new child digital sensor
/// </summary>
/// <param name="parent">The parent thing</param>
/// <param name="thingId">The ID of the thing, leave out or set to zero to generate an ID</param>
/// <param name="invokeEvent">Invoke a OnNewThing event when the thing has been created</param>
public DigitalSensor(Thing parent, byte thingId = 0, bool invokeEvent = true) : base(parent, Type.Switch, thingId, invokeEvent) { }
/// <summary>
/// Value which is true when the sensor is touching something, false otherwise
/// </summary>
private bool _state = false;
public bool state {
get { return _state; }
set {
if (_state != value) {
_state = value;
}
stateUpdated = true;
}
}
private bool stateUpdated = false;
#if UNITY_5_3_OR_NEWER
/// @copydoc Passer::RoboidControl::Thing::CreateComponent
public override void CreateComponent() {
this.component = Unity.DigitalSensor.Create(this);
this.component.core = this;
}
#endif
/// <summary>
/// Function used to generate binary data for this digital sensor
/// </summary>
/// <returns>A byte array with the binary data</returns>
/// <remark>The byte array will be empty when the digital status has not changed</remark>
public override byte[] GenerateBinary() {
if (!stateUpdated)
return Array.Empty<byte>();
byte[] bytes = new byte[1];
bytes[0] = (byte)(state ? 1 : 0);
stateUpdated = false;
return bytes;
}
/// <summary>
/// Function used to process binary data received for this digital sensor
/// </summary>
/// <param name="bytes">The binary data to process</param>
public override void ProcessBinary(byte[] bytes) {
this.state |= (bytes[0] == 1);
}
}
}