File: PSerial_mac.cpp

package info (click to toggle)
nqc 2.3.r1-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,452 kB
  • ctags: 2,325
  • sloc: cpp: 14,379; lex: 304; yacc: 259; makefile: 126; ansic: 25
file content (353 lines) | stat: -rw-r--r-- 8,252 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Initial Developer of this code is David Baum.
 * Portions created by David Baum are Copyright (C) 1998 David Baum.
 * All Rights Reserved.
 */

#include <Serial.h>
#include <string.h>
#include "PSerial.h"

#define kDefaultSpeed	9600

static bool SerialArbitrationExists(void);
static bool DriverIsOpen(ConstStr255Param driverName);
static OSErr OpenOneSerialDriver(ConstStr255Param driverName, short *refNum);


#define kDefaultBufferSize	16384

#define kNoTimeout	 -1

#define kSeparator ':'

class PSerial_mac : public PSerial
{
public:
	virtual	bool	Open(const char *name);

	virtual void	Close();
	virtual long	Write(const void *ptr, long count);
	virtual long	Read(void *ptr, long count);
	virtual bool	SetTimeout(long timeout_ms);
	virtual bool	SetDTR(bool assert);

	virtual bool	SetSpeed(int speed, int opts = 0);

private:
	Ptr		fInputBuffer;
	short	fInRef;
	short	fOutRef;
	long	fTimeoutTicks;
};


PSerial* PSerial::NewSerial()
{
	return new PSerial_mac();
}


const char *PSerial::GetDefaultName()
{
	return "a";
}


bool PSerial_mac::Open(const char *name)
{
	OSErr error;
	char inName[256];
	char outName[256];
	char *split;
		
	if (fOpen) return false;
	
	split = strchr(name, kSeparator);
	if (split)
	{
		memcpy(inName, name, split-name);
		inName[split-name] = 0;
		
		strcpy(outName, split+1);	
	}
	else
	{
		outName[0] = '.';
		strcpy(outName+1, name);
		strcat(outName, "Out");
		inName[0] = '.';
		strcpy(inName+1, name);
		strcat(inName, "In");
	}
	
	CtoPstr(outName);
	error=OpenOneSerialDriver((Byte*)outName, &fOutRef);
	if (error) goto Fail1;

	CtoPstr(inName);
	error=OpenOneSerialDriver((Byte*)inName, &fInRef);
	if (error) goto Fail2;

	fInputBuffer = NewPtr(kDefaultBufferSize);
	if (!fInputBuffer) goto Fail3;

	SerSetBuf(fInRef, fInputBuffer, kDefaultBufferSize);
	if (!SetSpeed(kDefaultSpeed)) goto Fail4;
	
	fOpen = true;
	fTimeoutTicks = kNoTimeout;
	return true;

Fail4:
	DisposePtr(fInputBuffer);
Fail3:
	FSClose(fInRef);
Fail2:
	FSClose(fOutRef);
Fail1:
	return false;	
}


void PSerial_mac::Close()
{
	if (!fOpen) return;
	
	KillIO(fInRef);
	CloseDriver(fInRef);
	KillIO(fOutRef);
	CloseDriver(fOutRef);
	DisposePtr(fInputBuffer);
	fOpen = false;
}


static const short sDataConfigs[] = { data8, data7, data6, data5 };
static const short sParityConfigs[] = {noParity, oddParity, evenParity};
static const short sStopConfigs[] = {stop10, stop15, stop20 };

bool PSerial_mac::SetSpeed(int speed, int opts)
{
	SerShk	shake;
	OSErr 	error;
	int divider;
	short config;
	int index;
	
	/* start with no handshaking */
	shake.fXOn = 0;
	shake.fCTS = 0;
	shake.xOn  = 0x11;
	shake.xOff = 0x13;
	shake.fInX = 0;
	shake.evts = 0;
	shake.fDTR = 0;

	// compute baud rate
	divider = ((115200 / speed) - 2) & 0x3ff;
	config = (short)divider;
	
	// data bits
	index = (opts & kPSerial_DataMask) >> kPSerial_DataShift;
	if (index > (sizeof(sDataConfigs)/sizeof(short))) return false;
	config |= sDataConfigs[index];

	// parity
	index = (opts & kPSerial_ParityMask) >> kPSerial_ParityShift;
	if (index > (sizeof(sParityConfigs)/sizeof(short))) return false;
	config |= sParityConfigs[index];

	// stop bits
	index = (opts & kPSerial_StopMask) >> kPSerial_StopShift;
	if (index > (sizeof(sStopConfigs)/sizeof(short))) return false;
	config |= sStopConfigs[index];

	
	error=SerReset(fOutRef, config);
	if (error) return false;
	error=SerHShake(fOutRef, &shake);
	if (error) return false;
	error=SerReset(fInRef, config);
	if (error) return false;
	error=SerHShake(fInRef, &shake);
	if (error) return false;

	return true;
}


long PSerial_mac::Write(const void *ptr, long count)
{
	OSErr error;
	
	if (!fOpen) return -1;
	
	error = FSWrite(fOutRef, &count, ptr);
	if (error) return -1;
	
	return count;
}


bool PSerial_mac::SetTimeout(long timeout_ms)
{
	if (timeout_ms == 0)
		fTimeoutTicks = 0;
	else if (timeout_ms == kPStream_NeverTimeout)
		fTimeoutTicks = kNoTimeout;
	else
		fTimeoutTicks = (timeout_ms * 3 + 49) / 50;

	return true;
}


bool PSerial_mac::SetDTR(bool assert)
{
	OSErr err = Control(fOutRef, assert ? 17 : 18, 0);
	return err == noErr;
}


long PSerial_mac::Read(void *ptr, long count)
{
	OSErr error;

	if (!fOpen) return -1;
	
	if (fTimeoutTicks != kNoTimeout)
	{
		long ready;
		unsigned long expire;
		
		// set expiration time
		expire = TickCount() + fTimeoutTicks;

		do
		{
			SerGetBuf(fInRef, &ready);	// check available
			
		} while(ready<count && TickCount() < expire);

		// no data?  then don't bother with FSRead, just return
		if (ready == 0) return 0;
		
		// only read what's required
		if (count > ready)
			count = ready;
	}

	error = FSRead(fInRef, &count, ptr);
	if (error) return -1;	
	return count;
}



/* sample code from Apple on opening serial drivers */
enum {
    gestaltSerialPortArbitratorAttr = 'arb ',
    
        gestaltSerialPortArbitratorExists = 0
};


static OSErr OpenOneSerialDriver(ConstStr255Param driverName, short *refNum)
    // The one true way of opening a serial driver.  This routine
    // tests whether a serial port arbitrator exists.  If it does,
    // it relies on the SPA to do the right thing when OpenDriver is called.
    // If not, it uses the old mechanism, which is to walk the unit table
    // to see whether the driver is already in use by another program.
{
    OSErr err;
    
    if ( SerialArbitrationExists() ) {
        err = OpenDriver(driverName, refNum);
    } else {
        if ( DriverIsOpen(driverName) ) {
            err = portInUse;
        } else {
            err = OpenDriver(driverName, refNum);
        }
    }
    return err;
}

static bool SerialArbitrationExists(void)
    // Test Gestalt to see if serial arbitration exists
    // on this machine.
{
    long    response;
    OSErr	err;
    
    err = Gestalt(gestaltSerialPortArbitratorAttr, &response);
    if (err) return false;
    
    return (response & (1 << gestaltSerialPortArbitratorExists)) ? true : false;
}


static bool DriverIsOpen(ConstStr255Param driverName)
    // Walks the unit table to determine whether the
    // given driver is marked as open in the table.
    // Returns false if the driver is closed, or does
    // not exist.
{
    bool     found;
    bool     isOpen;
    short       unit;
    DCtlHandle  dceHandle;
    StringPtr   namePtr;
    
    found = false;
    isOpen = false;
    
    unit = 0;   
    while ( ! found && ( unit < LMGetUnitTableEntryCount() ) ) {
    
        // Get handle to a device control entry.  GetDCtlEntry
        // takes a driver refNum, but we can convert between
        // a unit number and a driver refNum using bitwise not.
        
        dceHandle = GetDCtlEntry( (short)~unit );
        
        if ( dceHandle != nil && (**dceHandle).dCtlDriver != nil ) {
        
            // If the driver is RAM based, dCtlDriver is a handle,
            // otherwise it's a pointer.  We have to do some fancy
            // casting to handle each case.  This would be so much
            // easier to read in Pascal )-:
            
            if ( ((**dceHandle).dCtlFlags & dRAMBasedMask) != 0 ) {
                namePtr = & (**((DRVRHeaderHandle) (**dceHandle).dCtlDriver)).drvrName[0];
            } else {
                namePtr = & (*((DRVRHeaderPtr) (**dceHandle).dCtlDriver)).drvrName[0];
            }
    
            // Now that we have a pointer to the driver name, compare
            // it to the name we're looking for.  If we find it,
            // then we can test the flags to see whether it's open or
            // not.
            
            if ( EqualString(driverName, namePtr, false, true) ) {
                found = true;
                isOpen = ((**dceHandle).dCtlFlags & dOpenedMask) != 0;
            }
        }
        unit += 1;
    }
    
    return isOpen;
}