Minor change of c_str() to data() where a null terminator is not needed
[barry.git] / tools / bcharge.cc
blob2006f01225e21077c61dc66d9a13fa6a62b3032a
1 ///
2 /// \file bcharge.cc
3 /// Talk to the Blackberry just enough to change the Max Power
4 /// to 500mA. Cycles through all devices attached to USB,
5 /// attempting to set all matching Blackberry devices to charge.
6 ///
7 /// This file is part of the Barry project:
8 ///
9 /// http://www.netdirect.ca/software/packages/barry/index.php
10 /// http://sourceforge.net/projects/barry
11 ///
12 /// Compile with the following command (needs libusb):
13 ///
14 /// g++ -o bcharge bcharge.cc -lusb
15 ///
18 Copyright (C) 2006-2009, Net Direct Inc. (http://www.netdirect.ca/)
20 This program is free software; you can redistribute it and/or modify
21 it under the terms of the GNU General Public License as published by
22 the Free Software Foundation; either version 2 of the License, or
23 (at your option) any later version.
25 This program is distributed in the hope that it will be useful,
26 but WITHOUT ANY WARRANTY; without even the implied warranty of
27 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
29 See the GNU General Public License in the COPYING file at the
30 root directory of this project for more details.
33 #include <usb.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <fcntl.h>
41 #include <string>
42 #include <barry/common.h>
44 bool old_style_pearl = false;
45 bool force_dual = false;
46 std::string udev_devpath;
47 std::string sysfs_path = "/sys";
49 void Usage()
51 printf(
52 "bcharge - Adjust Blackberry charging modes\n"
53 " Copyright 2006-2009, Net Direct Inc. (http://www.netdirect.ca/)\n"
54 "\n"
55 " -d Dual mode (mode 0004) (default)\n"
56 " -o Set a Pearl to old Blackberry mode (0001)\n"
57 "\n"
58 " -h This help message\n"
59 " -p devpath The devpath argument from udev. If specified, will attempt\n"
60 " to adjust USB suspend settings to keep the device charging.\n"
61 " -s path The path where sysfs is mounted. Defaults to '/sys'\n"
62 "\n"
66 void control(usb_dev_handle *dev, int requesttype, int request, int value,
67 int index, char *bytes, int size, int timeout)
69 int result = usb_control_msg(dev, requesttype, request, value, index,
70 bytes, size, timeout);
71 if( result < 0 ) {
72 printf("\nusb_control_msg failed: code: %d, %s\n", result,
73 usb_strerror());
77 void charge(struct usb_dev_handle *handle)
79 // the special sauce... these steps seem to do the trick
80 // for the 7750 series... needs testing on others
81 char buffer[2];
82 control(handle, 0xc0, 0xa5, 0, 1, buffer, 2, 100);
83 control(handle, 0x40, 0xa2, 0, 1, buffer, 0, 100);
86 void pearl_mode(struct usb_dev_handle *handle)
88 char buffer[2];
89 if( old_style_pearl ) {
90 // use this for "old style" interface: product ID 0001
91 control(handle, 0xc0, 0xa9, 0, 1, buffer, 2, 100);
93 else {
94 // Product ID 0004
95 control(handle, 0xc0, 0xa9, 1, 1, buffer, 2, 100);
99 int find_mass_storage_interface(struct usb_dev_handle *handle)
101 // search the configuration descriptor for a Mass Storage
102 // interface (class 8)
103 struct usb_device *dev = usb_device(handle);
104 struct usb_config_descriptor *cfg = dev ? dev->config : 0;
106 if( cfg ) {
108 for( unsigned i = 0; cfg->interface && i < cfg->bNumInterfaces; i++ ) {
109 struct usb_interface *iface = &cfg->interface[i];
110 for( int a = 0; iface->altsetting && a < iface->num_altsetting; a++ ) {
111 struct usb_interface_descriptor *id = &iface->altsetting[a];
112 if( id->bInterfaceClass == USB_CLASS_MASS_STORAGE )
113 return id->bInterfaceNumber;
118 // if we get here, then we didn't find the Mass Storage interface
119 // ... this should never happen, but if it does, assume
120 // the device is s showing product ID 0006, and the Mass Storage
121 // interface is interface #0
122 printf("Can't find Mass Storage interface, assuming 0.\n");
123 return 0;
126 void driver_conflict(struct usb_dev_handle *handle)
128 // this is called if the first usb_set_configuration()
129 // failed... this most probably means that usb_storage
130 // has already claimed the Mass Storage interface,
131 // in which case we politely tell it to away.
133 #if LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
134 printf("Detecting possible kernel driver conflict, trying to resolve...\n");
136 int iface = find_mass_storage_interface(handle);
137 if( usb_detach_kernel_driver_np(handle, iface) < 0 )
138 printf("usb_detach_kernel_driver_np() failed: %s\n", usb_strerror());
140 if( usb_set_configuration(handle, BLACKBERRY_CONFIGURATION) < 0 )
141 printf("usb_set_configuration() failed: %s\n", usb_strerror());
142 #endif
145 // returns true if device mode was modified, false otherwise
146 bool process(struct usb_device *dev, bool is_pearl)
148 bool apply = false;
149 printf("Found device #%s...", dev->filename);
151 // open
152 usb_dev_handle *handle = usb_open(dev);
153 if( !handle ) {
154 printf("unable to open device\n");
155 return false;
158 // adjust power
159 if( dev->config &&
160 dev->descriptor.bNumConfigurations >= 1 &&
161 dev->config[0].MaxPower < 250 ) {
162 printf("adjusting charge setting");
163 charge(handle);
164 apply = true;
166 else {
167 printf("already at 500mA");
170 // adjust Pearl mode
171 if( is_pearl || force_dual ) {
172 int desired_mode = old_style_pearl
173 ? PRODUCT_RIM_BLACKBERRY : PRODUCT_RIM_PEARL_DUAL;
175 if( desired_mode != dev->descriptor.idProduct ) {
176 printf("...adjusting Pearl mode to %s",
177 old_style_pearl ? "single" : "dual");
178 pearl_mode(handle);
179 apply = true;
181 else {
182 printf("...already in desired Pearl mode");
185 else {
186 printf("...no Pearl adjustment");
189 // apply changes
190 if( apply ) {
191 if( usb_set_configuration(handle, BLACKBERRY_CONFIGURATION) < 0 )
192 driver_conflict(handle);
194 // the Blackberry Pearl doesn't reset itself after the above,
195 // so do it ourselves
196 if( is_pearl || force_dual ) {
198 // It has been observed that the 8830 behaves both like
199 // a Pearl device (in that it has mass storage +
200 // database modes) as well as a Classic device in
201 // that it resets itself and doesn't need an explicit
202 // reset call.
204 // In order to deal with this, we insert a brief sleep.
205 // If it is an 8830, it will reset itself and the
206 // following reset call will fail. If it is a Pearl,
207 // the reset will work as normal.
209 sleep(1);
210 if( usb_reset(handle) < 0 ) {
211 printf("\nusb_reset failed: %s\n", usb_strerror());
215 printf("...done\n");
217 else {
218 printf("...no change\n");
221 // cleanup
222 usb_close(handle);
223 return apply;
226 bool power_write(const std::string &file, const std::string &value)
228 // attempt to open the state file
229 int fd = open(file.c_str(), O_RDWR);
230 if( fd == -1 ) {
231 printf("autosuspend adjustment failure: (file: %s): %s\n",
232 file.c_str(),
233 strerror(errno));
234 return false;
237 int written = write(fd, value.data(), value.size());
238 int error = errno;
239 close(fd);
241 if( written < 0 || (size_t)written != value.size() ) {
242 printf("autosuspend adjustment failure (write): (file: %s): %s\n",
243 file.c_str(),
244 strerror(error));
245 return false;
248 printf("autosuspend adjustment: wrote %s to %s\n",
249 value.c_str(), file.c_str());
250 return true;
254 // Checks for USB suspend, and enables the device if suspended.
256 // Kernel 2.6.21 behaves with autosuspend=0 meaning off, while 2.6.22
257 // and higher needs autosuspend=-1 to turn it off. In 2.6.22, a value
258 // of 0 means "immediate" instead of "never".
260 // Version 2.6.22 adds variables internal to the system called
261 // autosuspend_disabled and autoresume_disabled. These are controlled by the
262 // /sys/class/usb_device/*/device/power/level file. (See below)
264 // Here's a summary of files under device/power. These may or may not exist
265 // depending on your kernel version and configuration.
268 // autosuspend
269 // -1 or 0 means off, depending on kernel,
270 // otherwise it is the number of seconds to
271 // autosuspend
273 // level
274 // with the settings:
276 // on - suspend is disabled, device is fully powered
277 // auto - suspend is controlled by the kernel (default)
278 // suspend - suspend is enabled permanently
280 // You can write these strings to the file to control
281 // behaviour on a per-device basis.
283 // echo on > /sys/usb_device/.../device/power/level
285 // state
286 // current state of device
287 // 0 - fully powered
288 // 2 - suspended
290 // You can write these numbers to control behaviour, but
291 // any change you make here might change automatically
292 // if autosuspend is on.
294 // echo -n 0 > /sys/usb_device/.../device/power/state
296 // wakeup
297 // unknown
300 // Given the above facts, use the following heuristics to try to disable
301 // autosuspend for the Blackberry:
303 // - if level exists, write "on" to it
304 // - if autosuspend exists, write -1 to it
305 // - if error, write 0 to it
306 // - if neither of the above work, and state exists, write 0 to it
308 void resume()
310 if( udev_devpath.size() == 0 )
311 return; // nothing to do
313 // let sysfs settle a bit
314 sleep(5);
316 std::string power_path = sysfs_path + "/" + udev_devpath + "/device/power/";
318 if( !power_write(power_path + "level", "on\n") )
319 if( !power_write(power_path + "autosuspend", "-1\n") )
320 if( !power_write(power_path + "autosuspend", "0\n") )
321 power_write(power_path + "state", "0");
324 int main(int argc, char *argv[])
326 struct usb_bus *busses;
329 // allow -o command line switch to choose which mode to use for
330 // Blackberry Pearls:
331 // Dual(default): 0004 -d
332 // With switch: 0001 -o
335 // process command line options
336 for(;;) {
337 int cmd = getopt(argc, argv, "dop:s:h");
338 if( cmd == -1 )
339 break;
341 switch( cmd )
343 case 'd': // Dual (default)
344 force_dual = true;
345 old_style_pearl = false;
346 break;
348 case 'o': // Old style pearl
349 force_dual = false;
350 old_style_pearl = true;
351 break;
353 case 'p': // udev devpath
354 udev_devpath = optarg;
355 break;
357 case 's': // where sysfs is mounted
358 sysfs_path = optarg;
359 break;
361 case 'h': // help!
362 default:
363 Usage();
364 return 0;
368 usb_init();
369 if( usb_find_busses() < 0 || usb_find_devices() < 0 ) {
370 printf("\nUnable to scan devices: %s\n", usb_strerror());
371 return 1;
373 busses = usb_get_busses();
375 printf("Scanning for Blackberry devices...\n");
377 struct usb_bus *bus;
378 for( bus = busses; bus; bus = bus->next ) {
379 struct usb_device *dev;
381 for (dev = bus->devices; dev; dev = dev->next) {
382 // Is this a blackberry?
383 if( dev->descriptor.idVendor == VENDOR_RIM ) {
384 switch(dev->descriptor.idProduct)
386 case PRODUCT_RIM_BLACKBERRY:
387 if( !process(dev, false) )
388 resume();
389 break;
391 case PRODUCT_RIM_PEARL_DUAL:
392 case PRODUCT_RIM_PEARL:
393 case PRODUCT_RIM_PEARL_8120:
394 case PRODUCT_RIM_STORM:
395 if( !process(dev, true) )
396 resume();
397 break;