Module: Ant

Extended by:
Loggability
Defined in:
lib/ant.rb,
lib/ant/mixins.rb,
ext/ant_ext/ant_ext.c,
ext/ant_ext/ant_ext.c,
ext/ant_ext/channel.c,
ext/ant_ext/message.c

Overview

This is an extension for using the ANT ultra-low power wireless protocol via the Garmin USB ANT Stick. ANT can be used to send information wirelessly from one device to another device, in a robust and flexible manner.

Defined Under Namespace

Modules: Channel, DataUtilities, ResponseCallbacks Classes: BitVector, Message

Constant Summary collapse

VERSION =

Package version

'0.4.0'
VALID_DEVICE_NUMBERS =

A Range for matching valid ANT device numbers

( 0...65535 ).freeze
VALID_DEVICE_TYPES =

A Range for matching valid ANT device types (6 least signficant bits)

( 0...127 ).freeze
VALID_CHANNEL_PERIODS =

The default range of frequencies for the channel period

( 0...65535 ).freeze
VALID_RF_FREQUENCIES =

The valid offsets for the “RF Frequency” setting; this is an offset from 2400Hz.

( 0...124 ).freeze
DEFAULT_ADVANCED_OPTIONS =

Default options for advanced burst when it’s enabled.

{
  max_packet_length: 24,
  frequency_hopping: :optional,
  stall_count: 0,
  retry_count: 0
}
ANT_EXT_MESG_BITFIELD_EXTENSION =
INT2FIX(ANT_EXT_MESG_BIFIELD_EXTENSION)
EXT_PARAM_BACKGROUND_SCANNING =

Set up some aliases and values not in ant.h

INT2FIX(EXT_PARAM_ALWAYS_SEARCH)
EXT_PARAM_FAST_CHANNEL_INIT =
INT2FIX(0x10)
EXT_PARAM_ASYNC_TRANSMIT =
INT2FIX(0x20)
CAPABILITIES_RFACTIVE_NOTIFICATION_ENABLED =

Not in the header; this is taken from 9.5.7.4, ANT Message Protocol and Usage v5.1

INT2FIX(0)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#capabilitiesObject (readonly)

Returns the value of attribute capabilities.



48
49
50
# File 'lib/ant.rb', line 48

def capabilities
  @capabilities
end

#hardware_versionObject (readonly)

Returns the value of attribute hardware_version.



57
58
59
# File 'lib/ant.rb', line 57

def hardware_version
  @hardware_version
end

#serial_numObject (readonly)

Returns the value of attribute serial_num.



52
53
54
# File 'lib/ant.rb', line 52

def serial_num
  @serial_num
end

Class Method Details

.assign_channel(channel, channel_type, network_number = 0, extended_options = 0x0, timeout = 0) ⇒ Object

Assign a channel and return an Ant::Channel object for it. Channel assignment reserves a channel number and assigns the type and network number to the channel. The optional extended assignment byte allows for the following features to be enabled:

EXT_PARAM_FREQUENCY_AGILITY

enable frequency agility

EXT_PARAM_BACKGROUND_SCANNING

enable background scanning

EXT_PARAM_FAST_CHANNEL_INIT

enable fast channel initiation

EXT_PARAM_ASYNC_TRANSMIT

enable asynchronous transmission



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'ext/ant_ext/ant_ext.c', line 362

static VALUE
rant_s_assign_channel( int argc, VALUE *argv, VALUE _module )
{
  unsigned char ucChannel,
    ucChannelType,
    ucNetworkNumber = 0,
    ucExtend = 0,
    ulResponseTime = 0;
  VALUE channel,
    channel_type,
    network_number,
    extended_options,
    timeout;
  VALUE args[4];

  rb_scan_args( argc, argv, "23", &channel, &channel_type, &network_number, &extended_options, &timeout );

  ucChannel = NUM2CHR( channel );
  ucChannelType = NUM2CHR( channel_type );

  if ( RTEST(network_number) ) {
    ucNetworkNumber = NUM2CHR( network_number );
  }
  if ( RTEST(extended_options) ) {
    ucExtend = NUM2CHR( extended_options );
  }
  if ( RTEST(timeout) ) {
    ulResponseTime = NUM2CHR( timeout );
  }

  if ( !ANT_AssignChannelExt_RTO(ucChannel, ucChannelType, ucNetworkNumber, ucExtend, ulResponseTime) ) {
    rb_raise( rb_eRuntimeError, "Couldn't assign channel %d", ucChannel );
  }

  rant_log( "info", "Assigned channel %d (0x%02x) to network %d {0x%02x}.",
    ucChannel, ucChannelType, ucNetworkNumber, ucExtend );

  args[0] = channel;
  args[1] = channel_type;
  args[2] = network_number;
  args[3] = extended_options;

  return rb_class_new_instance( 4, args, rant_cAntChannel );
}

.closeObject

Close the USB connection to the ANT module.



256
257
258
259
260
261
262
263
264
# File 'ext/ant_ext/ant_ext.c', line 256

static VALUE
rant_s_close( VALUE _module )
{
  ANT_Close();

  rant_channel_clear_registry();

  return Qtrue;
}

.configure_advanced_burst(enabled, max_packet_length, required_fields, optional_fields) ⇒ Object .stall_count=Object

Enable/disable and configure advanced burst. This is the lower-level method; the higher-level methods are: #enable_advanced_burst and #disable_advanced_burst.



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'ext/ant_ext/ant_ext.c', line 439

static VALUE
rant_s_configure_advanced_burst( int argc, VALUE *argv, VALUE _module )
{
  VALUE enabled,
    max_packet_length,
    required_fields,
    optional_fields,
    stall_count = Qnil,
    retry_count = Qnil;
  bool bEnable;
  unsigned char ucMaxPacketLength,
    ucRetryCount = 0;
  unsigned long ulRequiredFields,
    ulOptionalFields;
  unsigned short usStallCount = 0;
  bool rval;

  rb_scan_args( argc, argv, "42", &enabled, &max_packet_length, &required_fields,
    &optional_fields, &stall_count, &retry_count );

  bEnable = RTEST( enabled );
  ucMaxPacketLength = NUM2CHR( max_packet_length );
  ulRequiredFields = NUM2ULONG( required_fields );
  ulOptionalFields = NUM2ULONG( optional_fields );

  if ( RTEST(stall_count) ) {
    usStallCount = NUM2USHORT( stall_count );
  }
  if ( RTEST(retry_count) ) {
    ucRetryCount = NUM2CHR( retry_count );
  }

  rant_log( "warn", "Configuring advanced burst: enable = %d, maxpacketlength = %d",
    bEnable, ucMaxPacketLength );
  rval = ANT_ConfigureAdvancedBurst_ext( bEnable, ucMaxPacketLength, ulRequiredFields,
    ulOptionalFields, usStallCount, ucRetryCount );

  return rval ? Qtrue : Qfalse;
}

.convert_max_packet_length(length) ⇒ Object

Validate that the specified length (in bytes) is a valid setting as an advanced burst max packet length configuration value. Returns the equivalent configuration value.



175
176
177
178
179
180
181
182
183
184
# File 'lib/ant.rb', line 175

def self::convert_max_packet_length( length )
  case length
  when 8 then return 0x01
  when 16 then return 0x02
  when 24 then return 0x03
  else
    raise ArgumentError,
      "invalid max packet length; expected 8, 16, or 24, got %p" % [ length ]
  end
end

.device_serial_numberInteger

Returns the serial number of the ANT device; not implemented on all devices.

Returns:

  • (Integer)


173
174
175
176
177
178
179
180
181
182
# File 'ext/ant_ext/ant_ext.c', line 173

static VALUE
rant_s_device_serial_number( VALUE _module )
{
#ifdef HAVE_ANT_GETDEVICESERIALNUMBER
  const unsigned long serial = ANT_GetDeviceSerialNumber();
  return LONG2FIX( serial );
#else
  rb_notimplement();
#endif
}

.device_usb_info(device_num) ⇒ Array

Get the product and serial info of the USB device device_num.

Returns:

  • (Array)


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'ext/ant_ext/ant_ext.c', line 106

static VALUE
rant_s_device_usb_info( VALUE _module, VALUE device_num )
{
  const unsigned short deviceNum = NUM2SHORT( device_num );
  unsigned char product_string[256];
  unsigned char serial_string[256];
  VALUE rval = rb_ary_new2( 2 );

  if ( !ANT_GetDeviceUSBInfo( (unsigned char)deviceNum, product_string, serial_string ) ) {
    return Qnil;
  }

  rant_log_obj( _module, "debug", "Got product string = %s, serial string = %s", product_string, serial_string );
  rb_ary_push( rval, rb_str_new_cstr((const char *)product_string) );
  rb_ary_push( rval, rb_str_new_cstr((const char *)serial_string) );

  return rval;
}

.device_usb_pidInteger

Returns the pid of the USB device.

Returns:

  • (Integer)


133
134
135
136
137
138
139
140
141
142
143
# File 'ext/ant_ext/ant_ext.c', line 133

static VALUE
rant_s_device_usb_pid( VALUE _module )
{
  unsigned short pid;

  if ( !ANT_GetDeviceUSBPID(&pid) ) {
    rb_sys_fail( "Fetching the USB PID." );
  }

  return INT2FIX( pid );
}

.device_usb_vidInteger

Returns the vid of the USB device.

Returns:

  • (Integer)


153
154
155
156
157
158
159
160
161
162
163
# File 'ext/ant_ext/ant_ext.c', line 153

static VALUE
rant_s_device_usb_vid( VALUE _module )
{
  unsigned short vid;

  if ( !ANT_GetDeviceUSBVID(&vid) ) {
    rb_sys_fail( "Fetching the USB VID." );
  }

  return INT2FIX( vid );
}

.enable_advanced_burst(**options) ⇒ Object

Enable advanced burst mode with the given options.



156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/ant.rb', line 156

def self::enable_advanced_burst( **options )
  options = DEFAULT_ADVANCED_OPTIONS.merge( options )

  max_packet_length = self.convert_max_packet_length( options[:max_packet_length] )

  required_fields = self.make_required_fields_config( options )
  optional_fields = self.make_optional_fields_config( options )

  stall_count = options[:stall_count]
  retry_count = options[:retry_count]

  self.configure_advanced_burst( true, max_packet_length, required_fields, optional_fields,
    stall_count, retry_count )
end

.init(device_num = 0, baud_rate = 57600) ⇒ true

Initialize the ANT library and connect to the ANT module. The device_num is the USB device number of the module to connect to, defaulting to 0. Modules connected to a PC will be assigned USB device numbers starting from 0. N is the number of USB ANT devices that are connected. The baud_rate is the asynchronous baud rate used to connect to the ANT controller. See specific ANT controllers for allowable baud rates.

Returns:

  • (true)


198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'ext/ant_ext/ant_ext.c', line 198

static VALUE
rant_s_init( int argc, VALUE *argv, VALUE _module )
{
  VALUE device_num = Qnil, baud_rate = Qnil;
  unsigned char ucUSBDeviceNum;
  unsigned int ulBaudrate;

  rb_scan_args( argc, argv, "02", &device_num, &baud_rate );

  if ( RTEST(device_num) ) {
    ucUSBDeviceNum = NUM2CHR( device_num );
  } else {
    ucUSBDeviceNum = 0;
  }

  if ( RTEST(baud_rate) ) {
    ulBaudrate = NUM2UINT( baud_rate );
  } else {
    ulBaudrate = DEFAULT_BAUDRATE;
  }

  rant_log_obj( rant_mAnt, "info", "Initializing ANT device %d at %d baud", ucUSBDeviceNum, ulBaudrate );
  if ( !ANT_Init(ucUSBDeviceNum, ulBaudrate) ) {
    rb_raise( rb_eRuntimeError, "Initializing the ANT library (no ANT device present?)." );
  }

  return Qtrue;
}

.initialized?Boolean

Returns true if the ANT library has been initialized.

Note: this requires a modified version of the Garmin ANT-SDK.

Returns:

  • (Boolean)


237
238
239
240
241
242
243
244
245
246
# File 'ext/ant_ext/ant_ext.c', line 237

static VALUE
rant_s_initialized_p( VALUE _module )
{
#ifdef HAVE_ANT_ISINITIALIZED
  const bool initialized = ANT_IsInitialized();
  return initialized ? Qtrue : Qfalse;
#else
  rb_notimplement();
#endif
}

.lib_versionInteger

Return the version of the underlying libant.

Returns:

  • (Integer)


90
91
92
93
94
95
96
# File 'ext/ant_ext/ant_ext.c', line 90

static VALUE
rant_s_lib_version( VALUE _module )
{
  const char *version = ANT_LibVersion();

  return rb_str_new_cstr( version );
}

.log_directory=(directory) ⇒ Object

Write debugging logs to the specified directory, which should already exist.



637
638
639
640
641
642
643
644
# File 'ext/ant_ext/ant_ext.c', line 637

static VALUE
rant_s_log_directory_eq( VALUE _module, VALUE directory )
{
  const char *directory_s = StringValueCStr( directory );
  bool rval = ANT_SetDebugLogDirectory( (char *)directory_s );

  return rval ? Qtrue : Qfalse;
}

.make_optional_fields_config(**options) ⇒ Object

Given an options hash, return a configuration value for optional fields.



197
198
199
200
201
202
# File 'lib/ant.rb', line 197

def self::make_optional_fields_config( **options )
  value = 0
  value |= 0x01 if options[:frequency_hopping] == :optional

  return value
end

.make_required_fields_config(**options) ⇒ Object

Given an options hash, return a configuration value for required fields.



188
189
190
191
192
193
# File 'lib/ant.rb', line 188

def self::make_required_fields_config( **options )
  value = 0
  value |= 0x01 if options[:frequency_hopping] == :required

  return value
end

.on_response {|channel, response_msg_id| ... } ⇒ Object

Sets the response callback. The callback is called whenever a response message is received from ANT. See #set_response_handlers for a set of default handlers.

Yields:

  • (channel, response_msg_id)


542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'ext/ant_ext/ant_ext.c', line 542

static VALUE
rant_s_on_response( int argc, VALUE *argv, VALUE module )
{
  VALUE callback = Qnil;

  rb_scan_args( argc, argv, "0&", &callback );

  if ( !RTEST(callback) ) {
    rb_raise( rb_eLocalJumpError, "block required, but not given" );
  }

  rant_log( "debug", "Callback is: %s", RSTRING_PTR(rb_inspect(callback)) );
  rb_ivar_set( module, response_callback_ivar, callback );

  ANT_AssignResponseFunction( rant_on_response_callback, pucResponseBuffer );

  return Qtrue;
}

.request_advanced_burst_capabilitiesObject

Request the current device’s advanced burst capabilities. The result will be delivered via a callback to the #on_version response callback, which by default extracts it and stores it at Ant.advanced_burst_capabilities.



622
623
624
625
626
627
# File 'ext/ant_ext/ant_ext.c', line 622

static VALUE
rant_s_request_advanced_burst_capabilities( VALUE _module )
{
  bool rval = ANT_RequestMessage( 0, MESG_CONFIG_ADV_BURST_ID );
  return rval ? Qtrue : Qfalse;
}

.request_capabilitiesObject

Request the current ANT device’s capabilities. These will be delivered via a callback to the #on_capabilities response callback, which by default extracts them into a Hash which is stored at Ant.capabilities.



571
572
573
574
575
576
# File 'ext/ant_ext/ant_ext.c', line 571

static VALUE
rant_s_request_capabilities( VALUE _module )
{
  bool rval = ANT_RequestMessage( 0, MESG_CAPABILITIES_ID );
  return rval ? Qtrue : Qfalse;
}

.request_serial_numObject

Request the current ANT device’s serial number. The result will be delivered via a callback to the #on_get_serial_num response callback, which by default extracts it and stores it at Ant.serial_number.



588
589
590
591
592
593
# File 'ext/ant_ext/ant_ext.c', line 588

static VALUE
rant_s_request_serial_num( VALUE _module )
{
  bool rval = ANT_RequestMessage( 0, MESG_GET_SERIAL_NUM_ID );
  return rval ? Qtrue : Qfalse;
}

.request_versionObject

Request the current device’s ANT version. The result will be delivered via a callback to the #on_version response callback, which by default extracts it and stores it at Ant.hardware_version.



605
606
607
608
609
610
# File 'ext/ant_ext/ant_ext.c', line 605

static VALUE
rant_s_request_version( VALUE _module )
{
  bool rval = ANT_RequestMessage( 0, MESG_VERSION_ID );
  return rval ? Qtrue : Qfalse;
}

.resetObject

Reset the system and put it in a known, low-power state. Execution of this command terminates all channels. All information previously configured in the system can no longer be considered valid.



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'ext/ant_ext/ant_ext.c', line 276

static VALUE
rant_s_reset( VALUE _module )
{
  const struct timeval wait_time = {
    .tv_sec = 0,
    .tv_usec = 500,
  };
  ANT_ResetSystem();

  rant_channel_clear_registry();

  // After a Reset System command has been issued, the application should wait
  // 500ms to ensure that ANT is in the proper, 

.set_network_key(network_num, network_key) ⇒ Object

Configures a network address for use by one of the available network numbers.



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'ext/ant_ext/ant_ext.c', line 303

static VALUE
rant_s_set_network_key( VALUE _module, VALUE network_number, VALUE key )
{
  const unsigned short ucNetNumber = NUM2USHORT( network_number );
  const char *pucKey = StringValuePtr( key );

  if ( RSTRING_LEN(key) != 8 ) {
    rb_raise( rb_eArgError, "expected an 8-byte key" );
  }

  if ( !ANT_SetNetworkKey(ucNetNumber, (unsigned char *)pucKey) ) {
    rant_log( "error", "could not set the network key." );
  }

  return Qtrue;
}

.set_response_handler(object = Ant::ResponseCallbacks) ⇒ Object

Set up the given object as the handler for response callbacks. It must respond to :handle_response_callback.



65
66
67
# File 'lib/ant.rb', line 65

def self::set_response_handler( object=Ant::ResponseCallbacks )
  self.on_response( &object.method(:handle_response_callback) )
end

.transmit_power=(4) ⇒ Object

Set the transmit power level for all channels. Valid values are 0-4; default is 3 = 0dBm.

# Set transmit power to -5 dBm
Ant.transmit_power = 2


331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'ext/ant_ext/ant_ext.c', line 331

static VALUE
rant_s_transmit_power_eq( VALUE _module, VALUE power )
{
  const unsigned char ucTransmitPower = NUM2CHR( power );
  BOOL rval;

  if ( ucTransmitPower < 0 || ucTransmitPower > 4 ) {
    rb_raise( rb_eArgError, "expected a value between 0 and 4, got %d", ucTransmitPower );
  }

  rval = ANT_SetTransmitPower( ucTransmitPower );

  return rval ? Qtrue : Qfalse;
}

.use_extended_messages=(true) ⇒ Object

Enable or disable extended Rx messages. If the device supports it, when ANT will include the channel ID with the data message.



416
417
418
419
420
421
422
423
424
425
426
427
# File 'ext/ant_ext/ant_ext.c', line 416

static VALUE
rant_s_use_extended_messages_eq( VALUE _module, VALUE true_false )
{
  // This is documented as an unsigned char and then explicitly cast
  // to a signed char. So this just uses their typedef.
  const BOOL ucEnable = RTEST( true_false ) ? TRUE : FALSE;

  rant_log( "info", "%s extended messages.", ucEnable ? "Enabling" : "Disabling" );
  ANT_RxExtMesgsEnable( ucEnable );

  return Qtrue;
}

.validate_channel_period(frequency) ⇒ Object

Check that specified frequency is a valid channel period and raise an appropriate exception if it isn’t. Returns the frequency as an Integer if it is valid.



101
102
103
104
105
106
107
108
109
# File 'lib/ant.rb', line 101

def self::validate_channel_period( frequency )
  frequency = Integer( frequency )
  unless VALID_CHANNEL_PERIODS.include?( frequency )
    raise RangeError, "invalid channel period; expected a frequency between %d and %d, got %p" %
      [ VALID_CHANNEL_PERIODS.begin, VALID_CHANNEL_PERIODS.end, frequency ]
  end

  return frequency
end

.validate_device_number(number) ⇒ Object

Check that specified number is a valid device number and raise an appropriate exception if it isn’t. Returns the number as an Integer if it is valid.



73
74
75
76
77
78
79
80
81
# File 'lib/ant.rb', line 73

def self::validate_device_number( number )
  number = Integer( number )
  unless VALID_DEVICE_NUMBERS.include?( number )
    raise RangeError, "invalid device number; expected a number between %d and %d, got %p" %
      [ VALID_DEVICE_NUMBERS.begin, VALID_DEVICE_NUMBERS.end, number ]
  end

  return number
end

.validate_device_type(number) ⇒ Object

Check that specified number is a valid device type and raise an appropriate exception if it isn’t. Returns the number as an Integer if it is valid.



87
88
89
90
91
92
93
94
95
# File 'lib/ant.rb', line 87

def self::validate_device_type( number )
  number = Integer( number )
  unless VALID_DEVICE_TYPES.include?( number )
    raise RangeError, "invalid device type; expected a number between %d and %d, got %p" %
      [ VALID_DEVICE_TYPES.begin, VALID_DEVICE_TYPES.end, number ]
  end

  return number
end

.validate_network_key(data) ⇒ Object

Check that specified data is a valid ANT network key and raise an appropriate exception if it isn’t. Returns the key itself if it is valid.



129
130
131
132
133
134
135
136
137
138
# File 'lib/ant.rb', line 129

def self::validate_network_key( data )
  data = data.to_s
  unless data.bytesize == 8
    raise RangeError, "invalid network key; expected exactly eight bytes, got %d" %
      [ data.bytesize ]
  end

  self.log.debug "Validated network key: %p" % [ data ]
  return data
end

.validate_network_number(number) ⇒ Object

Check that specified number is a valid ANT network number and raise an appropriate exception if it isn’t. Note that this does not check the local device(s) to ensure they support the given network. Returns the key as an Integer if it is valid.



116
117
118
119
120
121
122
123
124
# File 'lib/ant.rb', line 116

def self::validate_network_number( number )
  number = Integer( number )
  unless number >= 0 && number <= 255
    raise RangeError, "invalid network number; expected an eight-bit number, got %p" %
      [ number ]
  end

  return number
end

.validate_rf_frequency(offset) ⇒ Object

Check that specified offset is a valid “rf frequency” and raise an appropriate exception if it isn’t. Returns the offset as an Integer if it is valid.



144
145
146
147
148
149
150
151
152
# File 'lib/ant.rb', line 144

def self::validate_rf_frequency( offset )
  offset = Integer( offset )
  unless VALID_RF_FREQUENCIES.include?( offset )
    raise RangeError, "invalid RF Frequency; expected a offset between %d and %d, got %p" %
      [ VALID_RF_FREQUENCIES.begin, VALID_RF_FREQUENCIES.end, offset ]
  end

  return offset
end