1 /*
2     OWFS -- One-Wire filesystem
3     OWHTTPD -- One-Wire Web Server
4     Written 2003 Paul H Alfille
5     email: paul.alfille@gmail.com
6     Released under the GPL
7     See the header file: ow.h for full attribution
8     1wire/iButton system from Dallas Semiconductor
9 */
10 
11 /* DS9490R-W USB 1-Wire master
12 
13    USB parameters:
14        Vendor ID: 04FA
15        ProductID: 2490
16 
17    Dallas controller DS2490
18 
19 */
20 
21 #include <config.h>
22 #include "owfs_config.h"
23 #include "ow.h"
24 #include "ow_counters.h"
25 #include "ow_connection.h"
26 #include "ow_codes.h"
27 
28 #if OW_USB						/* conditional inclusion of USB */
29 #include "ow_usb_msg.h"
30 #include "ow_usb_cycle.h"
31 
32 /* All the rest of the code sees is the DS9490_detect routine and the iroutine structure */
33 
34 static RESET_TYPE DS9490_reset(const struct parsedname *pn);
35 static void BUS_ERROR_fix(const struct parsedname *pn);
36 
37 static GOOD_OR_BAD DS9490_detect_single_adapter(int usb_nr, struct connection_in *in);
38 static GOOD_OR_BAD DS9490_detect_all_adapters(struct port_in * pin_first);
39 static GOOD_OR_BAD DS9490_detect_specific_adapter(int bus_nr, int dev_nr, struct connection_in * in) ;
40 
41 static GOOD_OR_BAD DS9490_reconnect(const struct parsedname *pn);
42 static GOOD_OR_BAD DS9490_redetect_low(struct connection_in * in);
43 static GOOD_OR_BAD DS9490_redetect_match(struct connection_in * in);
44 static GOOD_OR_BAD DS9490_redetect_specific_adapter( struct connection_in * in) ;
45 static void DS9490_setroutines(struct connection_in *in);
46 static GOOD_OR_BAD DS9490_setup_adapter(struct connection_in * in) ;
47 
48 static enum search_status DS9490_next_both(struct device_search *ds, const struct parsedname *pn);
49 static GOOD_OR_BAD DS9490_sendback_data(const BYTE * data, BYTE * resp, size_t len, const struct parsedname *pn);
50 static GOOD_OR_BAD DS9490_HaltPulse(const struct parsedname *pn);
51 static GOOD_OR_BAD DS9490_PowerByte(BYTE byte, BYTE * resp, UINT delay, const struct parsedname *pn);
52 static GOOD_OR_BAD DS9490_ProgramPulse(const struct parsedname *pn);
53 static GOOD_OR_BAD DS9490_overdrive(const struct parsedname *pn);
54 static void SetupDiscrepancy(const struct device_search *ds, BYTE * discrepancy);
55 static int FindDiscrepancy(BYTE * last_sn, BYTE * discrepancy_sn);
56 static enum search_status DS9490_directory(struct device_search *ds, const struct parsedname *pn);
57 static GOOD_OR_BAD DS9490_SetSpeed(const struct parsedname *pn);
58 static void DS9490_SetFlexParameters(struct connection_in *in) ;
59 static GOOD_OR_BAD DS9490_open_and_name( libusb_device * dev, struct connection_in *in);
60 
61 /* Device-specific routines */
DS9490_setroutines(struct connection_in * in)62 static void DS9490_setroutines(struct connection_in *in)
63 {
64 	in->iroutines.detect = DS9490_detect;
65 	in->iroutines.reset = DS9490_reset;
66 	in->iroutines.next_both = DS9490_next_both;
67 	in->iroutines.PowerByte = DS9490_PowerByte;
68 	in->iroutines.ProgramPulse = DS9490_ProgramPulse;
69 	in->iroutines.sendback_data = DS9490_sendback_data;
70 	in->iroutines.sendback_bits = NO_SENDBACKBITS_ROUTINE;
71 	in->iroutines.select = NO_SELECT_ROUTINE;
72 	in->iroutines.select_and_sendback = NO_SELECTANDSENDBACK_ROUTINE;
73 	in->iroutines.set_config = NO_SET_CONFIG_ROUTINE;
74 	in->iroutines.get_config = NO_GET_CONFIG_ROUTINE;
75 	in->iroutines.reconnect = DS9490_reconnect;
76 	in->iroutines.close = DS9490_close;
77 	in->iroutines.verify = NO_VERIFY_ROUTINE ;
78 	in->iroutines.flags = ADAP_FLAG_default;
79 
80 	in->bundling_length = USB_FIFO_SIZE;
81 }
82 
83 #define DS2490_BULK_BUFFER_SIZE     64
84 //#define DS2490_DIR_GULP_ELEMENTS     ((DS2490_BULK_BUFFER_SIZE/SERIAL_NUMBER_SIZE) - 1)
85 #define DS2490_DIR_GULP_ELEMENTS     (1)
86 
87 #define MOD_PULSE_EN            0x0000
88 #define MOD_SPEED_CHANGE_EN     0x0001
89 #define MOD_1WIRE_SPEED         0x0002
90 #define MOD_STRONG_PU_DURATION  0x0003
91 #define MOD_PULLDOWN_SLEWRATE   0x0004
92 #define MOD_PROG_PULSE_DURATION 0x0005
93 #define MOD_WRITE1_LOWTIME      0x0006
94 #define MOD_DSOW0_TREC          0x0007
95 
96 //
97 // Value field COMM Command options
98 //
99 // COMM Bits (bitwise or into COMM commands to build full value byte pairs)
100 // Byte 1
101 #define COMM_TYPE                   0x0008
102 #define COMM_SE                     0x0008
103 #define COMM_D                      0x0008
104 #define COMM_Z                      0x0008
105 #define COMM_CH                     0x0008
106 #define COMM_SM                     0x0008
107 
108 #define COMM_R                      0x0008
109 #define COMM_IM                     0x0001
110 
111 // Byte 2
112 #define COMM_PS                     0x4000
113 #define COMM_PST                    0x4000
114 #define COMM_CIB                    0x4000
115 #define COMM_RTS                    0x4000
116 #define COMM_DT                     0x2000
117 #define COMM_SPU                    0x1000
118 #define COMM_F                      0x0800
119 #define COMM_NTF                    0x0400
120 #define COMM_ICP                    0x0200
121 #define COMM_RST                    0x0100
122 
123 // Read Straight command, special bits
124 #define COMM_READ_STRAIGHT_NTF          0x0008
125 #define COMM_READ_STRAIGHT_ICP          0x0004
126 #define COMM_READ_STRAIGHT_RST          0x0002
127 #define COMM_READ_STRAIGHT_IM           0x0001
128 
129 //
130 // Value field COMM Command options (0-F plus assorted bits)
131 //
132 #define COMM_ERROR_ESCAPE               0x0601
133 #define COMM_SET_DURATION               0x0012
134 #define COMM_BIT_IO                     0x0020
135 #define COMM_PULSE                      0x0030
136 #define COMM_1_WIRE_RESET               0x0042
137 #define COMM_BYTE_IO                    0x0052
138 #define COMM_MATCH_ACCESS               0x0064
139 #define COMM_BLOCK_IO                   0x0074
140 #define COMM_READ_STRAIGHT              0x0080
141 #define COMM_DO_RELEASE                 0x6092
142 #define COMM_SET_PATH                   0x00A2
143 #define COMM_WRITE_SRAM_PAGE            0x00B2
144 #define COMM_WRITE_EPROM                0x00C4
145 #define COMM_READ_CRC_PROT_PAGE         0x00D4
146 #define COMM_READ_REDIRECT_PAGE_CRC     0x21E4
147 #define COMM_SEARCH_ACCESS              0x00F4
148 
149 // Mode Command Code Constants
150 // Enable Pulse Constants
151 #define ENABLEPULSE_PRGE         0x01	// programming pulse
152 #define ENABLEPULSE_SPUE         0x02	// strong pull-up
153 
154 // Define our combinations:
155 #define ENABLE_PROGRAM_ONLY         (ENABLEPULSE_PRGE)
156 #define ENABLE_PROGRAM_AND_PULSE    (ENABLEPULSE_PRGE | ENABLEPULSE_SPUE)
157 
158 
159 // 1Wire Bus Speed Setting Constants
160 #define ONEWIREBUSSPEED_REGULAR        0x00
161 #define ONEWIREBUSSPEED_FLEXIBLE       0x01
162 #define ONEWIREBUSSPEED_OVERDRIVE      0x02
163 
164 #define PARMSET_Slew15Vus   0x0
165 #define PARMSET_Slew2p20Vus 0x1
166 #define PARMSET_Slew1p65Vus 0x2
167 #define PARMSET_Slew1p37Vus 0x3
168 #define PARMSET_Slew1p10Vus 0x4
169 #define PARMSET_Slew0p83Vus 0x5
170 #define PARMSET_Slew0p70Vus 0x6
171 #define PARMSET_Slew0p55Vus 0x7
172 
173 #define PARMSET_W1L_04us 0x0
174 #define PARMSET_W1L_05us 0x1
175 #define PARMSET_W1L_06us 0x2
176 #define PARMSET_W1L_07us 0x3
177 #define PARMSET_W1L_08us 0x4
178 #define PARMSET_W1L_09us 0x5
179 #define PARMSET_W1L_10us 0x6
180 #define PARMSET_W1L_11us 0x7
181 
182 #define PARMSET_DS0_W0R_10us 0x0
183 #define PARMSET_DS0_W0R_12us 0x1
184 #define PARMSET_DS0_W0R_14us 0x2
185 #define PARMSET_DS0_W0R_16us 0x3
186 #define PARMSET_DS0_W0R_18us 0x4
187 #define PARMSET_DS0_W0R_20us 0x5
188 #define PARMSET_DS0_W0R_22us 0x6
189 #define PARMSET_DS0_W0R_24us 0x7
190 
191 /* From datasheet http://datasheets.maxim-ic.com/en/ds/DS2490.pdf page 15 */
192 /* 480 usec = 8usec * 60 and 60(decimal) = 0x3C */
193 /* 480 usec is the recommended program pulse duration in the DS2406 DS2502 DS2505 datasheets */
194 #define PROGRAM_PULSE_DURATION_CODE	0x3C
195 
196 /* ------------------------------------------------------------ */
197 /* --- USB detection routines ----------------------------------*/
198 
199 /* Main routine for detecting (and setting up) the DS2490 1-wire USB chip */
DS9490_detect(struct port_in * pin)200 GOOD_OR_BAD DS9490_detect(struct port_in *pin)
201 {
202 	struct connection_in * in = pin->first ;
203 	struct address_pair ap ;
204 	GOOD_OR_BAD gbResult = gbBAD;
205 
206 	DS9490_setroutines(in);
207 
208 	if ( in->master.usb.lusb_dev != NULL ) {
209 		// special case: exists (from scan)
210 		return DS9490_open_and_name( in->master.usb.lusb_dev, in ) ;
211 		// Note DS9490_ID_this_master needs to be called,
212 		// but the bus hasn't yet been added.
213 		// So it's done in USB_scan_for_adapters
214 	}
215 
216 	/* uses "name" before it's cleared by connection_init */
217 	Parse_Address( pin->init_data, &ap ) ;
218 
219 	switch ( ap.entries ) {
220 		case 0:
221 			// Minimal specification, so use first USB device
222 			gbResult = DS9490_detect_single_adapter( 1, in) ;
223 			break ;
224 		case 1:
225 			switch( ap.first.type ) {
226 				case address_all:
227 				case address_asterix:
228 					LEVEL_DEBUG("Look for all USB adapters");
229 					gbResult = DS9490_detect_all_adapters(pin) ;
230 					break ;
231 				case address_numeric:
232 					LEVEL_DEBUG("Look for USB adapter number %d",ap.first.number);
233 					gbResult = DS9490_detect_single_adapter( ap.first.number, in) ;
234 					break ;
235 				case address_scan:
236 					// completely change personality!
237 					gbResult = USB_monitor_detect(pin) ;
238 					break ;
239 				default:
240 					LEVEL_DEFAULT("Unclear what <%s> means in USB specification, will use first adapter.",ap.first.alpha) ;
241 					gbResult = DS9490_detect_single_adapter( 1, in) ;
242 					break ;
243 			}
244 			break ;
245 		case 2:
246 			switch( ap.first.type ) {
247 				case address_all:
248 				case address_asterix:
249 					LEVEL_DEBUG("Look for all USB adapters");
250 					gbResult = DS9490_detect_all_adapters(pin) ;
251 					break ;
252 				case address_numeric:
253 					LEVEL_DEBUG("Look for USB adapter number %d:%d",ap.first.number,ap.second.number);
254 					gbResult = DS9490_detect_specific_adapter( ap.first.number, ap.second.number, in ) ;
255 					break ;
256 				case address_scan:
257 					// completely change personality!
258 					gbResult = USB_monitor_detect(pin) ;
259 					break ;
260 				default:
261 					LEVEL_DEFAULT("USB address <%s:%s> not in number:number format",ap.first.alpha,ap.second.alpha) ;
262 					gbResult = gbBAD ;
263 					break ;
264 			}
265 			break ;
266 	}
267 
268 	Free_Address( &ap ) ;
269 	return gbResult;
270 }
271 
272 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_detect_single_adapter(int usb_nr,struct connection_in * in)273 static GOOD_OR_BAD DS9490_detect_single_adapter(int usb_nr, struct connection_in * in)
274 {
275 	// discover devices
276 	libusb_device **device_list;
277 	int n_devices = libusb_get_device_list( Globals.luc, &device_list) ;
278 	int i_device ;
279 
280 	if ( n_devices < 1 ) {
281 		LEVEL_CONNECT("Could not find a list of USB devices");
282 		if ( n_devices<0 ) {
283 			LEVEL_DEBUG("<%s>",libusb_error_name(n_devices));
284 		}
285 		return gbBAD ;
286 	}
287 
288 	for ( i_device = 0 ; i_device < n_devices ; ++i_device ) {
289 		libusb_device * current = device_list[i_device] ;
290 		if ( GOOD( USB_match( current ) ) ) {
291 			--usb_nr ;
292 			if ( usb_nr > 0 ) {
293 				continue ;
294 			}
295 
296 			if ( BAD(DS9490_open_and_name( current, in)) ) {
297 				LEVEL_DEBUG("Cannot open USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
298 				break ;
299 			} else if ( BAD(DS9490_ID_this_master(in)) ) {
300 				DS9490_close(in) ;
301 				LEVEL_DEBUG("Cannot access USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
302 				break ;
303 			} else{
304 				libusb_free_device_list(device_list, 1);
305 				return gbGOOD ;
306 			}
307 		}
308 	}
309 
310 	libusb_free_device_list(device_list, 1);
311 
312 	LEVEL_CONNECT("No USB DS9490 bus master found");
313 	return gbBAD;
314 }
315 
316 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_detect_specific_adapter(int bus_nr,int dev_nr,struct connection_in * in)317 static GOOD_OR_BAD DS9490_detect_specific_adapter(int bus_nr, int dev_nr, struct connection_in * in)
318 {
319 	// discover devices
320 	libusb_device **device_list;
321 	int n_devices = libusb_get_device_list( Globals.luc, &device_list) ;
322 	int i_device ;
323 
324 	if ( n_devices < 1 ) {
325 		LEVEL_CONNECT("Could not find a list of USB devices");
326 		if ( n_devices<0 ) {
327 			LEVEL_DEBUG("<%s>",libusb_error_name(n_devices));
328 		}
329 		return gbBAD ;
330 	}
331 
332 	// Mark this connection as taking only this address pair. Important for reconnections.
333 	in->master.usb.specific_usb_address = 1 ;
334 
335 	for ( i_device = 0 ; i_device < n_devices ; ++i_device ) {
336 		libusb_device * current = device_list[i_device] ;
337 		if ( GOOD( USB_match( current ) ) ) {
338 			if ( libusb_get_bus_number(current) != bus_nr ) {
339 				continue ;
340 			}
341 
342 			if ( libusb_get_device_address(current) != dev_nr ) {
343 				continue ;
344 			}
345 
346 			if ( BAD(DS9490_open_and_name( current, in)) ) {
347 				LEVEL_DEBUG("Cannot open USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
348 				break ;
349 			} else if ( BAD(DS9490_ID_this_master(in)) ) {
350 				DS9490_close(in) ;
351 				LEVEL_DEBUG("Cannot access USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
352 				break ;
353 			} else{
354 				libusb_free_device_list(device_list, 1);
355 				return gbGOOD ;
356 			}
357 		}
358 	}
359 
360 	libusb_free_device_list(device_list, 1);
361 
362 	LEVEL_CONNECT("No USB DS9490 bus master found matching %d:%d", bus_nr,dev_nr);
363 	return gbBAD;
364 }
365 
366 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_detect_all_adapters(struct port_in * pin_first)367 static GOOD_OR_BAD DS9490_detect_all_adapters(struct port_in * pin_first)
368 {
369 	// discover devices
370 	struct port_in * pin = pin_first ;
371 	libusb_device **device_list;
372 	int n_devices = libusb_get_device_list( Globals.luc, &device_list) ;
373 	int i_device ;
374 
375 	if ( n_devices < 1 ) {
376 		LEVEL_CONNECT("Could not find a list of USB devices");
377 		if ( n_devices<0 ) {
378 			LEVEL_DEBUG("<%s>",libusb_error_name(n_devices));
379 		}
380 		return gbBAD ;
381 	}
382 
383 	for ( i_device = 0 ; i_device < n_devices ; ++i_device ) {
384 		libusb_device * current = device_list[i_device] ;
385 		if ( GOOD( USB_match( current ) ) ) {
386 			struct connection_in * in = pin->first ;
387 			if ( BAD(DS9490_open_and_name( current, in)) ) {
388 				LEVEL_DEBUG("Cannot open USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
389 				continue ;
390 			} else if ( BAD(DS9490_ID_this_master(in)) ) {
391 				DS9490_close(in) ;
392 				LEVEL_DEBUG("Cannot access USB device %.d:%.d", libusb_get_device_address(current), libusb_get_bus_number(current) );
393 				continue;
394 			} else{
395 				pin = NewPort(NULL) ; // no reason to copy anything
396 				if ( pin == NULL ) {
397 					return gbGOOD ;
398 				}
399 				// set up the new connection for the next adapter
400 				DS9490_setroutines(in);
401 			}
402 		}
403 	}
404 
405 	libusb_free_device_list(device_list, 1);
406 
407 	if ( pin == pin_first ) {
408 		LEVEL_CONNECT("No USB DS9490 bus masters used");
409 		return gbBAD;
410 	}
411 	// Remove the extra connection
412 	RemovePort(pin);
413 	return gbGOOD ;
414 }
415 
416 /* ------------------------------------------------------------ */
417 /* --- USB redetect routines -----------------------------------*/
418 
419 /* When the errors stop the USB device from functioning -- close and reopen.
420  * If it fails, re-scan the USB bus and search for the old adapter */
DS9490_reconnect(const struct parsedname * pn)421 static GOOD_OR_BAD DS9490_reconnect(const struct parsedname *pn)
422 {
423 	GOOD_OR_BAD ret;
424 	struct connection_in * in = pn->selected_connection ;
425 
426 	if ( in->master.usb.specific_usb_address ) {
427 		// special case where a usb bus:dev pair was given
428 		// only connect to the same spot
429 		return DS9490_redetect_specific_adapter( in ) ;
430 	}
431 
432 	/* Have to protect usb_find_busses() and usb_find_devices() with
433 	 * a lock since libusb could crash if 2 threads call it at the same time.
434 	 * It's not called until DS9490_redetect_low(), but I lock here just
435 	 * to be sure DS9490_close() and DS9490_open() get one try first. */
436 	LIBUSBLOCK;
437 	DS9490_close( in ) ;
438 	ret = DS9490_redetect_low(in) ;
439 	LIBUSBUNLOCK;
440 
441 	if ( GOOD(ret) ) {
442 		LEVEL_DEFAULT("Found USB DS9490 bus master after USB rescan as [%s]", SAFESTRING(DEVICENAME(in)));
443 	}
444 	return ret;
445 }
446 
447 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_redetect_low(struct connection_in * in)448 static GOOD_OR_BAD DS9490_redetect_low(struct connection_in * in)
449 {
450 	// discover devices
451 	libusb_device **device_list;
452 	int n_devices = libusb_get_device_list( Globals.luc, &device_list) ;
453 	int i_device ;
454 
455 	if ( n_devices < 1 ) {
456 		LEVEL_CONNECT("Could not find a list of USB devices");
457 		if ( n_devices<0 ) {
458 			LEVEL_DEBUG("<%s>",libusb_error_name(n_devices));
459 		}
460 		return gbBAD;
461 	}
462 
463 	for ( i_device = 0 ; i_device < n_devices ; ++i_device ) {
464 		libusb_device * current = device_list[i_device] ;
465 		if ( GOOD( USB_match( current ) ) ) {
466 			// try to open the DS9490
467 			if ( BAD(DS9490_open_and_name( current, in )) ) {
468 				LEVEL_CONNECT("Cannot open USB bus master, Find next...");
469 				continue;
470 			}
471 			if ( GOOD( DS9490_redetect_match( in ) ) ) {
472 				break ;
473 			}
474 			DS9490_close(in);
475 		}
476 	}
477 
478 	libusb_free_device_list(device_list, 1);
479 	return (in->master.usb.lusb_handle!=NULL) ? gbGOOD : gbBAD ;
480 }
481 
482 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_redetect_specific_adapter(struct connection_in * in)483 static GOOD_OR_BAD DS9490_redetect_specific_adapter( struct connection_in * in)
484 {
485 	struct address_pair ap ;
486 	GOOD_OR_BAD gbResult ;
487 
488 	Parse_Address( in->pown->init_data, &ap ) ;
489 	if ( ap.first.type != address_numeric || ap.second.type != address_numeric ) {
490 		LEVEL_DEBUG("Cannot understand the specific usb address pair to reconnect <%s>",in->pown->init_data) ;
491 		gbResult = gbBAD ;
492 	} else {
493 		/* Have to protect usb_find_busses() and usb_find_devices() with
494 		 * a lock since libusb could crash if 2 threads call it at the same time.
495 		 * It's not called until DS9490_redetect_low(), but I lock here just
496 		 * to be sure DS9490_close() and DS9490_open() get one try first. */
497 		LIBUSBLOCK;
498 		DS9490_close( in ) ;
499 		gbResult = DS9490_detect_specific_adapter( ap.first.number, ap.second.number, in) ;
500 		LIBUSBUNLOCK;
501 	}
502 
503 	Free_Address( &ap ) ;
504 	return gbResult ;
505 }
506 
507 /* Open a DS9490  -- low level code (to allow for repeats)  */
DS9490_redetect_match(struct connection_in * in)508 static GOOD_OR_BAD DS9490_redetect_match( struct connection_in * in)
509 {
510 	struct dirblob db ;
511 	BYTE sn[SERIAL_NUMBER_SIZE] ;
512 	int device_number ;
513 
514 	LEVEL_DEBUG("Attempting reconnect on %s",SAFESTRING(DEVICENAME(in)));
515 
516 	// Special case -- originally untagged adapter
517 	if ( in->master.usb.ds1420_address[0] == '\0' ) {
518 		LEVEL_CONNECT("Since originally untagged bus master, we will use first available slot.");
519 		return gbGOOD ;
520 	}
521 
522 	// Generate a root directory
523 	RETURN_BAD_IF_BAD( DS9490_root_dir( &db, in ) ) ;
524 
525 	// This adapter has no tags, so not the one we want
526 	if ( DirblobElements( &db) == 0 ) {
527 		DirblobClear( &db ) ;
528 		LEVEL_DATA("Empty directory on [%s] (Doesn't match initial scan).", SAFESTRING(DEVICENAME(in)));
529 		return gbBAD ;
530 	}
531 
532 	// Scan directory for a match to the original tag
533 	device_number = 0 ;
534 	while ( DirblobGet( device_number, sn, &db ) == 0 ) {
535 		if (memcmp(sn, in->master.usb.ds1420_address, SERIAL_NUMBER_SIZE) == 0) {	// same tag device?
536 			LEVEL_DATA("Matching device [%s].", SAFESTRING(DEVICENAME(in)));
537 			DirblobClear( &db ) ;
538 			return gbGOOD ;
539 		}
540 		++device_number ;
541 	}
542 	// Couldn't find correct ds1420 chip on this adapter
543 	LEVEL_CONNECT("Couldn't find correct ds1420 chip on this bus master [%s] (want: " SNformat ")", SAFESTRING(DEVICENAME(in)), SNvar(in->master.usb.ds1420_address));
544 	DirblobClear( &db ) ;
545 	return gbBAD;
546 }
547 
548 /* ------------------------------------------------------------ */
549 /* --- USB reset routines --------------------------------------*/
550 
551 /* Reset adapter and detect devices on the bus */
552 /* BUS locked at high level */
553 /* return 1=short, 0 good <0 error */
DS9490_reset(const struct parsedname * pn)554 static RESET_TYPE DS9490_reset(const struct parsedname *pn)
555 {
556 	int i;
557 	BYTE buffer[ DS9490_getstatus_BUFFER_LENGTH + 1 ];
558 	int USpeed;
559 	struct connection_in * in = pn->selected_connection ;
560 	int readlen = 0 ;
561 
562 	LEVEL_DEBUG("DS9490 RESET. changed %d, flex: %d", in->changed_bus_settings, in->flex) ;
563 
564 	if (in->master.usb.lusb_dev == NULL || in->master.usb.lusb_handle == NULL) {
565 		// From Michael Markstaller:
566 		LEVEL_DEBUG("Attempting RESET on null bus") ;
567 		//FIXME! what doees it mean? no action/reconnect is even tried-> shouldn't we just drop this BM and let uscan rediscover it? DS9490 must always have an ID chip..
568 		// Actually no, the home-brewed DS2490-based masters that people have built have no ID chip
569 		BUS_ERROR_fix(pn) ;
570 		return BUS_RESET_ERROR;
571 	}
572 
573 	// Do we need to change settings?
574 	if (in->changed_bus_settings > 0) {
575 		// Prevent recursive loops on reset
576 		DS9490_SetSpeed(pn);	// reset paramters
577 		in->changed_bus_settings = 0 ;
578 	}
579 
580 	memset(buffer, 0, 32);
581 
582 	// Bus timing
583 	if ( in->overdrive ) {
584 		USpeed = ONEWIREBUSSPEED_OVERDRIVE ;
585 	} else if ( in->flex ) {
586 		USpeed = ONEWIREBUSSPEED_FLEXIBLE ;
587 	} else {
588 		USpeed = ONEWIREBUSSPEED_REGULAR ;
589 	}
590 
591 	// Send reset
592 	//FIXME: from Michael Markstaller: changed hard to flexible speed as it gets wrong somewhere, only want flexible
593 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_1_WIRE_RESET | COMM_F | COMM_IM | COMM_SE, USpeed, pn)) ) {
594 //	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_1_WIRE_RESET | COMM_F | COMM_IM | COMM_SE, ONEWIREBUSSPEED_FLEXIBLE, pn)) ) {
595 		LEVEL_DATA("Reset command rejected");
596 		BUS_ERROR_fix(pn) ;
597 		return BUS_RESET_ERROR;			// fatal error... probably closed usb-handle
598 	}
599 
600 	// Extra delay?
601 	if (in->ds2404_found && (in->overdrive == 0)) {
602 		// extra delay for alarming DS1994/DS2404 compliance
603 		UT_delay(5);
604 	}
605 
606 	// Read response
607 	switch( DS9490_getstatus(buffer, &readlen, pn) ) {
608 		case BUS_RESET_SHORT:
609 			/* Short detected, but otherwise no bigger problem */
610 			LEVEL_DEBUG("DS9490_Reset: SHORT");
611 			return BUS_RESET_SHORT ;
612 		case BUS_RESET_OK:
613 			LEVEL_DEBUG("DS9490_Reset: OK");
614 			break ;
615 		case BUS_RESET_ERROR:
616 		default:
617 			LEVEL_DEBUG("DS9490_Reset: ERROR");
618 			BUS_ERROR_fix(pn) ;
619 			return BUS_RESET_ERROR;
620 	}
621 	//USBpowered = (buffer[8]&STATUSFLAGS_PMOD) == STATUSFLAGS_PMOD ;
622 	in->AnyDevices = anydevices_yes ;
623 	for (i = 16; i < readlen; i++) {
624 		BYTE val = buffer[i];
625 		LEVEL_DEBUG("Reset: Status bytes[%d]: %X", i, val);
626 		if (val != ONEWIREDEVICEDETECT) {
627 			// check for NRS bit (0x01)
628 			if (val & COMMCMDERRORRESULT_NRS) {
629 				// empty bus detected, no presence pulse detected
630 				in->AnyDevices = anydevices_no;
631 				LEVEL_DATA("no presence pulse detected");
632 			}
633 		}
634 	}
635 	return BUS_RESET_OK;
636 }
637 
BUS_ERROR_fix(const struct parsedname * pn)638 static void BUS_ERROR_fix(const struct parsedname *pn)
639 {
640 	LEVEL_DEBUG("DS9490_Reset: ERROR -- will attempt a fix");
641 	/* FIXME: FIXED. In ow_usb_msg.c an USB-reset was was issued:
642 	* USB_Control_Msg(CONTROL_CMD, CTL_RESET_DEVICE, 0x0000, pn) ;
643 	* So we need to setup the Adapter again
644 	* Though here is probably the wrong place, duplicated code from _setup_adaptor
645 	*/
646 
647 	// enable both program and strong pulses
648 	if ( BAD( USB_Control_Msg(MODE_CMD, MOD_PULSE_EN, ENABLE_PROGRAM_AND_PULSE, pn)) ) {
649 		LEVEL_DATA("EnableProgram error");
650 	}
651 	// enable speed changes
652 	if ( BAD( USB_Control_Msg(MODE_CMD, MOD_SPEED_CHANGE_EN, 1, pn)) ) {
653 		LEVEL_DATA("RESET_Error: SpeedEnable error");
654 	}
655 	// set the strong pullup duration to infinite
656 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_SET_DURATION | COMM_IM, 0x0000, pn)) ) {
657 		LEVEL_DATA("StrongPullup error");
658 	}
659 
660 	// Don't set speed right now, it calls reset for infinite recursion. Just set for next pass
661 	++ 	pn->selected_connection->changed_bus_settings ;
662 }
663 
664 
665 /* ------------------------------------------------------------ */
666 /* --- USB Directory functions  --------------------------------*/
667 
DS9490_next_both(struct device_search * ds,const struct parsedname * pn)668 static enum search_status DS9490_next_both(struct device_search *ds, const struct parsedname *pn)
669 {
670 	int dir_gulp_elements = (pn->ds2409_depth==0) ? DS2490_DIR_GULP_ELEMENTS : 1 ;
671 
672 	// LOOK FOR NEXT ELEMENT
673 	++ds->index;
674 	LEVEL_DEBUG("Index %d", ds->index);
675 
676 	if (ds->index % dir_gulp_elements == 0) {
677 		if (ds->LastDevice) {
678 			return search_done;
679 		}
680 		switch ( DS9490_directory(ds, pn) ) {
681 			case search_done:
682 				return search_done;
683 			case search_error:
684 				return search_error;
685 			case search_good:
686 				break;
687 		}
688 	}
689 
690 	switch ( DirblobGet(ds->index % dir_gulp_elements, ds->sn, &(ds->gulp) ) ) {
691 		case 0:
692 			LEVEL_DEBUG("SN found: " SNformat, SNvar(ds->sn));
693 			return search_good;
694 		case -ENODEV:
695 		default:
696 			LEVEL_DEBUG("SN finished");
697 			return search_done;
698 	}
699 }
700 
701 // Read up to 7 (DS2490_DIR_GULP_ELEMENTS) at a time, and  place into
702 // a dirblob. Called from DS9490_next_both every 7 devices to fill.
DS9490_directory(struct device_search * ds,const struct parsedname * pn)703 static enum search_status DS9490_directory(struct device_search *ds, const struct parsedname *pn)
704 {
705 	BYTE status_buffer[ DS9490_getstatus_BUFFER_LENGTH + 1 ];
706 	BYTE EP2_data[SERIAL_NUMBER_SIZE] ; //USB endpoint 3 buffer
707 	union {
708 		BYTE b[DS2490_BULK_BUFFER_SIZE] ;
709 		BYTE sn[DS2490_BULK_BUFFER_SIZE/SERIAL_NUMBER_SIZE][SERIAL_NUMBER_SIZE];
710 	} EP3 ; //USB endpoint 3 buffer
711 	SIZE_OR_ERROR ret;
712 	int bytes_back;
713 	int devices_found;
714 	int device_index;
715 	int dir_gulp_elements = (pn->ds2409_depth==0) ? DS2490_DIR_GULP_ELEMENTS : 1 ;
716 	int readlen = 0 ;
717 
718 	DirblobClear(&(ds->gulp));
719 
720 	if ( BAD( BUS_select(pn) ) ) {
721 		LEVEL_DEBUG("Selection problem before a directory listing") ;
722 		return search_error ;
723 	}
724 
725 	if ( pn->selected_connection->AnyDevices == anydevices_no ) {
726 		// empty bus detected, no presence pulse detected
727 		return search_done ;
728 	}
729 
730 	SetupDiscrepancy(ds, EP2_data);
731 
732 	// set the search start location
733 	ret = DS9490_write(EP2_data, SERIAL_NUMBER_SIZE, pn) ;
734 	if ( ret < SERIAL_NUMBER_SIZE ) {
735 		LEVEL_DATA("bulk write problem = %d", ret);
736 		return search_error;
737 	}
738 	// Send the search request
739 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_SEARCH_ACCESS | COMM_IM | COMM_SM | COMM_F | COMM_RTS, (dir_gulp_elements << 8) | (ds->search), pn) ) ) {
740 		LEVEL_DATA("control error");
741 		return search_error;
742 	}
743 	// read the search status
744 	if ( DS9490_getstatus(status_buffer, &readlen, pn)  != BUS_RESET_OK ) {
745 		return search_error;
746 	}
747 
748 	// test the buffer size waiting for us
749 	bytes_back = status_buffer[13];
750 	LEVEL_DEBUG("Got %d bytes from USB search", bytes_back);
751 	if (bytes_back == 0) {
752 		/* Nothing found on the bus. Have to return something != search_good to avoid
753 		 * getting stuck in loop in FS_realdir() and FS_alarmdir()
754 		 * which ends when ret!=search_good */
755 		LEVEL_DATA("ReadBufferstatus == 0");
756 		return search_done;
757 	} else if ( bytes_back % SERIAL_NUMBER_SIZE != 0 ) {
758 		LEVEL_DATA("ReadBufferstatus size %d not a multiple of %d", bytes_back,SERIAL_NUMBER_SIZE);
759 		return search_error;
760 	} else if ( bytes_back > (dir_gulp_elements + 1) * SERIAL_NUMBER_SIZE ) {
761 		LEVEL_DATA("ReadBufferstatus size %d too large", bytes_back);
762 		return search_error;
763 	}
764 	devices_found = bytes_back / SERIAL_NUMBER_SIZE;
765 	if (devices_found > dir_gulp_elements) {
766 		devices_found = dir_gulp_elements;
767 	}
768 
769 	// read in the buffer that holds the devices found
770 	if ((ret = DS9490_read(EP3.b, bytes_back, pn)) <= 0) {
771 		LEVEL_DATA("bulk read problem ret=%d", ret);
772 		return search_error;
773 	}
774 
775 	// analyze each device found
776 	for (device_index = 0; device_index < devices_found; ++device_index) {
777 		/* test for CRC error */
778 		LEVEL_DEBUG("gulp. Adding element %d:" SNformat, device_index, SNvar(EP3.sn[device_index]));
779 		if (CRC8(EP3.sn[device_index], SERIAL_NUMBER_SIZE) != 0 || EP3.sn[device_index][0] == 0) {
780 			LEVEL_DATA("CRC error");
781 			return search_error;
782 		}
783 	}
784 	// all ok, so add the devices
785 	for (device_index = 0; device_index < devices_found; ++device_index) {
786 		DirblobAdd(EP3.sn[device_index], &(ds->gulp));
787 	}
788 	ds->LastDiscrepancy = FindDiscrepancy(EP3.sn[devices_found-1], EP3.sn[devices_found]);
789 	ds->LastDevice = (bytes_back == devices_found * SERIAL_NUMBER_SIZE);	// no more to read
790 
791 	return search_good;
792 }
793 
SetupDiscrepancy(const struct device_search * ds,BYTE * discrepancy)794 static void SetupDiscrepancy(const struct device_search *ds, BYTE * discrepancy)
795 {
796 	int i;
797 
798 	/** Play LastDescrepancy games with bitstream */
799 	memcpy(discrepancy, ds->sn, SERIAL_NUMBER_SIZE);	/* set buffer to zeros */
800 
801 	if (ds->LastDiscrepancy > -1) {
802 		UT_setbit(discrepancy, ds->LastDiscrepancy, 1);
803 	}
804 
805 	/* This could be more efficiently done than bit-setting, but probably wouldn't make a difference */
806 	for (i = ds->LastDiscrepancy + 1; i < 64; i++) {
807 		UT_setbit(discrepancy, i, 0);
808 	}
809 }
810 
FindDiscrepancy(BYTE * last_sn,BYTE * discrepancy_sn)811 static int FindDiscrepancy(BYTE * last_sn, BYTE * discrepancy_sn)
812 {
813 	int i;
814 	for (i = 63; i >= 0; i--) {
815 		if ((UT_getbit(discrepancy_sn, i) != 0)
816 			&& (UT_getbit(last_sn, i) == 0)) {
817 			return i;
818 		}
819 	}
820 	return 0;
821 }
822 
823 /* ------------------------------------------------------------ */
824 /* --- USB Open and Close --------------------------------------*/
825 
826 // Open usb device,
827 // dev already set
DS9490_open_and_name(libusb_device * dev,struct connection_in * in)828 static GOOD_OR_BAD DS9490_open_and_name( libusb_device * dev, struct connection_in *in)
829 {
830 	if (in->master.usb.lusb_handle != NULL) {
831 		LEVEL_DEFAULT("DS9490 %s was NOT closed?", DEVICENAME(in));
832 		return gbBAD ;
833 	}
834 
835 	DS9490_port_setup( dev, in->pown ) ;
836 
837 	if ( BAD( DS9490_open( in ) ) ) {
838 		STAT_ADD1_BUS(e_bus_open_errors, in);
839 		return gbBAD ;
840 	} else if ( BAD( DS9490_setup_adapter(in)) ) {
841 		LEVEL_DEFAULT("Error setting up USB DS9490 bus master at %s.", DEVICENAME(in));
842 		DS9490_close( in ) ;
843 		return gbBAD ;
844 	}
845 	DS9490_SetFlexParameters(in);
846 
847 	return gbGOOD ;
848 }
849 
850 /* ------------------------------------------------------------ */
851 /* --- USB read and write --------------------------------------*/
852 
DS9490_sendback_data(const BYTE * const_data,BYTE * resp,size_t len,const struct parsedname * pn)853 static GOOD_OR_BAD DS9490_sendback_data(const BYTE * const_data, BYTE * resp, size_t len, const struct parsedname *pn)
854 {
855 	size_t location = 0 ;
856 	BYTE data[len] ; // to avoid const problem
857 
858 	memcpy( data, const_data, len ) ;
859 
860 	while ( location < len ) {
861 		BYTE buffer[ DS9490_getstatus_BUFFER_LENGTH + 1 ];
862 		int readlen ;
863 
864 		size_t block = len - location ;
865 		if ( block > USB_FIFO_EACH ) {
866 			block = USB_FIFO_EACH ;
867 		}
868 
869 		if ( DS9490_write( &data[location], block, pn) < (int) block) {
870 			LEVEL_DATA("USBsendback bulk write problem");
871 			return gbBAD;
872 		}
873 
874 		// COMM_BLOCK_IO | COMM_IM | COMM_F == 0x0075
875 		readlen = block ;
876 		if (( BAD( USB_Control_Msg(COMM_CMD, COMM_BLOCK_IO | COMM_IM | COMM_F, block, pn)) )
877 			|| ( DS9490_getstatus(buffer, &readlen, pn)  != BUS_RESET_OK )	// wait for len bytes
878 			) {
879 			LEVEL_DATA("USBsendback control error");
880 			STAT_ADD1_BUS(e_bus_errors, pn->selected_connection);
881 			return gbBAD;
882 		}
883 
884 		if ( DS9490_read( &resp[location], block, pn) < 0) {
885 			LEVEL_DATA("USBsendback bulk read error");
886 			return gbBAD;
887 		}
888 
889 		location += block ;
890 	}
891 	return gbGOOD;
892 }
893 
894 
895 /* ------------------------------------------------------------ */
896 /* --- USB Power byte for temperature conversion ---------------*/
897 
898 // Send 8 bits of communication to the 1-Wire Net and read the
899 // 8 bits back from the 1-Wire Net.
900 // The parameter 'byte' least significant 8 bits are used.  After the
901 // 8 bits are sent change the level of the 1-Wire net.
902 // Delay delay msec and return to normal
DS9490_PowerByte(BYTE byte,BYTE * resp,UINT delay,const struct parsedname * pn)903 static GOOD_OR_BAD DS9490_PowerByte(BYTE byte, BYTE * resp, UINT delay, const struct parsedname *pn)
904 {
905 	LEVEL_DATA("DS9490_PowerByte start");
906 
907 	/* This is more likely to be the correct way to handle powerbytes */
908 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_BYTE_IO | COMM_IM | COMM_SPU, byte & 0xFF, pn)) ) {
909 		DS9490_HaltPulse(pn);
910 		return gbBAD ;
911 	} else if ( DS9490_read(resp, 1, pn) < 0) {
912 		/* Read back the result (may be the same as "byte") */
913 		DS9490_HaltPulse(pn);
914 		return gbBAD ;
915 	}
916 	/* Delay with strong pullup */
917 	LEVEL_DEBUG("DS9490_PowerByte DELAY:%d", delay);
918 	UT_delay(delay);
919 	DS9490_HaltPulse(pn);
920 	return gbGOOD ;
921 }
922 
923 /* ------------------------------------------------------------ */
924 /* --- USB Program Pulse ---------------------------------------*/
925 
DS9490_ProgramPulse(const struct parsedname * pn)926 static GOOD_OR_BAD DS9490_ProgramPulse(const struct parsedname *pn)
927 {
928 	GOOD_OR_BAD ret;
929 
930 	// set pullup to strong5 or program
931 	// set the strong pullup duration to infinite
932 	ret = USB_Control_Msg(COMM_CMD, COMM_PULSE | COMM_TYPE | COMM_IM, 0, pn);
933 	if ( GOOD(ret) ) {
934 		UT_delay_us(520);		// 520 usec (480 usec would be enough)
935 	}
936 
937 	if ( BAD(DS9490_HaltPulse(pn)) ) {
938 		LEVEL_DEBUG("Couldn't reset the program pulse level back to normal");
939 		return gbBAD;
940 	}
941 	return ret ;
942 }
943 
DS9490_HaltPulse(const struct parsedname * pn)944 static GOOD_OR_BAD DS9490_HaltPulse(const struct parsedname *pn)
945 {
946 	BYTE buffer[ DS9490_getstatus_BUFFER_LENGTH + 1 ];
947 	struct timeval tv;
948 	struct timeval tvtarget;
949 	struct timeval tvlimit = { 0, 300000 } ; // 300 millisec from PDKit /ib/other/libUSB/libusbds2490.c
950 
951 	if ( timernow( &tv ) < 0) {
952 		return gbBAD;
953 	}
954 	timeradd( &tv, &tvlimit, &tvtarget ) ;
955 
956 	do {
957 		int readlen = -1 ;
958 
959 		if ( BAD(USB_Control_Msg(CONTROL_CMD, CTL_HALT_EXE_IDLE, 0, pn)) ) {
960 			break;
961 		}
962 		if ( BAD(USB_Control_Msg(CONTROL_CMD, CTL_RESUME_EXE, 0, pn)) ) {
963 			break;
964 		}
965 
966 		/* Can't wait for STATUSFLAGS_IDLE... just get first availalbe status flag */
967 		if ( DS9490_getstatus(buffer, &readlen, pn) != BUS_RESET_OK ) {
968 			break;
969 		}
970 		// check the SPU flag
971 		if (!(buffer[8] & STATUSFLAGS_SPUA)) {
972 			return gbGOOD;
973 		}
974 		if ( timernow( &tv ) < 0) {
975 			return gbBAD;
976 		}
977 	} while ( timercmp( &tv, &tvtarget, >) ) ;
978 	LEVEL_DATA("DS9490_HaltPulse timeout");
979 	return gbBAD;
980 }
981 
982 /* ------------------------------------------------------------ */
983 /* --- USB Various Parameters ----------------------------------*/
984 
DS9490_SetSpeed(const struct parsedname * pn)985 static GOOD_OR_BAD DS9490_SetSpeed(const struct parsedname *pn)
986 {
987 	struct connection_in * in = pn->selected_connection ;
988 	int ret = 0;
989 
990 	// in case timeout value changed (via settings) -- sec -> msec
991 	in->master.usb.timeout = 1000 * Globals.timeout_usb;
992 
993 	// Failed overdrive, switch to slow
994 
995 	if (in->changed_bus_settings | CHANGED_USB_SPEED) {
996 		in->changed_bus_settings ^= CHANGED_USB_SPEED ;
997 		if (in->overdrive) {
998 			if ( BAD(DS9490_overdrive(pn)) ) {
999 				++ ret;
1000 				in->overdrive = 0 ;
1001 			} else {
1002 				LEVEL_DATA("set overdrive speed");
1003 			}
1004 		} else if ( in->flex ) {
1005 			if ( BAD(USB_Control_Msg(MODE_CMD, MOD_1WIRE_SPEED, ONEWIREBUSSPEED_FLEXIBLE, pn)) ) {
1006 				++ ret;
1007 			} else {
1008 				LEVEL_DATA("set flexible speed");
1009 			}
1010 		} else {
1011 			if ( BAD(USB_Control_Msg(MODE_CMD, MOD_1WIRE_SPEED, ONEWIREBUSSPEED_REGULAR, pn)) ) {
1012 				++ ret;
1013 			} else {
1014 				LEVEL_DATA("set regular speed");
1015 			}
1016 		}
1017 	}
1018 	if (in->changed_bus_settings | CHANGED_USB_SLEW) {
1019 		in->changed_bus_settings ^= CHANGED_USB_SLEW ;
1020 		/* Slew Rate */
1021 		if ( BAD(USB_Control_Msg(MODE_CMD, MOD_PULLDOWN_SLEWRATE, in->master.usb.pulldownslewrate, pn)) ) {
1022 			LEVEL_DATA("MOD_PULLDOWN_SLEWRATE error");
1023 			++ret;
1024 		}
1025 	}
1026 	if (in->changed_bus_settings | CHANGED_USB_LOW) {
1027 		in->changed_bus_settings ^= CHANGED_USB_LOW ;
1028 		/* Low Time */
1029 		if ( BAD(USB_Control_Msg(MODE_CMD, MOD_WRITE1_LOWTIME, in->master.usb.writeonelowtime, pn)) ) {
1030 			LEVEL_DATA("MOD_WRITE1_LOWTIME error");
1031 			++ret;
1032 		}
1033 	}
1034 	if (in->changed_bus_settings | CHANGED_USB_OFFSET) {
1035 		in->changed_bus_settings ^= CHANGED_USB_OFFSET ;
1036 		/* DS0 Low */
1037 		if ( BAD(USB_Control_Msg(MODE_CMD, MOD_DSOW0_TREC, in->master.usb.datasampleoffset, pn)) ) {
1038 			LEVEL_DATA("MOD_DS0W0 error");
1039 			++ret;
1040 		}
1041 	}
1042 	return ret>0 ? gbBAD : gbGOOD;
1043 }
1044 
1045 // Switch to overdrive speed -- 3 tries
DS9490_overdrive(const struct parsedname * pn)1046 static GOOD_OR_BAD DS9490_overdrive(const struct parsedname *pn)
1047 {
1048 	BYTE sp = _1W_OVERDRIVE_SKIP_ROM;
1049 	BYTE resp = 0;
1050 	int i;
1051 
1052 	// we need to change speed to overdrive
1053 	for (i = 0; i < 3; i++) {
1054 		LEVEL_DATA("set overdrive speed. Attempt %d",i);
1055 		if ( BAD( gbRESET(BUS_reset(pn)) ) ) {
1056 			continue;
1057 		}
1058 		if ( BAD( DS9490_sendback_data(&sp, &resp, 1, pn) ) || (_1W_OVERDRIVE_SKIP_ROM != resp) ) {
1059 			LEVEL_DEBUG("error setting overdrive %.2X/0x%02X", _1W_OVERDRIVE_SKIP_ROM, resp);
1060 			continue;
1061 		}
1062 		if ( GOOD( USB_Control_Msg(MODE_CMD, MOD_1WIRE_SPEED, ONEWIREBUSSPEED_OVERDRIVE, pn)) ) {
1063 			LEVEL_DEBUG("speed is now set to overdrive");
1064 			return gbGOOD;
1065 		}
1066 	}
1067 
1068 	LEVEL_DEBUG("Error setting overdrive after 3 retries");
1069 	return gbBAD;
1070 }
1071 
DS9490_setup_adapter(struct connection_in * in)1072 static GOOD_OR_BAD DS9490_setup_adapter(struct connection_in * in)
1073 {
1074 	struct parsedname s_pn;
1075 	struct parsedname * pn = &s_pn ;
1076 	BYTE buffer[ DS9490_getstatus_BUFFER_LENGTH + 1 ];
1077 	int readlen = 0 ;
1078 
1079 	FS_ParsedName_Placeholder(pn);	// minimal parsename -- no destroy needed
1080 	pn->selected_connection = in;
1081 	// reset the device (not the 1-wire bus)
1082 	if ( BAD(USB_Control_Msg(CONTROL_CMD, CTL_RESET_DEVICE, 0x0000, pn))) {
1083 		LEVEL_DATA("ResetDevice error");
1084 		return gbBAD;
1085 	}
1086 	// set the strong pullup duration to infinite
1087 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_SET_DURATION | COMM_IM, 0x0000, pn)) ) {
1088 		LEVEL_DATA("StrongPullup error");
1089 		return gbBAD;
1090 	}
1091 	// set the 12V pullup duration to 512us
1092 	if ( BAD( USB_Control_Msg(COMM_CMD, COMM_SET_DURATION | COMM_IM | COMM_TYPE, PROGRAM_PULSE_DURATION_CODE, pn)) ) {
1093 		LEVEL_DATA("12VPullup error");
1094 		return gbBAD;
1095 	}
1096 	// enable both program and strong pulses
1097 	if ( BAD( USB_Control_Msg(MODE_CMD, MOD_PULSE_EN, ENABLE_PROGRAM_AND_PULSE, pn)) ) {
1098 		LEVEL_DATA("EnableProgram error");
1099 		return gbBAD;
1100 	}
1101 	// enable speed changes
1102 	if ( BAD( USB_Control_Msg(MODE_CMD, MOD_SPEED_CHANGE_EN, 1, pn)) ) {
1103 		LEVEL_DATA("SpeedEnable error");
1104 		return gbBAD;
1105 	}
1106 
1107 	if ( DS9490_getstatus(buffer, &readlen, pn) != BUS_RESET_OK ) {
1108 		LEVEL_DATA("getstatus failed error");
1109 		return gbBAD;
1110 	}
1111 
1112 	return gbGOOD;
1113 }
1114 
DS9490_SetFlexParameters(struct connection_in * in)1115 static void DS9490_SetFlexParameters(struct connection_in *in)
1116 {
1117 	/* in regular and overdrive speed, slew rate is 15V/us. It's only
1118 	* suitable for short 1-wire busses. Use flexible speed instead. */
1119 
1120 	// default values for bus-timing when using --altUSB
1121 	if (Globals.altUSB) {
1122 		in->master.usb.pulldownslewrate = PARMSET_Slew1p37Vus;
1123 		in->master.usb.writeonelowtime = PARMSET_W1L_06us;
1124 		in->master.usb.datasampleoffset = PARMSET_DS0_W0R_20us;
1125 	} else {
1126 		/* This seem to be the default value when reseting the ds2490 chip */
1127 		// Change by Michael Markstaller from datasheet
1128 		in->master.usb.pulldownslewrate = PARMSET_Slew1p10Vus;
1129 //		in->master.usb.pulldownslewrate = PARMSET_Slew0p83Vus;
1130 		in->master.usb.writeonelowtime = PARMSET_W1L_08us;
1131 		in->master.usb.datasampleoffset = PARMSET_DS0_W0R_18us;
1132 	}
1133 	in->changed_bus_settings |= CHANGED_USB_SLEW | CHANGED_USB_LOW | CHANGED_USB_OFFSET ;
1134 }
1135 
1136 #endif							/* OW_USB */
1137