aboutsummaryrefslogtreecommitdiff
path: root/libraries/Firmata/Firmata.cpp
blob: f2688b9b304b549303944f463db5201473671484 (plain)
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
354
355
356
357
358
359
360
361
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
  Firmata.cpp - Firmata library
  Copyright (C) 2006-2008 Hans-Christoph Steiner.  All rights reserved.
 
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  See file LICENSE.txt for further informations on licensing terms.
*/

/*
 * TODO generalized SysEx support
 * TODO firmware name/version reporting (i.e. some firmwares will use the Firmata
 *       protocol, but will only support specific devices, like ultrasound 
 *       rangefinders or servos)
 * TODO implement v2 protocol using digital ports
 */

//******************************************************************************
//* Includes
//******************************************************************************

#include "WProgram.h"
#include "HardwareSerial.h"
#include "Firmata.h"

extern "C" {
#include <string.h>
#include <stdlib.h>
}

//******************************************************************************
//* Support Functions
//******************************************************************************

void sendValueAsTwo7bitBytes(int value)
{
    Serial.print(value & B01111111, BYTE); // LSB
    Serial.print(value >> 7 & B01111111, BYTE); // MSB
}

void startSysex(void)
{
    Serial.print(START_SYSEX, BYTE);
}

void endSysex(void)
{
    Serial.print(END_SYSEX, BYTE);
}

//******************************************************************************
//* Constructors
//******************************************************************************

FirmataClass::FirmataClass(void)
{
    firmwareVersionCount = 0;
    systemReset();
}

//******************************************************************************
//* Public Methods
//******************************************************************************

/* begin method for overriding default serial bitrate */
void FirmataClass::begin(void)
{
    Serial.begin(115200);
    blinkVersion();
    delay(300);
    printVersion();
}

/* begin method for overriding default serial bitrate */
void FirmataClass::begin(long speed)
{
    blinkVersion();
#if defined(__AVR_ATmega128__)  // Wiring
    Serial.begin((uint32_t)speed);
#else
    Serial.begin(speed);
#endif
    delay(300);
    printVersion();
    printFirmwareVersion();
}

// output the protocol version message to the serial port
void FirmataClass::printVersion(void) {
    Serial.print(REPORT_VERSION, BYTE);
    Serial.print(FIRMATA_MAJOR_VERSION, BYTE);
    Serial.print(FIRMATA_MINOR_VERSION, BYTE);
}

void FirmataClass::blinkVersion(void)
{
    // flash the pin with the protocol version
    pinMode(VERSION_BLINK_PIN,OUTPUT);
    pin13strobe(FIRMATA_MAJOR_VERSION, 200, 400);
    delay(300);
    pin13strobe(2,1,4); // separator, a quick burst
    delay(300);
    pin13strobe(FIRMATA_MINOR_VERSION, 200, 400);
}

void FirmataClass::printFirmwareVersion(void)
{
    byte i;

    if(firmwareVersionCount) { // make sure that the name has been set before reporting
        startSysex();
        Serial.print(REPORT_FIRMWARE, BYTE);
        Serial.print(firmwareVersionVector[0]); // major version number
        Serial.print(firmwareVersionVector[1]); // minor version number
        for(i=2; i<firmwareVersionCount; ++i) {
            sendValueAsTwo7bitBytes(firmwareVersionVector[i]);
        }
        endSysex();
    }
}

void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor)
{
    const char *filename;
    char *extension;

// parse out ".cpp" and "applet/" that comes from using __FILE__
    extension = strstr(name, ".cpp");
    filename = strrchr(name, '/') + 1; //points to slash, +1 gets to start of filename
    // add two bytes for version numbers
    if(extension && filename) {
        firmwareVersionCount = extension - filename + 2;
    } else {
        firmwareVersionCount = strlen(name) + 2;
        filename = name;
    }
    firmwareVersionVector = (byte *) malloc(firmwareVersionCount);
    firmwareVersionVector[firmwareVersionCount] = 0;
    firmwareVersionVector[0] = major;
    firmwareVersionVector[1] = minor;
    strncpy((char*)firmwareVersionVector + 2, filename, firmwareVersionCount - 2);
// alas, no snprintf on Arduino
//    snprintf(firmwareVersionVector, MAX_DATA_BYTES, "%c%c%s", 
//             (char)major, (char)minor, firmwareVersionVector);
}

//------------------------------------------------------------------------------
// Serial Receive Handling

int FirmataClass::available(void)
{
    return Serial.available();
}


void FirmataClass::processSysexMessage(void)
{
    switch(storedInputData[0]) { //first byte in buffer is command
    case REPORT_FIRMWARE:
        printFirmwareVersion();
        break;
    case FIRMATA_STRING:
        if(currentStringCallback) {
            byte bufferLength = (sysexBytesRead - 1) / 2;
            char *buffer = (char*)malloc(bufferLength * sizeof(char));
            byte i = 1;
            byte j = 0;
            while(j < bufferLength) {
                buffer[j] = (char)storedInputData[i];
                i++;
                buffer[j] += (char)(storedInputData[i] << 7);
                i++;
                j++;
            }
            (*currentStringCallback)(buffer);
        }
        break;
    default:
        if(currentSysexCallback)
        (*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1);
    }
}

void FirmataClass::processInput(void)
{
    int inputData = Serial.read(); // this is 'int' to handle -1 when no data
    int command;
    
    // TODO make sure it handles -1 properly

    if (parsingSysex) {
        if(inputData == END_SYSEX) {
            //stop sysex byte      
            parsingSysex = false;
            //fire off handler function
            processSysexMessage();
        } else {
            //normal data byte - add to buffer
            storedInputData[sysexBytesRead] = inputData;
            sysexBytesRead++;
        }
    } else if( (waitForData > 0) && (inputData < 128) ) {  
        waitForData--;
        storedInputData[waitForData] = inputData;
        if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message
            switch(executeMultiByteCommand) {
            case ANALOG_MESSAGE:
                if(currentAnalogCallback) {
                    (*currentAnalogCallback)(multiByteChannel,
                                             (storedInputData[0] << 7)
                                             + storedInputData[1]);
                }
                break;
            case DIGITAL_MESSAGE:
                if(currentDigitalCallback) {
                    (*currentDigitalCallback)(multiByteChannel,
                                              (storedInputData[0] << 7)
                                              + storedInputData[1]);
                }
                break;
            case SET_PIN_MODE:
                if(currentPinModeCallback)
                    (*currentPinModeCallback)(storedInputData[1], storedInputData[0]);
                break;
            case REPORT_ANALOG:
                if(currentReportAnalogCallback)
                    (*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]);
                break;
            case REPORT_DIGITAL:
                if(currentReportDigitalCallback)
                    (*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]);
                break;
            }
            executeMultiByteCommand = 0;
        }	
    } else {
        // remove channel info from command byte if less than 0xF0
        if(inputData < 0xF0) {
            command = inputData & 0xF0;
            multiByteChannel = inputData & 0x0F;
        } else {
            command = inputData;
            // commands in the 0xF* range don't use channel data
        }
        switch (command) {
        case ANALOG_MESSAGE:
        case DIGITAL_MESSAGE:
        case SET_PIN_MODE:
            waitForData = 2; // two data bytes needed
            executeMultiByteCommand = command;
            break;
        case REPORT_ANALOG:
        case REPORT_DIGITAL:
            waitForData = 1; // two data bytes needed
            executeMultiByteCommand = command;
            break;
        case START_SYSEX:
            parsingSysex = true;
            sysexBytesRead = 0;
            break;
        case SYSTEM_RESET:
            systemReset();
            break;
        case REPORT_VERSION:
            Firmata.printVersion();
            break;
        }
    }
}

//------------------------------------------------------------------------------
// Serial Send Handling

// send an analog message
void FirmataClass::sendAnalog(byte pin, int value) 
{
	// pin can only be 0-15, so chop higher bits
	Serial.print(ANALOG_MESSAGE | (pin & 0xF), BYTE);
    sendValueAsTwo7bitBytes(value);
}

// send a single digital pin in a digital message
void FirmataClass::sendDigital(byte pin, int value) 
{
	/* TODO add single pin digital messages to the protocol, this needs to
     * track the last digital data sent so that it can be sure to change just
     * one bit in the packet.  This is complicated by the fact that the
     * numbering of the pins will probably differ on Arduino, Wiring, and
     * other boards.  The DIGITAL_MESSAGE sends 14 bits at a time, but it is
     * probably easier to send 8 bit ports for any board with more than 14
     * digital pins.
     */

	// TODO: the digital message should not be sent on the serial port every
	// time sendDigital() is called.  Instead, it should add it to an int
	// which will be sent on a schedule.  If a pin changes more than once
	// before the digital message is sent on the serial port, it should send a
	// digital message for each change.

//    if(value == 0)
//        sendDigitalPortPair();
}


// send 14-bits in a single digital message (protocol v1)
// send an 8-bit port in a single digital message (protocol v2)
void FirmataClass::sendDigitalPort(byte portNumber, int portData)
{
	Serial.print(DIGITAL_MESSAGE | (portNumber & 0xF),BYTE);
	Serial.print(portData % 128, BYTE); // Tx bits 0-6
	Serial.print(portData >> 7, BYTE);  // Tx bits 7-13
}


void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev) 
{
    byte i;
    startSysex();
    Serial.print(command, BYTE);
    for(i=0; i<bytec; i++) {
        sendValueAsTwo7bitBytes(bytev[i]);        
    }
    endSysex();
}

void FirmataClass::sendString(byte command, const char* string) 
{
    sendSysex(command, strlen(string), (byte *)string);
}


// send a string as the protocol string type
void FirmataClass::sendString(const char* string) 
{
    sendString(FIRMATA_STRING, string);
}


// Internal Actions/////////////////////////////////////////////////////////////

// generic callbacks
void FirmataClass::attach(byte command, callbackFunction newFunction)
{
    switch(command) {
    case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break;
    case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break;
    case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break;
    case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break;
    case SET_PIN_MODE: currentPinModeCallback = newFunction; break;
    }
}

void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction)
{
    switch(command) {
    case SYSTEM_RESET: currentSystemResetCallback = newFunction; break;
    }
}

void FirmataClass::attach(byte command, stringCallbackFunction newFunction)
{
    switch(command) {
    case FIRMATA_STRING: currentStringCallback = newFunction; break;
    }
}

void FirmataClass::attach(byte command, sysexCallbackFunction newFunction)
{
    currentSysexCallback = newFunction;
}

void FirmataClass::detach(byte command)
{
    switch(command) {
    case SYSTEM_RESET: currentSystemResetCallback = NULL; break;
    case FIRMATA_STRING: currentStringCallback = NULL; break;
    case START_SYSEX: currentSysexCallback = NULL; break;
    default:
        attach(command, (callbackFunction)NULL);
    }
}

// sysex callbacks
/*
 * this is too complicated for analogReceive, but maybe for Sysex?
 void FirmataClass::attachSysex(sysexFunction newFunction)
 {
 byte i;
 byte tmpCount = analogReceiveFunctionCount;
 analogReceiveFunction* tmpArray = analogReceiveFunctionArray;
 analogReceiveFunctionCount++;
 analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction));
 for(i = 0; i < tmpCount; i++) {
 analogReceiveFunctionArray[i] = tmpArray[i];
 }
 analogReceiveFunctionArray[tmpCount] = newFunction;
 free(tmpArray);
 }
*/

//******************************************************************************
//* Private Methods
//******************************************************************************



// resets the system state upon a SYSTEM_RESET message from the host software
void FirmataClass::systemReset(void)
{
    byte i;

    waitForData = 0; // this flag says the next serial input will be data
    executeMultiByteCommand = 0; // execute this after getting multi-byte data
    multiByteChannel = 0; // channel data for multiByteCommands


    for(i=0; i<MAX_DATA_BYTES; i++) {
        storedInputData[i] = 0;
    }

    parsingSysex = false;
    sysexBytesRead = 0;

    if(currentSystemResetCallback)
                    (*currentSystemResetCallback)();

    //flush(); //TODO uncomment when Firmata is a subclass of HardwareSerial
}



// =============================================================================
// used for flashing the pin for the version number
void FirmataClass::pin13strobe(int count, int onInterval, int offInterval) 
{
    byte i;
    pinMode(VERSION_BLINK_PIN, OUTPUT);
    for(i=0; i<count; i++) {
        delay(offInterval);
        digitalWrite(VERSION_BLINK_PIN, HIGH);
        delay(onInterval);
        digitalWrite(VERSION_BLINK_PIN, LOW);
    }
}


// make one instance for the user to use
FirmataClass Firmata;