Code Monkey home page Code Monkey logo

xbee's People

Contributors

ajgriesemer avatar jefffhaynes avatar jtone123 avatar usmanqureshi19 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xbee's Issues

information request

I am interested in doing some c# applications using xbee series 1 chips. is there any way I can contact you for some help in using the XBee code.

Just checking in on the NuGet Package issue

Hi Jeff,

I was just wondering if you have had a chance to look into the issue where NuGet is adding all those extra packages to my project. It takes the disk footprint from ~300KB to ~300MB.

Thanks Paul.

I'm a beginner, please help

Hi, I just started with this library. I was running the Tester example using 2 S2C modules with ZigBee firmware. I found the first character of my serial message was always missing. Then I checked the addresses in dataFrame, it looks like the first byte (00) of high part of the 64-bit address is not taken and the first byte of the 16-bit address is added as the last byte of the 64-bit address. Similarly, probably the first character of the serial message is actually used for the field before data, i.e. Receive options? How should I fix this or did I do anything wrong? Thank you for your help.

private static void Main(string[] args)
{
MainAsync();
Console.ReadKey();
_xbee.Dispose();
}
private static async void MainAsync()
{
_xbee = new XBeeController("COM6", 9600);
await _xbee.OpenAsync("COM6", 9600);
_xbee.DataReceived += (sender, eventArgs) => Console.WriteLine("Received {0} bytes", eventArgs.Data.Length);
}

DataReceived event not working?

Hello,
First off, thanks for this awesome library.
I'm using it in a simple project I'm working on where I send serial data every 3 seconds from an end-point device to an API coordinator (mode 1). The frames show up in XCTU when monitoring the coordinator, but I can't get them to show up using this library. The DataReceived event seems to never trigger.

Am I doing something wrong or is this known?

namespace Gateway
{
    class Program
    {
        private static async void ConnectToCoordinator()
        {
            var controller = new XBeeController("COM3", 9600);

            controller.NodeDiscovered += async (sender, args) =>
            {
                Console.WriteLine("Discovered {0}", args.Name);

                var Node = args.Node;
                Node.DataReceived += (node, ev) => Console.WriteLine("Received: {0}", BitConverter.ToString(ev.Data));
            };

            try
            {
                await controller.OpenAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Succes!");

            await controller.DiscoverNetworkAsync();
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter to connect to Coordinator.");
            Console.ReadLine();

            ConnectToCoordinator();

            Console.ReadLine();
        }
    }
}

My thanks in advance!

Nuget packages

When i try to install with NuGet, I have to use an older XBee package since XBee.Core is 1.4.1 but latest XBee requires >= 1.4.3

System.TimeoutException: 'The operation has timed out.'

var controllers = await XBeeController.FindControllersAsync(9600); var controller = controllers.First(); var localNode = controller.Local; var serialNumber = await localNode.GetSerialNumberAsync();

Throws an exception on final line:
System.TimeoutException: 'The operation has timed out.'

It is a UWP app with XBee Nuget pakage version 5.3.3.
I have XBee S2C XB24CZ7WIT-004

How to add a Sleeping End Node to the Controller

Since Sleeping End Nodes won't show up during Network Discovery, I have to add them to the Controller manually. I didn't find any reference to this in the ReadMe file. After your last change to the Library, the way I was doing it stopped working. The Only way I was able to figure out, now, was to make a change to the Source Code, by making XBeeController.CreateNode Public. That allows me to add a Sleeping End Node after Network Discovery and also it's Event Handler.

await controller.DiscoverNetwork();

AddLog( "END network discovery" );

AddLog( "Adding Node End_Grove" );

endGrove = await Task.FromResult( controller.CreateNode( HardwareVersion.XBee24C, new NodeAddress( new LongAddress( ulong.Parse( "0013A20040F7829A", System.Globalization.NumberStyles.HexNumber ) ), new ShortAddress( ushort.Parse( "0A90", System.Globalization.NumberStyles.HexNumber ) ) ) ) );

endGrove.SampleReceived += ( node, sample ) => AddLog( cntr1++.ToString() + " " + DateTime.Now.ToShortTimeString() + " End_Grove Sample: " + sample.DigitalSampleState.ToString() );

AddLog( "End_Grove Added to controller" );

Is there a way to do this that I didn't find?

ForceSample() does not cause SampleReceived event to fire

Is there a way to get the state of the digital input pins on startup? I tried manually setting IR to 1, to 100, changing the value of IC, but nothing works. node.ForceSamples() does not seem to have any effect.

What should I set up for periodic sampling? Sorry, I guess this inadvertently became two questions.

After NuGet update, XBeeNode.SampleReceived handler doesn't get called

Hi Jeff,

I just used NuGet to update my project and my handlers for XBeeNode.SampleReceived are not getting called. Note: Controller.SampleReceived still works.

I was using VS2015 Community, so I installed VS2017 Community and restored my project from backup. Ran my original code in VS2017 and it still works. Then, from VS2017, I used NuGet to update my project again. Same problem. I was hoping you could look at the following and give me an idea of what is wrong.


My original code that works:

package id="BinarySerializer" version="6.0.3" targetFramework="net452"
package id="XBee" version="4.2-beta" targetFramework="net452"

// .Net 4.5.2
controller = new XBeeController( port, 115200 );
await controller.OpenAsync();

controller.SampleReceived += Controller_SampleReceived;

private void Controller_SampleReceived( object sender, SourcedSampleReceivedEventArgs e ) {
}

xBeeNode.SampleReceived += DayNightDetector_SampleReceived;

private void DayNightDetector_SampleReceived( object sender, SampleReceivedEventArgs e ) {
}


Updated from NuGet

package id="BinarySerializer" version="7.5.6" targetFramework="net461"
package id="XBee" version="5.3.3" targetFramework="net461"
package id="XBee.Core" version="1.4.4" targetFramework="net461"

// .Net 4.6.1
controller = new XBeeController();
await controller.OpenAsync( port, 115200 );

controller.SampleReceived += Controller_SampleReceived;

**** This handler still gets called
private void Controller_SampleReceived( object sender, SourcedSampleReceivedEventArgs e ) {
}

xBeeNode.SampleReceived += DayNightDetector_SampleReceived;

****** This handler never gets called now
private void DayNightDetector_SampleReceived( object sender, SampleReceivedEventArgs e ) {
}

I'm lost. Hope you can show me the path.
Thanks, Paul

cannot build the project...

Hi, I'm using vs 2015 and can't build the project. the error is unable to locate nuget.exe....

btw, is this api compatible with xbee xtend?

Is DigitalSampleState really the Digital Channel Mask?

When looking at the information returned by DigitalSampleState, I came to the conclusion that it is the Digital Channel Mask. Is this correct? If so, I need the to access the Digital Sample to know which pins are High or Low. I could not find a way to do this. If I'm on the wrong track please ignore the rest of this.

I looked at the XBee manual. Here goes...

Frame Type: 0x92 ZigBee IO Data Sample Rx Indicator

Offset 16,17 Digital Channel Mask
This is what I'm seeing returned by DigitalSampleState. I believe this, because it is a list of every pin on my node that is configured for digital input or output. This is not much use to me, because I already know which pin does what and it does not tell me which pin is an input or output, just that it is digital. I have never seen how to ask an XBee which pin is an input or output (maybe there is a way) and I have never had a reason to. I'm guessing this mask is a good way to test if a coding error is trying to read or write a non digital pin. I wonder how this would be useful to stop code from writing to an input pin?

Offset 19,20 Digital Samples
This is what I need to get at. The state of all configured digital pins.
I'm thinking this, about (SampleReceivedEventArgs sample)

Change: SampleReceivedEventArgs.DigitalSampleState

To: SampleReceivedEventArgs.DigitalSampleMask

Add: SampleReceivedEventArgs.DigitalSampleData

Be able to code things like: if ( sample.DigitalSampleData.DIO7 == false )
Actually: if ( !sample.DigitalSampleData.DIO7 )

What do you think?

Back Story:
The fact that the sample contains not just the state of input pins but also output pins turned out to be really useful to me. Here is why: By convention, I setup all my nodes with DIO7 high and to transmit a sample to the controller every 10 seconds. When a node shows up for the first time or if it has been Power Cycled, DIO7 will be High and my software knows that this node is out of sync with what my software thinks it is currently doing and can reconfigure it. Part of reconfiguration, is to set DIO7 Low and automatic sampling to every 60 seconds. I do not commit these changes. Every incoming sample my software sets a flag that the node has Phoned Home. Every 3 minutes I check the flags and reset them. If a flag isn't set, I know that the node has a problem requiring manual intervention. I also had a Solar Powered Motion Detector stolen and within 3 minutes it showed up as MIA. Never got it back. The other thing that my use of DIO7 is great for, is something like my Flood Light with Motion Detector. If DIO7 is High it acts like a regular motion detector light. When I set DIO7 Low the motion detector sends signals to my software and my software controls the light. I can make it flash from motion. I can turn it on when I need light at night and I don't want to keep moving to trigger the motion detector, etc...
Anyway, I have found that getting Input and output state in the sample is very useful.

Input5 included in input mask even though it is set as an output.

Title says it all. I have all I/O disabled except for input 0 as a digital input, and DIO5 as a Digital Output(low). Pullup is set for all I/O pins. However Input5 comes back very often (but not always) in the input mask when I deassert DIO0. Interestingly, it isn't included when I release my button to let input 0 go high.

Feature Request: Extend Input/Output Configuration and Change Detection for S2C

Hi Jeff,

I extended the input/output Configuration and Change Detection so it would cover DIO0 thru DIO14 on the S2C Version of the XBees. I was hoping you would consider modifying the library. The following includes the files I modified and the changes I made. I tested everything through DIO14 and it works. My tests included setting the pins low, high, and as an input with change detection. I don't know if this is the right way to do this because I made it work for just my flavor of S2C Xbees. Also I noticed that several of the ResponseData Methods need to support all the versions of XBees. I modified just InputOutputChangeDetectionResponseData to support just my flavor of XBee.

Here is what I did:

CHANGE DETECTION

// ADDED TO: InputOutputChangeDetectionResponseData.cs
// Needed to support my S2C version
[FieldOrder( 1 )]
[SerializeWhen( "ControllerHardwareVersion", HardwareVersion.XBeePro900, RelativeSourceMode = RelativeSourceMode.SerializationContext )]
[SerializeWhen( "ControllerHardwareVersion", HardwareVersion.XBeePro900HP, RelativeSourceMode = RelativeSourceMode.SerializationContext )]
[SerializeWhen( "ControllerHardwareVersion", HardwareVersion.XBee24C, RelativeSourceMode = RelativeSourceMode.SerializationContext )]
public DigitalSampleChannels? ChannelsExt { get; set; }



// MODIFIED: InputOutputChangeDetectionCommand.cs
// Needs to set 16 bit value
public class InputOutputChangeDetectionCommand : AtCommand {

    [Ignore]
    public DigitalSampleChannels? Channels {
        get { return Parameter as DigitalSampleChannels?; }
        set { Parameter = Convert.ToUInt16( value ); }
        //set { Parameter = Convert.ToByte(value); }
    }

//-----------------------------------------

INPUT OUTPUT CONFIGURATION

// MODIFIED: InputOutputConfigurationCommand.cs
// Above D9 starts with P0.  Cool, I learned I could include a conditional in a call to the base constructor!
public class InputOutputConfigurationCommand : AtCommand {

    public InputOutputConfigurationCommand( InputOutputChannel channel ) :
         base( (int)channel > 9 ? $"P{(int)channel - 10}" : $"D{(int)channel}" ) {
    }




// ADDED TO: InputOutputChannel.cs
// It stopped at Channel 9
public enum InputOutputChannel {
    Channel0 = 0,
    Channel1 = 1,
    Channel2 = 2,
    Channel3 = 3,
    Channel4 = 4,
    Channel5 = 5,
    Channel6 = 6,
    Channel7 = 7,
    Channel8 = 8,
    Channel9 = 9,
    Channel10 = 10,
    Channel11 = 11,
    Channel12 = 12,
    Channel13 = 13,
    Channel14 = 14
}




// ADDED TO: DigitalSampleState.cs
public enum DigitalSampleState : ushort {
    None = 0x0,
    Input0 = 0x1,
    Input1 = 0x2,
    Input2 = 0x4,
    Input3 = 0x8,
    Input4 = 0x10,
    Input5 = 0x20,
    Input6 = 0x40,
    Input7 = 0x80,
    Input8 = 0x100,
    Input9 = 0x200,
    Input10 = 0x400,
    Input11 = 0x800,
    Input12 = 0x1000,
    Input13 = 0x2000,
    Input14 = 0x4000,

    All = Input0 | Input1 | Input2 | Input3 | Input4 | Input5
            | Input6 | Input7 | Input8 | Input9 | Input10 | Input11 | Input12 | Input13 | Input14
}




// ADDED TO: DigitalSampleChannels.cs
public enum DigitalSampleChannels : ushort {
    None = 0x0,
    Input0 = 0x1,
    Input1 = 0x2,
    Input2 = 0x4,
    Input3 = 0x8,
    Input4 = 0x10,
    Input5 = 0x20,
    Input6 = 0x40,
    Input7 = 0x80,
    Input8 = 0x100,
    Input9 = 0x200,
    Input10 = 0x400,
    Input11 = 0x800,
    Input12 = 0x1000,
    Input13 = 0x2000,
    Input14 = 0x4000
}




// ADDED TO: RxIndicatorSampleExtFrame.cs
[SerializeWhen( "DigitalChannels", DigitalSampleChannels.Input13,
     ConverterType = typeof( BitwiseAndConverter ), ConverterParameter = DigitalSampleChannels.Input13 )]
[SerializeWhen( "DigitalChannels", DigitalSampleChannels.Input14,
     ConverterType = typeof( BitwiseAndConverter ), ConverterParameter = DigitalSampleChannels.Input14 )]

Like I said, this works for me, but, I don't know the big picture of what you are doing.

PS. I was testing on a router. I never tested committing a change to DIO13 or DIO14 and putting it back in the programmer board. I assume it wouldn't work because DIO13 & 14 are also the serial data pins.

DigitalSampleState is always None

This is my main issue at this time. Samples are coming in from my router and End Devices. However, the DigitalSampleState is always None. I can send commands to my router to control output pins ( It's a Flood Light) and the light turns on and off. It also has a motion detector when the Motion detector is triggered the Controller gets a Sample. However the DigitalSampleState is None. Because I have a new S2C XBee installed in the Flood Light I wanted to make sure it worked in my active network. So, I moved the Router from my test network to my active network ( where it came from originally ) by changing it's PAN ID and API Mode from 1 to 2. It works fine. The GBee Library on the Netduino picks up Pin State and reports motion. I moved it back to my test network, and Downloaded the source code to your BinarySerializer Library, so I could step through it with the Debugger and try to figure out why the DigitalSampleState wasn't getting decoded.

WOW ! What an elegant piece of software! Way beyond my skill level. I bet you graduated top of your class from MIT.

Anyway I attempted to keep up with what it was doing. However, at the part where it checks the DigitalSampleState, I could not figure out why it was deciding that there was None.

I'm stumped. Any help would be greatly appreciated.

Please help...

Hi Jeff, Thanks for this lib, i am planning to use this for for my project. I am familiar with xbee/zigbee and how this work. I have a mesh network where i use only api frame packet to send to node/end device to coordinator or vise-versa. I can successfully receive data by this below:

private static async void Run()
        {
            _xbee = await XBeeController.FindAndOpenAsync(SerialPort.GetPortNames(), 115200);

            _xbee.DataReceived += _controller_DataReceived;
            //await node.TransmitDataAsync(Encoding.UTF8.GetBytes("hi here is some data"));
            //await node.TransmitDataAsync(Encoding.UTF8.GetBytes("Hello!"));
        }

        private static void _controller_DataReceived(object sender, SourcedDataReceivedEventArgs e)
        {
            Console.WriteLine("CReceived: {0}", ((e.Address).LongAddress));
            Console.WriteLine("recevied from: " + sender.ToString());
            Console.WriteLine("Data Received: {0}", Encoding.UTF8.GetString(e.Data));
            
        }

But struggling to simply send a packet, I was just wondering if you can show me what would be the best practice to get:

Type of received data frame?
send frame using different packet frame, such as 0x10, 0x11 with Long address or broadcast?

Thanks for your help, and keep up the good work.

update:
forget to mention the coordinator is ZigBeeS2.

Now i am able to send and receive the package using of your example as below. I wasn't able at the start because of router(A0=1) was configured as Explicit mode. when i use "TransmitDataAsync", data was ignored by router (as received data was no Explicit addressing command mode (0x11)). after change back to A0=0, received raw data as below:

{'options': b'\x01', 'id': 'rx', 'source_addr_long': b'\x00\x13\xa2\x00@\xaf\xb7_', 'source_addr': b'\x00\x00', 'rf_data': b'hi here is some data'}

private static async void _xbee_Run(string whatToSend, ulong xbeeAddress)
        { _xbee = new XBeeController();
            var _xbee = await XBeeController.FindAndOpenAsync(SerialPort.GetPortNames(), 115200);
            if (_xbee != null)
            {
                var node = await _xbee.GetRemoteNodeAsync(new NodeAddress(new LongAddress(xbeeAddress)));
                await node.TransmitDataAsync(Encoding.UTF8.GetBytes(whatToSend), true);
                _xbee.DataReceived += _xbee_DataReceived;
                 node.DataReceived += Node_DataReceived;
             )
            else{ ................. }

Sorry for the noob question, if i receive a new packet by _xbee.Datareceive, i want to send some Data to another Xbeenode. how can i handle this? how can i get a new instance of _xbee.GetRemoteNodeAsync? Thanks for your help!

[FieldLength] for null string

It seems that the reserved field length for a string is ignored if the string is null. If the string is empty, it works fine.

[FieldLength(50)]
[SerializeAs(Encoding = "ASCII")]
public string Data { get; set; }

How to find node identifiers of end devices?

Hello Jeff,
Thank you for your help for the last issue. I'm running into a new problem now. I try to get the node identifiers of nodes in the network. I'm following your example but I see nothing but this error

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: 45 not supported.

Can you help me with this? Thanks.

This's the code I'm using:

private static void Main(string[] args)
{
MainAsync();
Console.ReadKey();
_xbee.Dispose();
}
private static async void MainAsync()
{
_xbee = new XBeeController("COM22", 9600);
await _xbee.OpenAsync("COM22", 9600);
Console.WriteLine("Discovering network...");
_xbee.NodeDiscovered += (sender, args) =>
{
Console.WriteLine("Discovered {0}", args.Name);
};
await _xbee.DiscoverNetworkAsync();
}

New to XBee and Added Supply Voltage measurement.

I'm just getting into your API, and I like it. I've got a need to ask the modules for Supply Voltage (%V command) so I added it. Perhaps you'd like to roll it into the main API.

to XBeeNode.cs:

        /// <summary>
        ///     Gets the Supply Voltage in mV
        /// </summary>
        /// <returns></returns>
        public async Task<ushort> GetSupplyVoltageAsync()
        {
            var response = await ExecuteAtQueryAsync<PrimitiveResponseData<ushort>>(new SupplyVoltageCommand()).ConfigureAwait(false);
            return response.Value;
        }

to AtCommandResponseFrameContent.cs:

        [Subtype(nameof(AtCommand), SupplyVoltageCommand.Name, typeof(PrimitiveResponseData<ushort>), BindingMode = BindingMode.OneWay)]

New file SupplyVoltageCommand.cs

namespace XBee.Frames.AtCommands
{
    internal class SupplyVoltageCommand : AtCommand
    {
        public const string Name = "%V";

        public SupplyVoltageCommand() : base(Name)
        {
        }
    }
}

XBeeNode.SampleReceived Handler not called. Continued

Hope you don't mind, I wanted to start a fresh Issue, because the other one had gotten to lengthy.

Anyway, my way of initializing the XBeeNode.SampleReceived handler still doesn't work. However, I made a test, adapting your DiscoverNetwork example and it works.

I did find 2 Issues:

#1) args.Name is missing the first character of the Name for all nodes found.

#2) DiscoverNetworkAsync does not discover Sleeping Nodes, which is to be expected because they are asleep. That is why I developed a reactive system that adds nodes when they send a sample for the first time.

Now I'm back to my original problem. I remember you said you tried my code on your machine and it worked. I am lost at this point. You just suggested that it might be a difference in the way we are creating nodes, but you ran my code on your system and it was calling the Node_SampleReceived Handler.

Anyway, I have made something that does work, and it is always good to know that everything can work. However, it won't work for what I need, because of the sleeping nodes. Any suggestions would be greatly appreciated.
Thanks, Paul.


THIS CODE WORKS to call the Node_SampleReceived Handler

using System;
using System.Windows;
using XBee;

namespace WpfApp2 {
///


/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window {
private XBeeController controller = null;

	public MainWindow() {
		InitializeComponent();
		controller = new XBeeController();

		controller.NodeDiscovered += NodeDiscovered;

		Await_DiscoverController();
	}

	//----------------------------------------------------------

	private async void Await_DiscoverController() {
		try {
			await controller.OpenAsync( "COM3", 115200 );
			// NOTE: DiscoverNetworkAsync does not discover Sleeping Nodes  < < < < < < < < < < < <
			await controller.DiscoverNetworkAsync();
		}
		catch ( Exception e ) {
			string s = e.Message;
		}
	}

	//----------------------------------------------------------

	private void NodeDiscovered( object sender, NodeDiscoveredEventArgs args ) {
	// NOTE: args.Name is missing the first character of the Name for all nodes found  < < < < < < < < < < < <
	string s = args.Name;
		if ( args.Node.Address.LongAddress.Value == 0x0013A20040F4F731 ) {
			args.Node.SampleReceived += Node_SampleReceived;
		}
	}

	//---------------------------------------------------------------------------

	private int _sampleReceived_Cntr = 0;
	private void Node_SampleReceived( object sender, SampleReceivedEventArgs e ) {
		_sampleReceived_Cntr++;
	}



}

}

Very Happy, not an issue

Hi Jeff,
I had a chance this morning to try NuGet. Installed all recommended updates and ran my application. It runs perfect.
Thank you,
Paul Noto

NuGet Package Issue Continued

Hi Jeff,
The old issue was getting a little long. I hope you don't mind that I started a new one.

Anyway, in response to your last question, I didn't do anything extra. All I do is create a new WPF Desktop App, Hit F5 to make sure it works, then I go to NuGet and add BinarySerializer, that's when it tries to add all the extra packages.

I just updated my Win7 and Win10 machines to VS 15.7.3 and .Net 4.7.2. I still have the same issue with a new WPF App.

So, if it works for you, I'm thinking that there is something that BinarySerializer is depending on, that is not installed on my win7 and win10 machines.

The first dependency for BinarySerializer is .NETStandard,Version=v1.3. I can see in Programs and Features that I have several .Net Core SDKs installed, the latest is v2.1.201 I cant find that .NetStandard is installed on either machine. Is it magically included with VS or is do I need to download it from somewhere?

Could this be the issue?

Examples

Hello,

I want to thank you for letting us use this cool lib, i am however not the best c# programmer and it is not really apparent how to use the ExecuteQueryAsync to send data. currently i keep getting timeout exceptions on the thread.

i was wondering could you make a simple ample on how to send data?

Node_SampleReceived still not being called

Hi Jeff,

I just tried 1.5.4 and it works for your proactive DiscoverNetworkAsync() to call Node_SampleReceived() on a Router. However, naturally , it will not find sleeping nodes.

I tried it on my reactive code that does find all nodes even if they are sleeping. However, it will not call Node_SampleReceived() on the same router that works above. I'm including the code that works, the code that doesn't work, and the packages that NuGet added for the code that doesn't work.

I can't thank you enough for all the effort your putting into this.

This code works and calls Node_SampleReceived() <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

using System;
using System.Windows;
using XBee;

namespace WpfApp2 {
///


/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window {
private XBeeController controller = null;

	public MainWindow() {
		InitializeComponent();
		controller = new XBeeController();

		controller.NodeDiscovered += NodeDiscovered;

		Await_DiscoverController();
	}

	//----------------------------------------------------------

	private async void Await_DiscoverController() {
		try {
			await controller.OpenAsync( "COM3", 115200 );
			// NOTE: DiscoverNetworkAsync does not discover Sleeping Nodes  < < < < < < < < < < < <
			await controller.DiscoverNetworkAsync();
		}
		catch ( Exception e ) {
			string s = e.Message;
		}
	}

	//----------------------------------------------------------

	private void NodeDiscovered( object sender, NodeDiscoveredEventArgs args ) {
	string s = args.Name;
		if ( args.Node.Address.LongAddress.Value == 0x0013A20040F4F731 ) {
			args.Node.SampleReceived += Node_SampleReceived;
		}
	}

	//---------------------------------------------------------------------------

	private int _sampleReceived_Cntr = 0;
	private void Node_SampleReceived( object sender, SampleReceivedEventArgs e ) {
		_sampleReceived_Cntr++;
	}

}

}

This code DOES NOT CALL Node_SampleReceived() <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

using System;
using System.IO.Ports;
using System.Threading.Tasks;
using System.Windows;
using XBee;

namespace WpfApp3 {
///


/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window {
private XBeeController controller = null;
private XBeeNode _xBeeNode = null;

	public MainWindow() {
		InitializeComponent();
		Await_DiscoverController();
	}


	private async void Await_DiscoverController() {
		await DiscoverController();
	}

	//---------------------------------------------------------------------------

	private async Task DiscoverController() {

		// NOTE: Sometimes the controller will take several tries before it is discovered

		var ports = SerialPort.GetPortNames();
		if ( ports.Length == 0 ) {
			//historyLog.Add( new HistoryLog_Item( false, "Can't find XBee Controller on any USB Serial Port", HistoryLog_Item_Types.error ) );
			return;
		}
		//historyLog.Add( new HistoryLog_Item( false, "Initializing XBee Controller", HistoryLog_Item_Types.info ) );
		//historyLog.Add( new HistoryLog_Item( false, string.Format( "Checking serial ports: {0}", string.Join( ", ", ports ) ), HistoryLog_Item_Types.info ) );

		int pass = 1;
		do {
			foreach ( var port in ports ) {
				try {
					controller = new XBeeController();
					await controller.OpenAsync( port, 115200 );
					//historyLog.Add( new HistoryLog_Item( false, string.Format( "Opened {0}", port ), HistoryLog_Item_Types.info ) );
					controller.SampleReceived += Controller_SampleReceived;
					pass = 0; // Finished initializing controller
				}
				catch ( Exception e ) {
					controller?.Dispose();
					controller = null;
					//historyLog.Add( new HistoryLog_Item( false, string.Format( "Pass {0}: Failed to open {1} with {2}", pass, port, e.Message ), HistoryLog_Item_Types.error ) );
					pass++;
				}
				if ( pass >= 30 ) {
					//historyLog.Add( new HistoryLog_Item( false, string.Format( "Can't initialize XBee Controller on USB Serial Port {0}", port ), HistoryLog_Item_Types.error ) );
					return;
				}
			}
		} while ( pass != 0 );

		//historyLog.Add( new HistoryLog_Item( false, "Finished Initializing XBee Controller", HistoryLog_Item_Types.info ) );
	}

	//---------------------------------------------------------------------------

	public async void GetXBeeAsync( string hexAddressString ) {
		try {
			// I think somehow this is the problem.
			_xBeeNode = await controller.GetNodeAsync( new NodeAddress( new LongAddress( ulong.Parse( hexAddressString, System.Globalization.NumberStyles.HexNumber ) ) ) );
		}
		catch {
			return;
		}
	}

	//---------------------------------------------------------------------------

	ulong _test_XBeeNodeAddress_ULong = 5526146530998065;
	string _test_XBeeNodeAddress_HexString = "13A20040F4F731";
	bool _sampleHandlerSet = false;
	/// <summary>
	/// This is the incomming Method of the Controller XBee, every incomming communication hits this before the data is sent to the actual XBee Node object (if one exists).
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void Controller_SampleReceived( object sender, SourcedSampleReceivedEventArgs e ) {
		ulong nodeAddressULong = e.Address.LongAddress.Value;

		if ( nodeAddressULong == _test_XBeeNodeAddress_ULong ) {

			// Pass #1 Create Node
			if ( _xBeeNode == null ) {
				GetXBeeAsync( _test_XBeeNodeAddress_HexString );
				return;
			}
			// Pass #2 Set Handler
			if ( !_sampleHandlerSet ) {
				_xBeeNode.SampleReceived += Node_SampleReceived;
				_sampleHandlerSet = true;
				return;
			} else {
				// Pass #3 For some reason the debugger won't show me the method, the Node's SampleReceived handler is set to, when I inspect the node on the third pass
				// Pass #4 or more will let me inspect what method the Node's SampleReceived handler is set to. WEIRD! 
				XBeeNode node = _xBeeNode;
				return; // Set Break Point Here to inspect fully initialized Node
			}
		}
	}// END Controller_SampleReceived()

	//---------------------------------------------------------------------------
	private int _sampleReceived_Cntr = 0;
	private void Node_SampleReceived( object sender, SampleReceivedEventArgs e ) {
		_sampleReceived_Cntr++; // This Break Point never happens
	}

}

}

These are the packages that NuGet added <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

package id="BinarySerializer" version="7.5.7" targetFramework="net47" />
package id="Microsoft.NETCore.Platforms" version="2.0.0" targetFramework="net47" />
package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="net47" />
package id="NETStandard.Library" version="2.0.0" targetFramework="net47" />
package id="System.AppContext" version="4.3.0" targetFramework="net47" />
package id="System.Collections" version="4.3.0" targetFramework="net47" />
package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net47" />
package id="System.Console" version="4.3.0" targetFramework="net47" />
package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net47" />
package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net47" />
package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net47" />
package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net47" />
package id="System.Globalization" version="4.3.0" targetFramework="net47" />
package id="System.Globalization.Calendars" version="4.3.0" targetFramework="net47" />
package id="System.IO" version="4.3.0" targetFramework="net47" />
package id="System.IO.Compression" version="4.3.0" targetFramework="net47" />
package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="net47" />
package id="System.IO.FileSystem" version="4.3.0" targetFramework="net47" />
package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net47" />
package id="System.Linq" version="4.3.0" targetFramework="net47" />
package id="System.Linq.Expressions" version="4.3.0" targetFramework="net47" />
package id="System.Net.Http" version="4.3.2" targetFramework="net47" />
package id="System.Net.Primitives" version="4.3.0" targetFramework="net47" />
package id="System.Net.Sockets" version="4.3.0" targetFramework="net47" />
package id="System.ObjectModel" version="4.3.0" targetFramework="net47" />
package id="System.Reflection" version="4.3.0" targetFramework="net47" />
package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net47" />
package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net47" />
package id="System.Reflection.TypeExtensions" version="4.4.0" targetFramework="net47" />
package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net47" />
package id="System.Runtime" version="4.3.0" targetFramework="net47" />
package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net47" />
package id="System.Runtime.Handles" version="4.3.0" targetFramework="net47" />
package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net47" />
package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net47" />
package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net47" />
package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net47" />
package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net47" />
package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net47" />
package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net47" />
package id="System.Text.Encoding" version="4.3.0" targetFramework="net47" />
package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net47" />
package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net47" />
package id="System.Threading" version="4.3.0" targetFramework="net47" />
package id="System.Threading.Tasks" version="4.3.0" targetFramework="net47" />
package id="System.Threading.Timer" version="4.3.0" targetFramework="net47" />
package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net47" />
package id="System.Xml.XDocument" version="4.3.0" targetFramework="net47" />
package id="XBee" version="5.3.3" targetFramework="net47" />
package id="XBee.Core" version="1.5.4" targetFramework="net47" />

Feature request: new commands or custom command?

Hello Jeff,

Let me start by saying thank you for suck an amazing library. It took me just a few minutes to set up a simple program that would have otherwise taken me days.

Unfortunately I found that there are a few commands missing in the library that I really need for my application. Those commands are: ID, RP, PR, ST, WH, M0 and M1.

I won't expect you to add all of them (although I'll be more than thankful if you did :).
But perhaps you could add a method to send a custom command, which would enable the possiblity for anyone to send comamnds that are not supported by specific methods in the library.

What do you think?

Thanks,
Agustin.

Connecting

I'm receiving a timeout exception when connecting to my out of the box XBee S2.

XTCU experiences no issues. Is there a specific firmware this is compatible with? Or something simple I am missing?

TxRequestExtFrame with 16-bit address

I was reading through the Xbee documentaion and came across this.

Address Table

The XBee modules can store up to ten address table entries. For applications where a single device (for example coordinator) may send unicast transmissions to more than ten devices, the application should implement an address table to store the 16-bit and 64-bit addresses for each remote device. Any XBee that will send data to more than ten remotes should also use API firmware. The application can then send both the 16-bit and 64-bit addresses to the XBee in the API transmit frames which will significantly reduce the number of 16-bit address discoveries and greatly improve data throughput.

If an application will support an address table, the size should ideally be larger than the maximum number of destination addresses the device will communicate with. Each entry in the address table should contain a 64-bit destination address and its last known 16-bit address.

When sending a transmission to a destination 64-bit address, the application should search the address table for a matching 64-bit address. If a match is found, the 16-bit address should be populated into the 16-bit address field of the API frame. If a match is not found, the 16-bit address should be set to 0xFFFE (unknown) in the API transmit frame.

Could you add the ability to to send a TxRequestExtFrame with the 16-bit address? I looked at it and it just uses 0xFFFE since we don't know it. It would also be cool if the library added the 16-bit address to the node when data is received from the node so I would have an easy way of getting the 16-bit address of the node and when I used the alternate frame that uses the 16-bit address it could just pull it from the node itself so I wouldn't need to keep a separate table of 64-bit and 16-bit pairs.

Also at the moment I can only use Visual Studio 2013 so I can't install Xbee 5.0. I don't know what it would take to add it to the version 4 branch. I am going to try and get at least Visual Studio 2015, but I don't know if I will be able to get it or not.

Error in FindControllersAsync

Hello Jeff,
I have upgraded my version from 1.5.10 to 1.6.1.

I have very often an error in XBeeController.FindControllersAsync

{System.IO.InvalidDataException: Found invalid data while decoding. at XBee.AtCommandWriter.<WriteAsync>d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Core.XBeeControllerBase.<SetApiModeAsync>d__85.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Core.XBeeControllerBase.<InitializeAsync>d__84.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Core.XBeeControllerBase.<ExecuteAsync>d__83.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Core.XBeeControllerBase.<ExecuteQueryAsync>d__761.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at XBee.Core.XBeeControllerBase.d__801.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Core.XBeeControllerBase.<GetHardwareVersionAsync>d__73.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Universal.XBeeController.<TryGetControllerAsync>d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at XBee.Universal.XBeeController.<FindControllersAsync>d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at IT.ITSellingSolution.OmniGreenMaster.XbeeHubNs.XBeeHub.d__89.MoveNext()}

`

I don't have this kind of error in 1.5.10 and I don't have made any changes to code.

Device Discovery is not working in vb.net

Hi Jeff,

I am using XBee Library in my vb.net winforms application. I am using 2 XBee devices(S2C) I have a coordinator in API mode(1). and other 2 XBEEs are in AT mode. While I use XCTU all devices are scanned properly, but while I use this .net library it triggers event randomly (nodeDiscovered)!! I have a debug info here which i am getting on console while I Discover. So everytime while discovery debug shows that devices are getting discovered but event is not triggering everytime!!

Code*
`Imports System.IO.Ports
Imports BinarySerialization
Imports XBee

Public Class FrmMain
Dim WithEvents controller As XBee.XBeeController

Private Sub contoller_NodeDiscovered(sender As Object, e As NodeDiscoveredEventArgs) Handles controller.NodeDiscovered
    Console.WriteLine("Discovered {0}", e.Name)	
End Sub

Private Sub contoller_SampleReceived(sender As Object, e As SourcedSampleReceivedEventArgs) Handles controller.SampleReceived
    Console.WriteLine("Sample recieved: {0}", e)
End Sub

Private Async Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
    BtnDiscover.Enabled = False
    Try
        controller = Await XBeeController.FindAndOpenAsync(SerialPort.GetPortNames(), 9600)
        If controller.IsOpen Then
            BtnDiscover.Enabled = True
        End If
    Catch ex As Exception
        Console.WriteLine(ex.Message & ex.StackTrace)
    End Try
End Sub

Private Async Sub BtnDiscover_Click(sender As Object, e As EventArgs) Handles BtnDiscover.Click
    If Not controller Is Nothing Then
        If controller.IsOpen Then
            Await controller.DiscoverNetworkAsync()
            Console.WriteLine("Node Discovery started")
        End If
    Else
        MsgBox("no Controller attached")
    End If
End Sub

Private Sub controller_FrameMemberSerializing(sender As Object, e As MemberSerializingEventArgs) Handles controller.FrameMemberSerializing
    Console.WriteLine("S-Start: {0}", e.MemberName)
End Sub

Private Sub controller_FrameMemberSerialized(sender As Object, e As MemberSerializedEventArgs) Handles controller.FrameMemberSerialized
    Dim value = If(e.Value, "null")
    Console.WriteLine("S-End: {0} ({1})", e.MemberName, value)
End Sub

Private Sub controller_FrameMemberDeserializing(sender As Object, e As MemberSerializingEventArgs) Handles controller.FrameMemberDeserializing
    Console.WriteLine("D-Start: {0}", e.MemberName)
End Sub

Private Sub controller_FrameMemberDeserialized(sender As Object, e As MemberSerializedEventArgs) Handles controller.FrameMemberDeserialized
    Dim value = If(e.Value, "null")
    Console.WriteLine("D-End: {0} ({1})", e.MemberName, value)
End Sub

End Class`

debug info*
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (4)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (AtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (5)
S-Start: Command
S-Start: Command
S-End: Command (ND)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.NetworkDiscoveryCommand)
S-End: Content (XBee.Frames.AtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (96)
D-End: StartDelimiter (FrameDelimiter)
D-Start: Length
D-End: Length (30)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (AtCommandResponse)
D-Start: Content
D-Start: FrameId
D-End: FrameId (5)
D-Start: Content
D-Start: AtCommand
D-End: AtCommand (ND)
D-Start: Status
D-End: Status (Success)
D-Start: Data
D-Start: ShortAddress
D-Start: Value
D-End: Value (5084)
D-End: ShortAddress (13DC)
D-Start: LongAddress
D-Start: Value
D-End: Value (5526146532141813)
D-End: LongAddress (0013A20041066AF5)
D-Start: ReceivedSignalStrengthIndicator
D-End: ReceivedSignalStrengthIndicator (null)
D-Start: Name
D-End: Name (ROUTER)
D-Start: ExtendedInfo
D-End: ExtendedInfo (null)
D-End: Data (ROUTER: 0013A20041066AF5)
D-End: Content (XBee.Frames.AtCommandResponseFrameContent)
D-End: Content (XBee.Frames.AtCommandResponseFrame)
D-End: Payload (XBee.FramePayload)
D-Start: Checksum
D-End: Checksum (0)
D-Start: StartDelimiter
D-End: StartDelimiter (193)
D-Start: Length
D-End: Length (1296)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (30)
D-Start: Content
D-End: Content (null)
D-End: Payload (XBee.FramePayload)
D-Start: Checksum
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (15)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (RemoteAtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (6)
S-Start: LongAddress
S-Start: Value
S-End: Value (5526146532141813)
S-End: LongAddress (0013A20041066AF5)
S-Start: ShortAddress
S-Start: Value
S-End: Value (65534)
S-End: ShortAddress (FFFE)
S-Start: Options
S-End: Options (Commit)
S-Start: Command
S-Start: Command
S-End: Command (HV)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.HardwareVersionCommand)
S-End: Content (XBee.Frames.RemoteAtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (234)
D-End: Checksum (126)
D-Start: StartDelimiter
D-End: StartDelimiter (0)
D-Start: Length
D-End: Length (4503)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (6)
D-Start: Content
D-End: Content (null)
D-End: Payload (XBee.FramePayload)
D-Start: Checksum
D-End: Checksum (19)
D-Start: StartDelimiter
D-End: StartDelimiter (162)
D-Start: Length
D-End: Length (65)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (6)
D-Start: Content
D-End: Content (null)
D-End: Payload (XBee.FramePayload)
D-Start: Checksum
D-End: Checksum (245)
D-Start: StartDelimiter
D-End: StartDelimiter (XOff)
D-Start: Length
D-End: Length (56392)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (86)
D-Start: Content
D-End: Content (null)
D-End: Payload (XBee.FramePayload)
D-Start: Checksum
D-End: Checksum (46)
D-Start: StartDelimiter
D-End: StartDelimiter (72)
D-Start: Length
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (15)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (RemoteAtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (7)
S-Start: LongAddress
S-Start: Value
S-End: Value (5526146532141813)
S-End: LongAddress (0013A20041066AF5)
S-Start: ShortAddress
S-Start: Value
S-End: Value (65534)
S-End: ShortAddress (FFFE)
S-Start: Options
S-End: Options (Commit)
S-Start: Command
S-Start: Command
S-End: Command (HV)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.HardwareVersionCommand)
S-End: Content (XBee.Frames.RemoteAtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (233)
D-End: Length (1150)
D-Start: Payload
D-Start: FrameType
D-End: FrameType (TxRequest)
D-Start: Content
D-Start: FrameId
D-End: FrameId (17)
D-Start: Destination
D-Start: Value
D-End: Value (10882667108886397190)
D-End: Destination (97070013A2004106)
D-Start: Options
D-End: Options (106)
D-Start: Data
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (15)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (RemoteAtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (8)
S-Start: LongAddress
S-Start: Value
S-End: Value (5526146532141813)
S-End: LongAddress (0013A20041066AF5)
S-Start: ShortAddress
S-Start: Value
S-End: Value (65534)
S-End: ShortAddress (FFFE)
S-Start: Options
S-End: Options (Commit)
S-Start: Command
S-Start: Command
S-End: Command (HV)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.HardwareVersionCommand)
S-End: Content (XBee.Frames.RemoteAtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (232)
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (15)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (RemoteAtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (9)
S-Start: LongAddress
S-Start: Value
S-End: Value (5526146532141813)
S-End: LongAddress (0013A20041066AF5)
S-Start: ShortAddress
S-Start: Value
S-End: Value (65534)
S-End: ShortAddress (FFFE)
S-Start: Options
S-End: Options (Commit)
S-Start: Command
S-Start: Command
S-End: Command (HV)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.HardwareVersionCommand)
S-End: Content (XBee.Frames.RemoteAtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (231)
S-Start: StartDelimiter
S-End: StartDelimiter (FrameDelimiter)
S-Start: Length
S-End: Length (15)
S-Start: Payload
S-Start: FrameType
S-End: FrameType (RemoteAtCommand)
S-Start: Content
S-Start: FrameId
S-End: FrameId (10)
S-Start: LongAddress
S-Start: Value
S-End: Value (5526146532141813)
S-End: LongAddress (0013A20041066AF5)
S-Start: ShortAddress
S-Start: Value
S-End: Value (65534)
S-End: ShortAddress (FFFE)
S-Start: Options
S-End: Options (Commit)
S-Start: Command
S-Start: Command
S-End: Command (HV)
S-Start: Parameter
S-End: Parameter (null)
S-End: Command (XBee.Frames.AtCommands.HardwareVersionCommand)
S-End: Content (XBee.Frames.RemoteAtCommandFrameContent)
S-End: Payload (XBee.FramePayload)
S-Start: Checksum
S-End: Checksum (230)

Please Help me with this issue.
Thanks

No change. Node_SampleReceived is still not being called

After updating to XBee.Core 1.5.5 Node_SampleReceived is still not being called. When I inspect the Node with the debugger, I can see that SampleReceived is set to Node_SampleReceived. As far as I can tell it should work, it just refuses to.

Add AT Command to set SN Register for sleeping end device

Hi Jeff,
I've been using your XBee Library for about a year now. It is Rock Solid! Thank You.

I have been using the source code with a few modifications. I just switched over to using the compiled library so that NuGet will keep up with the latest releases for me.

The only thing missing from the library that I need is the ability to set the SN register on a sleeping end device. I added the following code to my copy of your source and I was hoping you could roll something like it into your released version.

In the AtCommands folder I added this:

namespace XBee.Frames.AtCommands {
public class SleepNumberCyclicCommand : AtCommand {

	public SleepNumberCyclicCommand() : base( "SN" ) {
	}

	public SleepNumberCyclicCommand( ushort numberOfCycles ) : this() {
		NumberOfCycles = numberOfCycles;
	}

	[Ignore]
	public ushort? NumberOfCycles {
		get {
				return Parameter as ushort?;
		}
		set { Parameter = value; }
	}
}

}


To the XBeeNode I added this:

	/// <summary>
	/// Sets the configured Cyclic Sleep Number "SN".
	/// </summary>
	/// <param name="numberOfCycles">The Number of extra "SP" Cyclic Sleep Cycles to sleep for. Total = SP * SN</param>
	public async Task SetSleepNumberCyclicAsync( ushort numberOfCylcles ) {
		await ExecuteAtCommandAsync( new SleepNumberCyclicCommand( numberOfCylcles ) );
	}

I would really appreciate if you could add something like this.
Thanks,
Paul

ATCommand for CB

Hello Jeff,
I noticed that isn't present a command for CB (commisioning button). I would ask you if possibile to send custom AT command to local xBee or is mandattory have a specific function for single AT command.

Thank so much

Stefano

EndOfStreamException when using in UWP app

When I try to use this lib in a UWP app, it throws an EndOfStreamException
at System.IO.BinaryReader.ReadByte() at BinarySerialization.Graph.ValueGraph.ValueValueNode.Deserialize(EndianAwareBinaryReader reader, SerializedType serializedType, Nullable1 length)`

The exception is thrown at the very beginning of the process, during FindAndOpen()... actually it happens the first time ReadByte() is called.

The same thing happens with an FTDI-based XBee board, and with a Leonardo-based serial passthrough device. The XBees are accessible from XCTU through both adapters. I tried with a simple S2, and an S2C Pro TH module, both set to 9600 baud, AO=1, and the result was the same: EndOfStreamException.

Do you have any idea what might be wrong?

Using Series 2 Xbees

I'm having an issue trying to figure out how to construct a frame to send to the Series 2 Xbee. In XBeeController.cs you have the ExecuteAsync function which takes an object of type FrameContent. I assume this is the function that I want to use, but I am not sure where to go from there. Any help would be greatly appreciated! As an example I would like to construct a TX request frame.

Not Receiveing Samples from my nodes

Not receiving samples from my nodes after the last update to the XBee and Serializer Libraries. I was reading your comments from my last issue and it seems like you already know about this. Please let me know if there is a known issue or if I need to figure out what I didn't get updated correctly on my end.

Missing Events?

I'm not sure if this is an issue or not, but I will explain what is going on. Right now I am doing some testing with the XBees to learn how to use your library with them. Each remote XBee(S2B with AT Router Firmware) is paired with either an Arduino or a PIC micro controller. All these do is receive serial data from the host(S2B API Coordinator) and echo it back. My program sends a packet of data to each XBee one at a time. After I send a packet I wait until I receive a response before sending a packet to the next one. I also set a timer to send a packet to the next one if I don't hear back in a certain amount of time. If I receive a packet I compare it to what was sent to make sure that it is correct. I do this in a continuous loop.

Currently I am just sending "Stardust\n". The "\n" is used as a terminator character on the remote devices.(I have those devices send back "Stardust"). Most of time the everything runs great and I get the correct data back before the timer expires. Some times I don't get a response back and the timer expires and I move on to the next one. This is also OK as I expect it to happen sometimes. Then sometimes I go through the loop a few times not getting a response from the same XBee then all of the sudden I get a response that has the word I am expecting only repeated a few times(Something like "StardustStardustStardust"), which I flag as incorrect. I am pretty sure that the remote devices is sending this. The code that I am using is this:

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial2.begin(115200);

}

const char terminator = '\n';
String data;
void loop() {
// put your main code here, to run repeatedly:
if(Serial2.available() > 0){
data = Serial2.readStringUntil(terminator);
Serial.print(data);
Serial2.print(data);
}
}

So is the DataReceived event just not firing? I will include a couple of files that contain some logging info. The normal file shows a couple of normal loops and the other file shows the issue.
normal.docx
problem.docx

controller.GetNodeAsync() sometimes returns null

i have a system where my nodes are running in sleep mode 5. They wake up every 200(ish) seconds. I have found that controller.GetNodeAsync() will often return null after it has attempted several messages to the node during the sleep. Even if I then hard-wire the sleep-request to ground to essentially make it permanently awake, I cannot communicate to the node.

Any ideas of a better way to handle that?

S2C Support for DIO 10 thru DIO 14

Hi Jeff,
I downloaded the latest source for the XBee library. DIO0 thru DIO9 work. However, DIO10 thru DIO14 still don't work. I applied my mods to the source and got them working again. I was really hoping you would think about adding library support for DIOs above 9. I'm not sure how you would do it in the big picture of all the different flavors of XBee. This is what I'm doing to support my S2C version of the XBee.

// INPUT OUTPUT CONFIGURATION


// MODIFIED: InputOutputConfigurationCommand.cs
// Above D9 starts with P0 so I changed the Constructor

public InputOutputConfigurationCommand( InputOutputChannel channel ) :
         base( (int)channel > 9 ? $"P{(int)channel - 10}" : $"D{(int)channel}" ) {
}






// EXTENDED: InputOutputChannel.cs
// It stopped at Channel 9
public enum InputOutputChannel {
    Channel0 = 0,
    Channel1 = 1,
    Channel2 = 2,
    Channel3 = 3,
    Channel4 = 4,
    Channel5 = 5,
    Channel6 = 6,
    Channel7 = 7,
    Channel8 = 8,
    Channel9 = 9,
    Channel10 = 10,
    Channel11 = 11,
    Channel12 = 12,
    Channel13 = 13,
    Channel14 = 14
}





// EXTENDED: DigitalSampleState.cs
public enum DigitalSampleState : ushort {
    None = 0x0,
    Input0 = 0x1,
    Input1 = 0x2,
    Input2 = 0x4,
    Input3 = 0x8,
    Input4 = 0x10,
    Input5 = 0x20,
    Input6 = 0x40,
    Input7 = 0x80,
    Input8 = 0x100,
    Input9 = 0x200,
    Input10 = 0x400,
    Input11 = 0x800,
    Input12 = 0x1000,
    Input13 = 0x2000,
    Input14 = 0x4000,

    All = Input0 | Input1 | Input2 | Input3 | Input4 | Input5
            | Input6 | Input7 | Input8 | Input9 | Input10 | Input11 | Input12 | Input13 | Input14
}





// EXTENDED: DigitalSampleChannels.cs
public enum DigitalSampleChannels : ushort {
    None = 0x0,
    Input0 = 0x1,
    Input1 = 0x2,
    Input2 = 0x4,
    Input3 = 0x8,
    Input4 = 0x10,
    Input5 = 0x20,
    Input6 = 0x40,
    Input7 = 0x80,
    Input8 = 0x100,
    Input9 = 0x200,
    Input10 = 0x400,
    Input11 = 0x800,
    Input12 = 0x1000,
    Input13 = 0x2000,
    Input14 = 0x4000
}




// ADDED TO: RxIndicatorSampleExtFrame.cs
[SerializeWhen( "DigitalChannels", DigitalSampleChannels.Input13,
     ConverterType = typeof( BitwiseAndConverter ), ConverterParameter = DigitalSampleChannels.Input13 )]
[SerializeWhen( "DigitalChannels", DigitalSampleChannels.Input14,
     ConverterType = typeof( BitwiseAndConverter ), ConverterParameter = DigitalSampleChannels.Input14 )]

Anyway, I am using these mods and they do work for the S2C XBee. My favorite was finding out that Configuration Commands above D9 start over with P0. To me, the engineer that came up with that, just wanted to do something really evil ! ! !

Problems calling GetSignalStrengthAsync

I'm having problems when calling this method. I put some test code in the XbeeClassic.Tester app to call this infintely with a 5s or 10s sleep between calls. It will work for a small number of times (never more than about nine, sometimes as few as one) before it starts throwing Timeout exceptions. Once it begins throwing exceptions, it never makes another successful call.

I've tried this on the locally-connected node, as well as networked nodes with similar results. I can do other things: set a digital output high and low on 1s intervals for hours on end. I've also tried changing XBeeControllerBase.DefaultRemoteQueryTimeout and XBeeControllerBase.DefaultLocalQueryTimeout from 10 to 20 with no luck.

Any ideas?

Feature Request: SampleReceivedEventArgs, Properties for accessing Digital and Analog Data

Hi Jeff,
I have been able to get at the Digital and Analog data coming from an XBee. I was hoping that you would add properties to simplify the process. I modified your source code to test my idea and I like the way it works. This is what I did, let me know what you think.

I did this for the DIO pins

class SampleReceivedEventArgs

    /// <summary>
    /// Returns the state of DIO0 from the sample.
    /// </summary>
    public bool D0 { get { return DigitalSampleState.HasFlag( DigitalSampleState.Input0 ); } }

so now I have properties for D0 thru D12 and I can code the Event Handler:

    void DoIt( object node, SampleReceivedEventArgs sample ) {
        if ( !sample.D0 )
            AddLog( "End_Grove: Button_0 Pressed" );
    }

I really like this.

I also did the same for the ADC inputs

    /// <summary>
    /// Returns the value of ADC0 from the sample.
    /// </summary>
    public ushort A0 {
        get {
            foreach ( AnalogSample s in AnalogSamples ) if ( s.Channel == 0 ) return s.Value;
            return 0;
        }
    }

I checked the digital pin mask, to make sure it worked, like this

    /// <summary>
    /// Returns the state of DIO0 from the sample.
    /// </summary>
    public bool D0 {
        get {
            if ( debug_verify_mask && !DigitalChannels.HasFlag( DigitalSampleChannels.Input0 ) )
                throw new InvalidOperationException( string.Format( "{0} is not configured as a digital pin", DigitalSampleChannels.Input0 ) );
            return DigitalSampleState.HasFlag( DigitalSampleState.Input0 );
        }
    }

It works. However, I don't like it because, #1 Even though It does throw an exception the debugger never sees it. #2 The value of debug_verify_mask needs to be set globally. #3 There is no way I could figure out to know which XBee has the problem from inside SampleReceivedEventArgs. I also did something similar for the ADC Mask and it works, but with these same issues.

Anyway, please consider some way of adding properties to SampleReceivedEventArgs. I really like how easy it makes writing code in the Event handler.

Getting Started. Need some enlightenment.

Hi Jeff, Thank you for doing all the heavy lifting involved with creating this XBee library.
I'm going to use it going forward. However, I'm having some issues I hope you will help me with.

My development environment is a Windows 10 Pro Box and Visual Studio 2015 Community, and your XBee Library 2.1.0.0.

I have experience with XBees and I am switching over from a netduino solution to a PC based solution because the creator of the netduino hasn't been heard from for over 6 months.

The last issue in this list is the one I'm stuck on and can't figgure out. I have overcome all the others by using the source code to the XBee library in my test project and making modifications as required.

Issues:
#1. Failed to open COM4 with ZNetZigBeeS2 not supported.

Not a problem because these are the old XBees that have reached End of Life and I had already orderd S2C versions for this project. However, they have been available for years and I was wondering why you don't support them?
#2. Failed to open COM4 with 46 not supported.

This is a S2C XBee that I just received from DigiKey PN:602-1558-ND MFPN:XB24CZ7SIT-004 with a Hardware Version of 2E43. 2E Hex = 46 Dec. I modified the HardwareVersion.cs file because it only contained an enum for: XBee24S2C = 0x22. I added: XBee24C = 0x2E. I also had to modify the XBeeController.cs file: CreateNode switch statement to include, case HardwareVersion.XBee24C: return new XBeeSeries2( this, HardwareVersion.XBee24C, address ); and that solved the issue. FYI: I ordered 3 different types of XBees: RPSMA, UFL, and PCB Antenna. They all start the Hardware Version with 2E.
#3. Sleeping End Devices are not found during Network Discovery.

This is to be expected. I didn't find anything in the readme file addressing this issue. I solved it by manualy adding the node after network discovery:

await controller.DiscoverNetwork();
AddLog( "END network discovery" );
endPorch = await controller.GetRemoteNodeAsync( new NodeAddress( new LongAddress( ulong.Parse( "0013A20040D967EC", System.Globalization.NumberStyles.HexNumber ) ), new ShortAddress( ushort.Parse( "7D34", System.Globalization.NumberStyles.HexNumber ) ) ) );
endPorch.SampleReceived += ( node, sample ) => AddLog( cntr1++.ToString() + " " + DateTime.Now.ToShortTimeString() + " End_Porch Sample: " + sample.DigitalSampleState.ToString() );
AddLog( "End_Porch Added to controller" );

I'm OK with this. However their must be a shorter way of doing this that I didn't find. Also, these sleeping nodes eventualy send a sample to the controller and I was wondering how to catch a transmission from a new network node so I can have software add it to a list of unknown nodes and then add it to my network with my user interface. That way I don't have to use X-CTU to get it's info first.
#4. My sample data coming in from all my XBees says "none" by the time it gets to AddLog(). A Router is sending samples and 2 End Devices are sending samples. This is the one I'm stuck on. I know they are sending DIO input pin states. I just can't figure out where in the library the data is disapearing. Is there more I need to configure when a Node is added? Any help would be appreciated.

Thanks, Paul

RSSI Querying

Would like to be able to query each node for its RSSI.

From my newbie's reading of various docs, I should be able to send a node the DB command, but this API restricts it to the XBeeCellular class. Why is that?

I can give this a go once my hardware shipment comes in and is alive again, but that may be next week.

XBee 900HP

Hi Jeff,

I'm having issues getting the library to work with an XBee 900HP. When I plug in a Series 1 everything works great, but my application requires the 900HP.

The 900HP device is discovered correctly, but as soon as a packet of data comes in I get an exception. I have the endpoint device configured for cyclic sampling so my packets are coming in as RxIndicatorSampleExtFrame.

I noticed that in the source for RxIndicatorSampleExtFrame.cs the valuePath for the SerializeWhen attribute on the AnalogSamples is "AnalogSampleChannels" when the name of the field is AnalogChannels (AnalogSampleChannels is the field type). I changed "AnalogSampleChannels" to "AnalogChannels", but I still get an exception in GetAnalogSamples:
"Value cannot be null.Parameter name: first"

I've been trying to track down what else might be wrong by working my way through the Binary Serializer, but haven't been able to find much.

How much have you tested this against the 900HP series? Would you expect to see these kinds of issues?

Device Information (Pan ID)

Hi,

Im trying to collect the device info from the S2 connected to Pc (via USB). I can connect to the device and retrieve the Identifier and MAC address. But I want to bet more info than that.

From what I can see, the 'local' variable does not expose the methods to retrieve things like PANID.

I tries the GetNodeAsync with the Address of the device, but just get an error.

How can I retrieve the connected devices info?

Thanks

Wondering why ZNetZigBeeS2 is not supported.

Checking serial ports: COM4
Failed to open COM4 with ZNetZigBeeS2 not supported.

These are the previous XBees that have reached End Of Life. MFPN: XB24-Z7WIT-004. I was just wondering why they are not supported. Not a problem. However, I have some spares I would like to be able to use and I'm guessing other people are in the same boat.

Timeout XBee Series 2 Pro S5

Hi mate,

Try to get controller by issuing this statement on my XBee Series 2 Pro S5
var controller = await XBeeController.FindAndOpenAsync(SerialPort.GetPortNames(), 115200);

but it keeps on throwing TimeoutException on this statement from class XBeeControllerBase :

if (await Task.WhenAny(taskCompletionSource.Task, delayTask).ConfigureAwait(false) !=
taskCompletionSource.Task)
{
throw new TimeoutException();
}

Got Hardware version correctly filled up...but address is always null (maybe it is the problem?)

Can you help?
Thank u
Fred

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.