Friends, i'm planning to do a cloud based videoplayback project in unity. In my project, cloud targets are detecting but videos are not playing. I need to do json based cloud recognition to play videos but i don't know how to do that.
This is my code for your reference:
using System;
using UnityEngine;
using Vuforia;
using UnityEngine.UI;
/// <summary>
/// This MonoBehaviour implements the Cloud Reco Event handling for this sample.
/// It registers itself at the CloudRecoBehaviour and is notified of new search results.
/// </summary>
public class SimpleCloudHandler : MonoBehaviour, ICloudRecoEventHandler
{
#region PRIVATE_MEMBER_VARIABLES
// CloudRecoBehaviour reference to avoid lookups
private CloudRecoBehaviour mCloudRecoBehaviour;
// ImageTracker reference to avoid lookups
private ObjectTracker mImageTracker;
private bool mIsScanning = false;
private string mTargetMetadata = "";
private GameObject videoObject;
#endregion // PRIVATE_MEMBER_VARIABLES
#region EXPOSED_PUBLIC_VARIABLES
/// <summary>
/// can be set in the Unity inspector to reference a ImageTargetBehaviour that is used for augmentations of new cloud reco results.
/// </summary>
public ImageTargetBehaviour ImageTargetTemplate;
#endregion
#region UNTIY_MONOBEHAVIOUR_METHODS
/// <summary>
/// register for events at the CloudRecoBehaviour
/// </summary>
void Start()
{
// register this event handler at the cloud reco behaviour
CloudRecoBehaviour cloudRecoBehaviour = GetComponent<CloudRecoBehaviour>();
if (cloudRecoBehaviour)
{
cloudRecoBehaviour.RegisterEventHandler(this);
}
// remember cloudRecoBehaviour for later
mCloudRecoBehaviour = cloudRecoBehaviour;
}
#endregion // UNTIY_MONOBEHAVIOUR_METHODS
#region ICloudRecoEventHandler_IMPLEMENTATION
/// <summary>
/// called when TargetFinder has been initialized successfully
/// </summary>
public void OnInitialized()
{
// get a reference to the Image Tracker, remember it
mImageTracker = (ObjectTracker)TrackerManager.Instance.GetTracker<ObjectTracker>();
}
/// <summary>
/// visualize initialization errors
/// </summary>
public void OnInitError(TargetFinder.InitState initError)
{
}
/// <summary>
/// visualize update errors
/// </summary>
public void OnUpdateError(TargetFinder.UpdateState updateError)
{
}
/// <summary>
/// when we start scanning, unregister Trackable from the ImageTargetTemplate, then delete all trackables
/// </summary>
public void OnStateChanged(bool scanning) {
mIsScanning = scanning;
if (scanning) {
// clear all known trackables
ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker> ();
tracker.TargetFinder.ClearTrackables (false);
}
}
/// <summary>
/// Handles new search results
/// </summary>
/// <param name="targetSearchResult"></param>
public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
{
// duplicate the referenced image target
GameObject newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;
GameObject augmentation = null;
string model_name = targetSearchResult.MetaData;
if( augmentation != null )
augmentation.transform.parent = newImageTarget.transform;
// enable the new result with the same ImageTargetBehaviour:
//Debug.Log("Metadata value is " + model_name );
//VideoPlaybackBehaviour video = ImageTargetTemplate.gameObject.GetComponentInChildren<VideoPlaybackBehaviour>();
mTargetMetadata = model_name;
if (targetSearchResult.MetaData == "a") {
ImageTargetAbstractBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking (targetSearchResult, newImageTarget);
}
if (!mIsScanning)
{
// stop the target finder
mCloudRecoBehaviour.CloudRecoEnabled = true;
}
}
#endregion // ICloudRecoEventHandler_IMPLEMENTATION
}
Related
Hey i'm new to literally everything, sorry if this was solved but i'm having trouble editing a script from Unity's Platformer 2D Game. There's an Error where Player can't die and the error NullReferenceException: Object reference not set to an instance of an object. But idk the solution.
NullReferenceException: Object reference not set to an instance of an object
Platformer.Gameplay.PlayerDeath.Execute () (at Assets/Scripts/Gameplay/PlayerDeath.cs:20)
Platformer.Core.Simulation+Event`1[T].ExecuteEvent () (at Assets/Scripts/Core/Simulation.Event.cs:57)
Platformer.Core.Simulation.Tick () (at Assets/Scripts/Core/Simulation.cs:114)
Platformer.Mechanics.GameController.Update () (at Assets/Scripts/Mechanics/GameController.cs:40)
This is my PlayerDeath
using System.Collections;
using System.Collections.Generic;
using Platformer.Core;
using Platformer.Model;
using UnityEngine;
namespace Platformer.Gameplay
{
/// <summary>
/// Fired when the player has died.
/// </summary>
/// <typeparam name="PlayerDeath"></typeparam>
public class PlayerDeath : Simulation.Event<PlayerDeath>
{
PlatformerModel model = Simulation.GetModel<PlatformerModel>();
public override void Execute()
{
var player = model.player;
if (player.health.IsAlive)
{
player.health.Die();
model.virtualCamera.m_Follow = null;
model.virtualCamera.m_LookAt = null;
// player.collider.enabled = false;
player.controlEnabled = false;
if (player.audioSource && player.ouchAudio)
player.audioSource.PlayOneShot(player.ouchAudio);
player.animator.SetTrigger("hurt");
player.animator.SetBool("dead", true);
Simulation.Schedule<PlayerSpawn>(2);
}
}
}
}
This is my Simulation.Event
using System.Collections.Generic;
namespace Platformer.Core
{
public static partial class Simulation
{
/// <summary>
/// An event is something that happens at a point in time in a simulation.
/// The Precondition method is used to check if the event should be executed,
/// as conditions may have changed in the simulation since the event was
/// originally scheduled.
/// </summary>
/// <typeparam name="Event"></typeparam>
public abstract class Event : System.IComparable<Event>
{
internal float tick;
public int CompareTo(Event other)
{
return tick.CompareTo(other.tick);
}
public abstract void Execute();
public virtual bool Precondition() => true;
internal virtual void ExecuteEvent()
{
if (Precondition())
Execute();
}
/// <summary>
/// This method is generally used to set references to null when required.
/// It is automatically called by the Simulation when an event has completed.
/// </summary>
internal virtual void Cleanup()
{
}
}
/// <summary>
/// Event<T> adds the ability to hook into the OnExecute callback
/// whenever the event is executed. Use this class to allow functionality
/// to be plugged into your application with minimal or zero configuration.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Event<T> : Event where T : Event<T>
{
public static System.Action<T> OnExecute;
internal override void ExecuteEvent()
{
if (Precondition())
{
Execute();
OnExecute?.Invoke((T)this);
}
}
}
}
}
This is my Simulation
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Platformer.Core
{
/// <summary>
/// The Simulation class implements the discrete event simulator pattern.
/// Events are pooled, with a default capacity of 4 instances.
/// </summary>
public static partial class Simulation
{
static HeapQueue<Event> eventQueue = new HeapQueue<Event>();
static Dictionary<System.Type, Stack<Event>> eventPools = new Dictionary<System.Type, Stack<Event>>();
/// <summary>
/// Create a new event of type T and return it, but do not schedule it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
static public T New<T>() where T : Event, new()
{
Stack<Event> pool;
if (!eventPools.TryGetValue(typeof(T), out pool))
{
pool = new Stack<Event>(4);
pool.Push(new T());
eventPools[typeof(T)] = pool;
}
if (pool.Count > 0)
return (T)pool.Pop();
else
return new T();
}
/// <summary>
/// Clear all pending events and reset the tick to 0.
/// </summary>
public static void Clear()
{
eventQueue.Clear();
}
/// <summary>
/// Schedule an event for a future tick, and return it.
/// </summary>
/// <returns>The event.</returns>
/// <param name="tick">Tick.</param>
/// <typeparam name="T">The event type parameter.</typeparam>
static public T Schedule<T>(float tick = 0) where T : Event, new()
{
var ev = New<T>();
ev.tick = Time.time + tick;
eventQueue.Push(ev);
return ev;
}
/// <summary>
/// Reschedule an existing event for a future tick, and return it.
/// </summary>
/// <returns>The event.</returns>
/// <param name="tick">Tick.</param>
/// <typeparam name="T">The event type parameter.</typeparam>
static public T Reschedule<T>(T ev, float tick) where T : Event, new()
{
ev.tick = Time.time + tick;
eventQueue.Push(ev);
return ev;
}
/// <summary>
/// Return the simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public T GetModel<T>() where T : class, new()
{
return InstanceRegister<T>.instance;
}
/// <summary>
/// Set a simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public void SetModel<T>(T instance) where T : class, new()
{
InstanceRegister<T>.instance = instance;
}
/// <summary>
/// Destroy the simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public void DestroyModel<T>() where T : class, new()
{
InstanceRegister<T>.instance = null;
}
/// <summary>
/// Tick the simulation. Returns the count of remaining events.
/// If remaining events is zero, the simulation is finished unless events are
/// injected from an external system via a Schedule() call.
/// </summary>
/// <returns></returns>
static public int Tick()
{
var time = Time.time;
var executedEventCount = 0;
while (eventQueue.Count > 0 && eventQueue.Peek().tick <= time)
{
var ev = eventQueue.Pop();
var tick = ev.tick;
ev.ExecuteEvent();
if (ev.tick > tick)
{
//event was rescheduled, so do not return it to the pool.
}
else
{
// Debug.Log($"<color=green>{ev.tick} {ev.GetType().Name}</color>");
ev.Cleanup();
try
{
eventPools[ev.GetType()].Push(ev);
}
catch (KeyNotFoundException)
{
//This really should never happen inside a production build.
Debug.LogError($"No Pool for: {ev.GetType()}");
}
}
executedEventCount++;
}
return eventQueue.Count;
}
}
}
and this is my GameController
using Platformer.Core;
using Platformer.Model;
using UnityEngine;
namespace Platformer.Mechanics
{
/// <summary>
/// This class exposes the the game model in the inspector, and ticks the
/// simulation.
/// </summary>
public class GameController : MonoBehaviour
{
public static GameController Instance { get; private set; }
//This model field is public and can be therefore be modified in the
//inspector.
//The reference actually comes from the InstanceRegister, and is shared
//through the simulation and events. Unity will deserialize over this
//shared reference when the scene loads, allowing the model to be
//conveniently configured inside the inspector.
public PlatformerModel model = Simulation.GetModel<PlatformerModel>();
void Start()
{
Screen.SetResolution(1280, 720, true);
}
void OnEnable()
{
Instance = this;
}
void OnDisable()
{
if (Instance == this) Instance = null;
}
void Update()
{
if (Instance == this) Simulation.Tick();
}
}
}
I was dealing with the same issue. The problem generally begins when we write a custom player instead of using the default.
What you need to do, at least for the 2D Platformer microgame, is open up the GameObject called "GameController" (should be right up at the top) and drag your player* onto the Player field under the GameController component.
*Specifically, the GameObject that has your PlayerController component.
(I really like that Unity is diving into a full event system like Qt, but this Simulation class seems very convoluted and graceless to me. We'll see what I think as I progress with it; but I doubt it's that much more efficient than cached GameObject.Find calls.)
That should solve your problem!
I am trying to create a game in Unity3D which connects to bluetooth low energy device that supports the heart rate service and collects the HR data. I have created a WPF library that has been tested on a console application to connect to a BLE device and read the data which works perfectly. However, I do not know how to use this in Unity.
I transferred the library to Unity and had to disable it for the editor as the code uses Windows namespaces which are not supported in the editor. My problem now is how do I debug the code in Unity to check if the library code is working when I run the game. I tried wrapping the code for calling the library namespace and the functions from the library in #if NETFX_CORE, #if ENABLE_WINMD_SUPPORT, #if WINDOWS_UWP and many more but, never got any of the debug logs that I wrote.
Is there any possible solution to this?
Any help would be appreciated, thank you!
This is the code for the bluetooth LE connection library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;
namespace BLEHR
{
/// <summary>
/// Wraps and makes use if the <see cref="BluetoothLeAdvertisementWatcher"/>
/// for easier consumption
///
/// </summary>
public class BLEAdvertisementWatcher
{
#region Private Members
/// <summary>
/// The underlying bluetooth watcher class
/// </summary>
private readonly BluetoothLEAdvertisementWatcher mWatcher;
/// <summary>
/// a list of discovered devices
/// </summary>
private readonly Dictionary<string, BLEDevice> mDiscoveredDevices = new Dictionary<string, BLEDevice>();
/// <summary>
/// The details about Gatt services
/// </summary>
private readonly GattServiceIDs mGattServiceIds;
/// <summary>
/// a thread lock object for this class
/// </summary>
private readonly object mThreadLock = new object();
#endregion
#region Public Properties
/// <summary>
/// indicates is this watcher is listening for advertisements
/// </summary>
public bool Listening => mWatcher.Status == BluetoothLEAdvertisementWatcherStatus.Started;
/// <summary>
/// a list of discovered devices
/// </summary>
public IReadOnlyCollection<BLEDevice> DiscoveredDevices
{
get
{
//Clena up any Timeouts
CleanupTimeouts();
//Practice Thread safety
lock (mThreadLock)
{
//Convert to readonly list
return mDiscoveredDevices.Values.ToList().AsReadOnly();
}
}
}
/// <summary>
/// The timeout in seconds that a device is removed from the <see cref="DiscoveredDevices"/>
/// list if it is not re-advertised within this time
/// </summary>
public int TimeoutRemoval { get; set; } = 20;
public int HRValue { get; set; }
#endregion
#region Constructor
/// <summary>
/// The default constructor
/// </summary>
public BLEAdvertisementWatcher(GattServiceIDs gattIds)
{
//Null guard
mGattServiceIds = gattIds ?? throw new ArgumentNullException(nameof(gattIds));
//Create bluetooth listener
mWatcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
//Listen out for new advertisements
mWatcher.Received += WatcherAdvertisementReceivedAsync;
//Listen out for when the watcher stops listening
mWatcher.Stopped += (watcher, e) =>
{
//Inform listeners
StoppedListening();
};
}
#endregion
#region Private Methods
/// <summary>
/// Listens out for watcher advertisements
/// </summary>
/// <param name="sender"> The Watcher </param>
/// <param name="args">The Arguments </param>
private async void WatcherAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
//cleanup timeouts
CleanupTimeouts();
//Get BLE device info
var device = await GetBLEDeviceAsync(args.BluetoothAddress, args.Timestamp, args.RawSignalStrengthInDBm);
//Null guard
if(device == null)
{
return;
}
//is new discovery?
var newDiscovery = false;
var existingName = default(string);
//Lock your doors
lock (mThreadLock)
{
//Check if this is a new discovery
newDiscovery= !mDiscoveredDevices.ContainsKey(device.DeviceID);
//If this is not new...
if (!newDiscovery)
{
//Store the old name
existingName = mDiscoveredDevices[device.DeviceID].Name;
}
}
//Name changed?
var nameChanged =
//if it already exists
!newDiscovery &&
//And is not a blank name
!string.IsNullOrEmpty(device.Name) &&
//And the name is different
existingName != device.Name;
lock (mThreadLock)
{
//add/update the device in the dictionary
mDiscoveredDevices[device.DeviceID] = device;
}
//Inform listeners
DeviceDiscovered(device);
//if new discovery...
if (newDiscovery)
{
//Inform listeners
NewDeviceDiscovered(device);
}
}
/// <summary>
/// Connects to the BLE device and extracts more information from the
/// <seealso cref="https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice"/>
/// </summary>
/// <param name="address">The BT address of the device to connect to</param>
/// <param name="broadcastTime">The time the broadcast message was received</param>
/// <param name="rssi">The signal strength in dB</param>
/// <returns></returns>
private async Task<BLEDevice> GetBLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
{
//Get bluetooth device info
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();
//Null guard
if(device == null)
{
return null;
}
//Get GATT services that are available
var gatt = await device.GetGattServicesAsync().AsTask();
//if we have any services..
if(gatt.Status == GattCommunicationStatus.Success)
{
//loop each gatt service
foreach(var service in gatt.Services)
{
//This ID contains the GATT profile assigned number we want!
//TODO: Get more info and connect
var gattProfileId = service.Uuid;
}
}
//Return the new device information
return new BLEDevice
(
//Device ID
deviceID: device.DeviceId,
//Bluetooth address
address: device.BluetoothAddress,
//Device name
name: device.Name,
//Broadcast time
broadcastTime: broadcastTime,
//Signal strength
rssi: rssi,
//Is connected
connected: device.ConnectionStatus== BluetoothConnectionStatus.Connected,
//Can Pair?
canPair: device.DeviceInformation.Pairing.CanPair,
//Is Paired?
isPaired: device.DeviceInformation.Pairing.IsPaired
);
}
/// <summary>
/// Prune any timed out devices that we have not heard off
/// </summary>
private void CleanupTimeouts()
{
lock (mThreadLock)
{
//The date in time that if less than means a device has timed out
var threshold = DateTime.UtcNow - TimeSpan.FromSeconds(TimeoutRemoval);
//any devices that have not sent a new broadcast within the time
mDiscoveredDevices.Where(f => f.Value.BroadcastTime < threshold).ToList().ForEach(device =>
{
//remove device
mDiscoveredDevices.Remove(device.Key);
//Inform listeners
DeviceTimeout(device.Value);
});
}
}
#endregion
#region Public events
/// <summary>
/// Fired when the bluetooth watcher stops listening
/// </summary>
public event Action StoppedListening = () => { };
/// <summary>
/// Fired when the bluetooth watcher start listening
/// </summary>
public event Action StartedListening = () => { };
/// <summary>
/// fired when a new device is discovered
/// </summary>
public event Action<BLEDevice> NewDeviceDiscovered = (device) => {};
/// <summary>
/// fired when a device is discovered
/// </summary>
public event Action<BLEDevice> DeviceDiscovered = (device) => { };
/// <summary>
/// Fired when a device is removed for timing out
/// </summary>
public event Action<BLEDevice> DeviceTimeout = (device) => { };
#endregion
#region Public Methods
/// <summary>
/// Starts listening for advertisements
/// </summary>
public void StartListening()
{
lock (mThreadLock)
{
//if already listening...
if (Listening)
{
//DO nothing more
return;
}
//Start the underlying watcher
mWatcher.Start();
}
//inform listeners
StartedListening();
}
/// <summary>
/// Stops listening for advertisements
/// </summary>
public void StopListening()
{
lock (mThreadLock)
{
//if we are not currently listening
if (!Listening)
{
//Do nothing more
return;
}
//Stop listening
mWatcher.Stop();
//clear any devices
mDiscoveredDevices.Clear();
}
}
/// <summary>
/// Attempts to pair to a BLE device, by ID
/// </summary>
/// <param name="deviceID"> The BLE device ID</param>
/// <returns></returns>
public async Task PairToDeviceAsync(string deviceID)
{
//Get bluetooth device info
var device = await BluetoothLEDevice.FromIdAsync(deviceID).AsTask();
//Null guard
if (device == null)
{
//TODO: localize
throw new ArgumentNullException("");
}
//if we are already paired...
if (device.DeviceInformation.Pairing.IsPaired)
{
//un-pair the device
await device.DeviceInformation.Pairing.UnpairAsync().AsTask();
return;
}
//Try and pair to the device
device.DeviceInformation.Pairing.Custom.PairingRequested += (sender, args) =>
{
//Accept all attempts
args.Accept(); // <-- could enter a pin in here to accept
};
var result = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ConfirmOnly).AsTask();
//Get GATT services that are available
var gatt = await device.GetGattServicesAsync().AsTask();
GattDeviceService serviceReq = null;
GattCharacteristic characteristicReq = null;
//if we have any services..
if (gatt.Status == GattCommunicationStatus.Success)
{
//loop each gatt service
foreach (var service in gatt.Services)
{
if (service.Uuid == GattServiceUuids.HeartRate)
{
serviceReq = service;
}
//This ID contains the GATT profile assigned number we want!
//TODO: Get more info and connect
var gattProfileId = service.Uuid;
}
var charResults = await serviceReq.GetCharacteristicsAsync().AsTask();
if(charResults.Status == GattCommunicationStatus.Success)
{
foreach (var chars in charResults.Characteristics)
{
if(chars.Uuid == GattCharacteristicUuids.HeartRateMeasurement)
{
characteristicReq = chars;
}
}
GattCharacteristicProperties properties = characteristicReq.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
GattReadResult readVal = await characteristicReq.ReadValueAsync().AsTask();
if(readVal.Status == GattCommunicationStatus.Success)
{
var reader = DataReader.FromBuffer(readVal.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
HRValue = BitConverter.ToInt32(input, 0);
}
}
}
}
////Log the result
//if(result.Status == DevicePairingResultStatus.Paired)
//{
// Console.WriteLine("Pairing successful");
//}
//else
//{
// Console.WriteLine($"Pairing failed: {result.Status}");
//}
}
#endregion
}
}
And here is the code I am trying in Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if NETFX_CORE
using BLEHR
#endif
public class HRTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
#if NETFX_CORE
var watcher = new BLEAdvertisementWatcher(new GattServiceIDs());
Debug.Log("Working?");
#endif
}
// Update is called once per frame
void Update()
{
#if WINDOWS_UWP
Debug.Log("Connecting");
#endif
}
}
Debugging with UWP/.Net-Core-only features in Unity seems like an infeasible workflow to me because of the long edit-compile-run cycles. The Unity Editor runs with .Net-Framework and thus can't directly access .Net-Core features. For non-Unity projects there is the possibility to access UWP-API from .Net-Framework via wrappers provided by Windows. But that doesn't work for Unity because of some Unity-specifics1.
BUT there is the possibility to wrap the UWP-calls in a C++ winrt dll and copy the dll to Unity. This way the UWP-API can be also used inside the Unity Editor (e.g. when pushing the play button). My use case also requires BLE and I uploaded my wrapper in this repo. You're free to use it as a starting point if you want.
One last thing: With .Net version 5 which is also announced for Unity, I guess this should become obsolete as version 5 is said to merge .Net-Framework and .Net-Core.
[1] Much information for this answer came from this blog-post by Mike Taulty.
I get the following errormessage:
[SensorManager] sensor or listener is null.
I tried to debug the code and found out, that the sensor isn´t null! This class is not derived by the Activity class. Thank you for helping me :)
using Magic.Util;
using System;
using Android.Content;
using Android.Hardware;
using Magic.UI;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Android.OS;
namespace Magic
{
public class MiningMinigame : Scene, ISensorEventListener
{
private SensorManager mSensorManager = null;
Context _context = null;
//Random float value
Random random;
//Current mining Container Position
float xPositionMiningContainer;
//max & min value depends on the displaysize
float minValue;
float maxValue;
//device sizes
int deviceWidth;
int deviceHeight;
//UIElements
UIElement backgroundImage;
UIElement miningContainer;
public MiningMinigame (SceneManager sM, Context context)
: base(sM)
{
this._context = context;
deviceWidth = graphicsDevice.Viewport.Width;
deviceHeight = graphicsDevice.Viewport.Height;
SceneManager = sM;
InitializeBackgroundImage ();
InitializeMiningContainer ();
//mSensorManager = context.GetSystemService(Context.SensorService) as SensorManager;
AccelerometerStart ();
}
public void AccelerometerStart() {
mSensorManager = _context.GetSystemService(Context.SensorService) as SensorManager;
if (mSensorManager.GetDefaultSensor(SensorType.Accelerometer) != null){
Console.WriteLine ("Success! There's a Accelerator.");
}
else {
Console.WriteLine ("Failure! No Accelerator.");
}
if (mSensorManager != null)
{
Console.WriteLine ("mSensorManager is not null!");
Sensor sensor = mSensorManager.GetDefaultSensor(SensorType.Accelerometer);
mSensorManager.RegisterListener(this, sensor, SensorDelay.Ui);
}
else
{
throw new Exception("Could not load Accelerometer sensor");
}
}
public void AccelerometerCancel()
{
mSensorManager.UnregisterListener(this);
}
public void OnAccuracyChanged(Sensor sensor, SensorStatus sensorStatus)
{
}
public void OnSensorChanged(SensorEvent e)
{
Console.WriteLine (string.Format("x={0:f}, y={1:f}, y={2:f}", e.Values[0], e.Values[1], e.Values[2]));
}
/// <summary>
/// Initializes the background image.
/// </summary>
public void InitializeBackgroundImage()
{
Console.WriteLine("Welcome in the MiningMiniGame Scene");
//Sets the backgroundimage of the Scene
backgroundImage = new UIElement(this, new Rectangle(0, 0, deviceWidth, deviceHeight));
backgroundImage.SetBackgroundTexture(Resources.Content.Load<Texture2D>("Images/UI/Backgrounds/main_background"));
AddUIElement(backgroundImage);
}
/// <summary>
/// Initializes the mining container, where you collect the downfalling stuff.
/// </summary>
/// <returns>The mining container.</returns>
public void InitializeMiningContainer()
{
miningContainer = new UIElement (this, new Rectangle ((int)(deviceWidth * 0.375), (int)(deviceHeight * 0.8), (int)(deviceWidth * 0.25), (int)(deviceHeight * 0.2)));
miningContainer.SetBackgroundTexture (Resources.Content.Load<Texture2D> ("Images/UI/Buttons/mine"));
miningContainer.SetID ("MiningContainer");
// miningContainer.SetOnClickMethod (delegate()
// {
//
// });
AddUIElement (miningContainer);
}
/// <summary>
/// Updates the x-position from the mining container.
/// </summary>
public void UpdatePositionMiningContainer(float xPosition) {
miningContainer.Position.X = xPosition;
}
/// <summary>
/// Update the scene using the specified gameTime.
/// </summary>
/// <param name="gameTime">Game time.</param>
public override void Update (Microsoft.Xna.Framework.GameTime gameTime)
{
base.Update (gameTime);
HandleBackButton();
}
/// <summary>
/// Draw the scene using the specified gameTime.
/// </summary>
/// <param name="gameTime">Game time.</param>
public override void Draw (Microsoft.Xna.Framework.GameTime gameTime)
{
graphicsDevice.Clear (Color.White);
base.Draw (gameTime);
}
/// <summary>
/// Handles the back button.
/// </summary>
private void HandleBackButton()
{
if(GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed){
Console.WriteLine("HardwareBackButton in MiniGame was clicked!");
SceneManager.SwitchToOldScene();
}
}
/// <summary>
/// Creates the random X position.
/// </summary>
/// <returns>The random X position.</returns>
public float createRandomXPosition()
{
minValue = 0;
maxValue = graphicsDevice.Viewport.Width;
return ((float)random.NextDouble ()) * (maxValue - minValue) + minValue;
}
public IntPtr Handle
{
get;
}
/// <summary>
/// Releases all resource used by the <see cref="Magic.MiningMinigame"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Magic.MiningMinigame"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="Magic.MiningMinigame"/> in an unusable state. After calling
/// <see cref="Dispose"/>, you must release all references to the <see cref="Magic.MiningMinigame"/> so the garbage
/// collector can reclaim the memory that the <see cref="Magic.MiningMinigame"/> was occupying.</remarks>
public override void Dispose()
{
}
}
}
I have been trying to add a Write text file section to this project but i keep getting told that lots of things 'dont exist in the current context'.
The text tile is meant to be created my documents showing 'First line,new line 1, new line 2'
This should work alongside the kinect sample.
I am sorry that i am very new to this and may be doing it completely wrong.
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.HDFaceBasics
{
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using Microsoft.Kinect;
using Microsoft.Kinect.Face;
using System.IO;
/// <summary>
/// Main Window
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged, IDisposable
{
// Create a string array with the lines of text
string text = "First line" + Environment.NewLine;
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(mydocpath + #"\WriteFile.txt", text);
// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };
// Append new lines of text to the file
File.AppendAllLines(mydocpath + #"\WriteFile.txt", lines);
/// <summary>
/// Currently used KinectSensor
/// </summary>
private KinectSensor sensor = null;
/// <summary>
/// Body frame source to get a BodyFrameReader
/// </summary>
private BodyFrameSource bodySource = null;
/// <summary>
/// Body frame reader to get body frames
/// </summary>
private BodyFrameReader bodyReader = null;
/// <summary>
/// HighDefinitionFaceFrameSource to get a reader and a builder from.
/// Also to set the currently tracked user id to get High Definition Face Frames of
/// </summary>
private HighDefinitionFaceFrameSource highDefinitionFaceFrameSource = null;
/// <summary>
/// HighDefinitionFaceFrameReader to read HighDefinitionFaceFrame to get FaceAlignment
/// </summary>
private HighDefinitionFaceFrameReader highDefinitionFaceFrameReader = null;
/// <summary>
/// FaceAlignment is the result of tracking a face, it has face animations location and orientation
/// </summary>
private FaceAlignment currentFaceAlignment = null;
/// <summary>
/// FaceModel is a result of capturing a face
/// </summary>
private FaceModel currentFaceModel = null;
/// <summary>
/// FaceModelBuilder is used to produce a FaceModel
/// </summary>
private FaceModelBuilder faceModelBuilder = null;
/// <summary>
/// The currently tracked body
/// </summary>
private Body currentTrackedBody = null;
/// <summary>
/// The currently tracked body
/// </summary>
private ulong currentTrackingId = 0;
/// <summary>
/// Gets or sets the current tracked user id
/// </summary>
private string currentBuilderStatus = string.Empty;
/// <summary>
/// Gets or sets the current status text to display
/// </summary>
private string statusText = "Ready To Start Capture";
/// <summary>
/// Initializes a new instance of the MainWindow class.
/// </summary>
public MainWindow()
{
this.InitializeComponent();
this.DataContext = this;
}
/// <summary>
/// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets the current status text to display
/// </summary>
public string StatusText
{
get
{
return this.statusText;
}
set
{
if (this.statusText != value)
{
this.statusText = value;
// notify any bound elements that the text has changed
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
}
}
}
}
/// <summary>
/// Gets or sets the current tracked user id
/// </summary>
private ulong CurrentTrackingId
{
get
{
return this.currentTrackingId;
}
set
{
this.currentTrackingId = value;
this.StatusText = this.MakeStatusText();
}
}
/// <summary>
/// Gets or sets the current Face Builder instructions to user
/// </summary>
private string CurrentBuilderStatus
{
get
{
return this.currentBuilderStatus;
}
set
{
this.currentBuilderStatus = value;
this.StatusText = this.MakeStatusText();
}
}
/// <summary>
/// Called when disposed of
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose based on whether or not managed or native resources should be freed
/// </summary>
/// <param name="disposing">Set to true to free both native and managed resources, false otherwise</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.currentFaceModel != null)
{
this.currentFaceModel.Dispose();
this.currentFaceModel = null;
}
}
}
/// <summary>
/// Returns the length of a vector from origin
/// </summary>
/// <param name="point">Point in space to find it's distance from origin</param>
/// <returns>Distance from origin</returns>
private static double VectorLength(CameraSpacePoint point)
{
var result = Math.Pow(point.X, 2) + Math.Pow(point.Y, 2) + Math.Pow(point.Z, 2);
result = Math.Sqrt(result);
return result;
}
/// <summary>
/// Finds the closest body from the sensor if any
/// </summary>
/// <param name="bodyFrame">A body frame</param>
/// <returns>Closest body, null of none</returns>
private static Body FindClosestBody(BodyFrame bodyFrame)
{
Body result = null;
double closestBodyDistance = double.MaxValue;
Body[] bodies = new Body[bodyFrame.BodyCount];
bodyFrame.GetAndRefreshBodyData(bodies);
foreach (var body in bodies)
{
if (body.IsTracked)
{
var currentLocation = body.Joints[JointType.SpineBase].Position;
var currentDistance = VectorLength(currentLocation);
if (result == null || currentDistance < closestBodyDistance)
{
result = body;
closestBodyDistance = currentDistance;
}
}
}
return result;
}
/// <summary>
/// Find if there is a body tracked with the given trackingId
/// </summary>
/// <param name="bodyFrame">A body frame</param>
/// <param name="trackingId">The tracking Id</param>
/// <returns>The body object, null of none</returns>
private static Body FindBodyWithTrackingId(BodyFrame bodyFrame, ulong trackingId)
{
Body result = null;
Body[] bodies = new Body[bodyFrame.BodyCount];
bodyFrame.GetAndRefreshBodyData(bodies);
foreach (var body in bodies)
{
if (body.IsTracked)
{
if (body.TrackingId == trackingId)
{
result = body;
break;
}
}
}
return result;
}
/// <summary>
/// Gets the current collection status
/// </summary>
/// <param name="status">Status value</param>
/// <returns>Status value as text</returns>
private static string GetCollectionStatusText(FaceModelBuilderCollectionStatus status)
{
string res = string.Empty;
if ((status & FaceModelBuilderCollectionStatus.FrontViewFramesNeeded) != 0)
{
res = "FrontViewFramesNeeded";
return res;
}
if ((status & FaceModelBuilderCollectionStatus.LeftViewsNeeded) != 0)
{
res = "LeftViewsNeeded";
return res;
}
if ((status & FaceModelBuilderCollectionStatus.RightViewsNeeded) != 0)
{
res = "RightViewsNeeded";
return res;
}
if ((status & FaceModelBuilderCollectionStatus.TiltedUpViewsNeeded) != 0)
{
res = "TiltedUpViewsNeeded";
return res;
}
if ((status & FaceModelBuilderCollectionStatus.Complete) != 0)
{
res = "Complete";
return res;
}
if ((status & FaceModelBuilderCollectionStatus.MoreFramesNeeded) != 0)
{
res = "TiltedUpViewsNeeded";
return res;
}
return res;
}
/// <summary>
/// Helper function to format a status message
/// </summary>
/// <returns>Status text</returns>
private string MakeStatusText()
{
string status = string.Format(System.Globalization.CultureInfo.CurrentCulture, "Builder Status: {0}, Current Tracking ID: {1}", this.CurrentBuilderStatus, this.CurrentTrackingId);
return status;
}
/// <summary>
/// Fires when Window is Loaded
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.InitializeHDFace();
}
/// <summary>
/// Initialize Kinect object
/// </summary>
private void InitializeHDFace()
{
this.CurrentBuilderStatus = "Ready To Start Capture";
this.sensor = KinectSensor.GetDefault();
this.bodySource = this.sensor.BodyFrameSource;
this.bodyReader = this.bodySource.OpenReader();
this.bodyReader.FrameArrived += this.BodyReader_FrameArrived;
this.highDefinitionFaceFrameSource = new HighDefinitionFaceFrameSource(this.sensor);
this.highDefinitionFaceFrameSource.TrackingIdLost += this.HdFaceSource_TrackingIdLost;
this.highDefinitionFaceFrameReader = this.highDefinitionFaceFrameSource.OpenReader();
this.highDefinitionFaceFrameReader.FrameArrived += this.HdFaceReader_FrameArrived;
this.currentFaceModel = new FaceModel();
this.currentFaceAlignment = new FaceAlignment();
this.InitializeMesh();
this.UpdateMesh();
this.sensor.Open();
}
/// <summary>
/// Initializes a 3D mesh to deform every frame
/// </summary>
private void InitializeMesh()
{
var vertices = this.currentFaceModel.CalculateVerticesForAlignment(this.currentFaceAlignment);
var triangleIndices = this.currentFaceModel.TriangleIndices;
var indices = new Int32Collection(triangleIndices.Count);
for (int i = 0; i < triangleIndices.Count; i += 3)
{
uint index01 = triangleIndices[i];
uint index02 = triangleIndices[i + 1];
uint index03 = triangleIndices[i + 2];
indices.Add((int)index03);
indices.Add((int)index02);
indices.Add((int)index01);
}
this.theGeometry.TriangleIndices = indices;
this.theGeometry.Normals = null;
this.theGeometry.Positions = new Point3DCollection();
this.theGeometry.TextureCoordinates = new PointCollection();
foreach (var vert in vertices)
{
this.theGeometry.Positions.Add(new Point3D(vert.X, vert.Y, -vert.Z));
this.theGeometry.TextureCoordinates.Add(new Point());
}
}
/// <summary>
/// Sends the new deformed mesh to be drawn
/// </summary>
private void UpdateMesh()
{
var vertices = this.currentFaceModel.CalculateVerticesForAlignment(this.currentFaceAlignment);
for (int i = 0; i < vertices.Count; i++)
{
var vert = vertices[i];
this.theGeometry.Positions[i] = new Point3D(vert.X, vert.Y, -vert.Z);
}
}
/// <summary>
/// Start a face capture on clicking the button
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void StartCapture_Button_Click(object sender, RoutedEventArgs e)
{
this.StartCapture();
}
/// <summary>
/// This event fires when a BodyFrame is ready for consumption
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void BodyReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
this.CheckOnBuilderStatus();
var frameReference = e.FrameReference;
using (var frame = frameReference.AcquireFrame())
{
if (frame == null)
{
// We might miss the chance to acquire the frame, it will be null if it's missed
return;
}
if (this.currentTrackedBody != null)
{
this.currentTrackedBody = FindBodyWithTrackingId(frame, this.CurrentTrackingId);
if (this.currentTrackedBody != null)
{
return;
}
}
Body selectedBody = FindClosestBody(frame);
if (selectedBody == null)
{
return;
}
this.currentTrackedBody = selectedBody;
this.CurrentTrackingId = selectedBody.TrackingId;
this.highDefinitionFaceFrameSource.TrackingId = this.CurrentTrackingId;
}
}
/// <summary>
/// This event is fired when a tracking is lost for a body tracked by HDFace Tracker
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void HdFaceSource_TrackingIdLost(object sender, TrackingIdLostEventArgs e)
{
var lostTrackingID = e.TrackingId;
if (this.CurrentTrackingId == lostTrackingID)
{
this.CurrentTrackingId = 0;
this.currentTrackedBody = null;
if (this.faceModelBuilder != null)
{
this.faceModelBuilder.Dispose();
this.faceModelBuilder = null;
}
this.highDefinitionFaceFrameSource.TrackingId = 0;
}
}
/// <summary>
/// This event is fired when a new HDFace frame is ready for consumption
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void HdFaceReader_FrameArrived(object sender, HighDefinitionFaceFrameArrivedEventArgs e)
{
using (var frame = e.FrameReference.AcquireFrame())
{
// We might miss the chance to acquire the frame; it will be null if it's missed.
// Also ignore this frame if face tracking failed.
if (frame == null || !frame.IsFaceTracked)
{
return;
}
frame.GetAndRefreshFaceAlignmentResult(this.currentFaceAlignment);
this.UpdateMesh();
}
}
/// <summary>
/// Start a face capture operation
/// </summary>
private void StartCapture()
{
this.StopFaceCapture();
this.faceModelBuilder = null;
this.faceModelBuilder = this.highDefinitionFaceFrameSource.OpenModelBuilder(FaceModelBuilderAttributes.None);
this.faceModelBuilder.BeginFaceDataCollection();
this.faceModelBuilder.CollectionCompleted += this.HdFaceBuilder_CollectionCompleted;
}
/// <summary>
/// Cancel the current face capture operation
/// </summary>
private void StopFaceCapture()
{
if (this.faceModelBuilder != null)
{
this.faceModelBuilder.Dispose();
this.faceModelBuilder = null;
}
}
/// <summary>
/// This event fires when the face capture operation is completed
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void HdFaceBuilder_CollectionCompleted(object sender, FaceModelBuilderCollectionCompletedEventArgs e)
{
var modelData = e.ModelData;
this.currentFaceModel = modelData.ProduceFaceModel();
this.faceModelBuilder.Dispose();
this.faceModelBuilder = null;
this.CurrentBuilderStatus = "Capture Complete";
}
/// <summary>
/// Check the face model builder status
/// </summary>
private void CheckOnBuilderStatus()
{
if (this.faceModelBuilder == null)
{
return;
}
string newStatus = string.Empty;
var captureStatus = this.faceModelBuilder.CaptureStatus;
newStatus += captureStatus.ToString();
var collectionStatus = this.faceModelBuilder.CollectionStatus;
newStatus += ", " + GetCollectionStatusText(collectionStatus);
this.CurrentBuilderStatus = newStatus;
}
}
}
create a method that you can call that will allow you to create as well as append to the file
private static void WriteAndOrAppendText(string path, string strText)
{
using (StreamWriter fileStream = new StreamWriter(path, true))
{
fileStream.WriteLine(strText);
fileStream.Flush();
fileStream.Close();
}
}
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the text to a new file named "WriteFile.txt".
WriteAndOrAppendText(mydocpath + #"\WriteFile.txt", text);
string[] lines = { "New line 1", "New line 2" };
WriteAndOrAppendText(mydocpath , string.Join(",", lines.ToArray()));
I'm in face on the following problem: An application developed on Microsoft Visual Studio 2013 in .NET 4.5, needs to work in Window XP Platforms. I'm rebuild the software using .NET 4.0 and make some modifications to add compatibility, but when i click in a button the app crash and don't show a clear error message and the Trace resource don't log anything. On application start i had a little window that ask user to put your name, and this feature works fine. Anybody have any suggestion of what can i do ?
EDIT 1:
The follow code is the root of problems, this code was compiled using .NET 4.0:
SerialManager.cs
using System;
using System.Windows;
using TestSat;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace TestSat.DataModel
{
/// <summary>
///
/// </summary>
public class SerialManager : INotifyPropertyChanged
{
#region Events
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
/* [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class CallerMemberNameAttribute : Attribute
{
}*/
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="value"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
#endregion
#region Private Fields
private static SerialPort PortaSerial;
private ObservableCollection<String> mPorts;
private String mSelectedPort;
private int mBaudRate = 115200;
private int mDataBits = 8;
#endregion
#region Public Fields
public StringBuilder logText;
#endregion
#region Properties
/// <summary>
///
/// </summary>
public ObservableCollection<String> COMPorts
{
get { return mPorts; }
set { SetField(ref mPorts, value); }
}
/// <summary>
///
/// </summary>
public String TextoLog
{
get { return logText.ToString(); }
set
{
if (logText.Length >= logText.MaxCapacity)
{
logText.Clear();;
logText.Append(value);
}
else
{
logText.Append(value);
//MainWindow.last = value;
}
OnPropertyChanged("TextoLog");
}
}
/// <summary>
///
/// </summary>
public String SelectedPort
{
get { return mSelectedPort; }
set {SetField(ref mSelectedPort, value); }
}
#endregion
#region Construtors
/// <summary>
///
/// </summary>
public SerialManager()
{
InitComponents();
}
/// <summary>
///
/// </summary>
private void InitComponents()
{
RefreshPorts();
/*Initialize the log variable*/
logText = new StringBuilder();
/* Update selected port */
SelectedPort = COMPorts.Count > 0 ? COMPorts[0] : "";
}
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
public void RefreshPorts()
{
// Update ports
string[] pPorts = SerialPort.GetPortNames();
// Sort alphabetically
Array.Sort(pPorts);
// Sort by string length
Array.Sort(pPorts, (x, y) => x.Length.CompareTo(y.Length));
// Create collection
COMPorts = new ObservableCollection<string>(pPorts);
}
/// <summary>
///
/// </summary>
/// <param name="mSelectedPort"></param>
public void ConnectSerial(String mSelectedPort)
{
PortaSerial = new SerialPort();
PortaSerial.PortName = mSelectedPort;
PortaSerial.BaudRate = mBaudRate;
PortaSerial.Parity = Parity.None;
PortaSerial.DataBits = mDataBits;
PortaSerial.StopBits = StopBits.One;
PortaSerial.Handshake = Handshake.None;
PortaSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Trace.WriteLine("DataReceived definida");
try
{
PortaSerial.Open();
}
catch (SystemException)
{
MessageBox.Show("A porta serial esta sendo usada em outra aplicação.", "Erro", MessageBoxButton.OK);
throw new SystemException();
}
}
/// <summary>
///
/// </summary>
public void DesconnectSerial()
{
if (PortaSerial.IsOpen)
{
PortaSerial.Close();
}
}
/// <summary>
///
/// </summary>
public void writeSerial(String text)
{
if (PortaSerial.IsOpen)
{
if (text.Length > 0)
{
/* char[] array = text.ToCharArray(0,text.Length);
foreach(char ch in array)
{
PortaSerial.Write(ch.ToString());
Thread.Sleep(50);
}*/
PortaSerial.WriteLine(text);
}
else
{
PortaSerial.WriteLine("");
}
}
else
{
MessageBox.Show("Porta serial não esta aberta.", "Erro", MessageBoxButton.OK);
Console.WriteLine("Porta serial não esta aberta");
}
}
/// <summary>
///
/// </summary>
public bool IsOpen()
{
return PortaSerial.IsOpen;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
MainWindow.StartRawData = true;
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
TextoLog = indata;
/*Omited code only logical operation*/
}
#endregion
}
}
If i don't do any instance or reference to serial port the applications don't crashes. Exist a way to force this part of code compiled by .NET 3.5? Or exist another suggestion of solution for this problem?
The solution i found at http://blogs.msdn.com/b/bclteam/p/asynctargetingpackkb.asp , Issue 8. Installing the .NET 4.0 update the problems don't occured anymore.