aboutsummaryrefslogtreecommitdiff
path: root/smc.c
blob: fe042d72c4dcff1564ed79afc02e262b2c5f87ef (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
/* --------------------------------------------------------------------------*/
/*                                                                           */
/* read the System Management Controller on Apple Mac OS X                   */
/* Written by Hans-Christoph Steiner <hans@eds.org>                          */
/*                                                                           */
/* Copyright (C) 2008-2009 Hans-Christoph Steiner                            */
/* Copyright (C) 2006 devnull                                                */
/*                                                                           */
/* This program is free software; you can redistribute it and/or             */
/* modify it under the terms of the GNU General Public License               */
/* as published by the Free Software Foundation; either version 3            */
/* of the License, or (at your option) any later version.                    */
/*                                                                           */
/* See file LICENSE for further informations on licensing terms.             */
/*                                                                           */
/* This program is distributed in the hope that it will be useful,           */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             */
/* GNU General Public License for more details.                              */
/*                                                                           */
/* You should have received a copy of the GNU General Public License         */
/* along with this program; if not, write to the Free Software Foundation,   */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */
/*                                                                           */
/* --------------------------------------------------------------------------*/

#include <mach/mach.h> 
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <IOKit/IOKitLib.h> 

#include "m_pd.h"
#include "smc.h"

//#define DEBUG(x)
#define DEBUG(x) x 

/*------------------------------------------------------------------------------
 *  CLASS DEF
 */

static t_class *smc_class;

typedef struct _smc {
    t_object            x_obj;
    t_symbol*           key;
    t_outlet*           data_outlet;
    t_outlet*           status_outlet;
} t_smc;

static io_connect_t conn;


/*------------------------------------------------------------------------------
 * WEIRD SHIT TO GET RID OF (why not just use the standard functions?)
 */

UInt32 _strtoul(char *str, int size, int base)
{
    UInt32 total = 0;
    int i;

    for (i = 0; i < size; i++)
    {
        if (base == 16)
            total += str[i] << (size - 1 - i) * 8;
        else
            total += (unsigned char) (str[i] << (size - 1 - i) * 8);
    }
    return total;
}

void _ultostr(char *str, UInt32 val)
{
    str[0] = '\0';
    sprintf(str, "%c%c%c%c", 
            (unsigned int) val >> 24,
            (unsigned int) val >> 16,
            (unsigned int) val >> 8,
            (unsigned int) val);
}

float _strtof(char *str, int size, int e)
{
    float total = 0;
    int i;

    for (i = 0; i < size; i++)
    {
        if (i == (size - 1))
            total += (str[i] & 0xff) >> e;
        else
            total += str[i] << (size - 1 - i) * (8 - e);
    }

    return total;
}

/*------------------------------------------------------------------------------
 * SUPPORT FUNCTIONS
 */

kern_return_t SMCOpen(void)
{
    kern_return_t result;
    mach_port_t   masterPort;
    io_iterator_t iterator;
    io_object_t   device;

    result = IOMasterPort(MACH_PORT_NULL, &masterPort);

    CFMutableDictionaryRef matchingDictionary = IOServiceMatching("AppleSMC");
    result = IOServiceGetMatchingServices(masterPort, matchingDictionary, &iterator);
    if (result != kIOReturnSuccess)
    {
        post("Error: IOServiceGetMatchingServices() = %08x\n", result);
        return 1;
    }

    device = IOIteratorNext(iterator);
    IOObjectRelease(iterator);
    if (device == 0)
    {
        post("Error: no SMC found\n");
        return 1;
    }

    result = IOServiceOpen(device, mach_task_self(), 0, &conn);
    IOObjectRelease(device);
    if (result != kIOReturnSuccess)
    {
        post("Error: IOServiceOpen() = %08x\n", result);
        return 1;
    }

    return kIOReturnSuccess;
}

kern_return_t SMCClose()
{
    return IOServiceClose(conn);
}


kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure)
{
    IOItemCount   structureInputSize;
    IOByteCount   structureOutputSize;

    structureInputSize = sizeof(SMCKeyData_t);
    structureOutputSize = sizeof(SMCKeyData_t);

    return IOConnectMethodStructureIStructureO(
        conn,
        index,
        structureInputSize,
        &structureOutputSize,
        inputStructure,
        outputStructure
        );
}

kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val)
{
    kern_return_t result;
    SMCKeyData_t  inputStructure;
    SMCKeyData_t  outputStructure;

    memset(&inputStructure, 0, sizeof(SMCKeyData_t));
    memset(&outputStructure, 0, sizeof(SMCKeyData_t));
    memset(val, 0, sizeof(SMCVal_t));

    inputStructure.key = _strtoul(key, 4, 16);
    sprintf(val->key, key);
    inputStructure.data8 = SMC_CMD_READ_KEYINFO;    

    result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);
    if (result != kIOReturnSuccess)
        return result;

    val->dataSize = outputStructure.keyInfo.dataSize;
    _ultostr(val->dataType, outputStructure.keyInfo.dataType);
    inputStructure.keyInfo.dataSize = val->dataSize;
    inputStructure.data8 = SMC_CMD_READ_BYTES;

    result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);
    if (result != kIOReturnSuccess)
        return result;

    memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes));

    return kIOReturnSuccess;
}

kern_return_t SMCWriteKey(SMCVal_t writeVal)
{
    kern_return_t result;
    SMCKeyData_t  inputStructure;
    SMCKeyData_t  outputStructure;

    SMCVal_t      readVal;

    result = SMCReadKey(writeVal.key, &readVal);
    if (result != kIOReturnSuccess) 
        return result;

    if (readVal.dataSize != writeVal.dataSize)
        return kIOReturnError;

    memset(&inputStructure, 0, sizeof(SMCKeyData_t));
    memset(&outputStructure, 0, sizeof(SMCKeyData_t));

    inputStructure.key = _strtoul(writeVal.key, 4, 16);
    inputStructure.data8 = SMC_CMD_WRITE_BYTES;    
    inputStructure.keyInfo.dataSize = writeVal.dataSize;
    memcpy(inputStructure.bytes, writeVal.bytes, sizeof(writeVal.bytes));

    result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);
    if (result != kIOReturnSuccess)
        return result;
 
    return kIOReturnSuccess;
}

UInt32 SMCReadIndexCount(void)
{
    SMCVal_t val;

    SMCReadKey("#KEY", &val);
    return _strtoul(val.bytes, val.dataSize, 10);
}

double SMCGetTemperature(char *key)
{
    SMCVal_t val;
    kern_return_t result;

    result = SMCReadKey(key, &val);
    if (result == kIOReturnSuccess) {
        // read succeeded - check returned value
        if (val.dataSize > 0) {
            if (strcmp(val.dataType, DATATYPE_SP78) == 0) {
                // convert fp78 value to temperature
                int intValue = (val.bytes[0] * 256 + val.bytes[1]) >> 2;
                return intValue / 64.0;
            }
        }
    }
    // read failed
    return 0.0;
}

kern_return_t SMCSetFanRpm(char *key, int rpm)
{
    SMCVal_t val;
    
    strcpy(val.key, key);
    val.bytes[0] = (rpm << 2) / 256;
    val.bytes[1] = (rpm << 2) % 256;
    val.dataSize = 2;
    return SMCWriteKey(val);
}

int SMCGetFanRpm(char *key)
{
    SMCVal_t val;
    kern_return_t result;

    result = SMCReadKey(key, &val);
    if (result == kIOReturnSuccess) {
        // read succeeded - check returned value
        if (val.dataSize > 0) {
            if (strcmp(val.dataType, DATATYPE_FPE2) == 0) {
                // convert FPE2 value to int value
                return (int)_strtof(val.bytes, val.dataSize, 2);
            }
        }
    }
    // read failed
    return -1;
}



/*------------------------------------------------------------------------------
 * IMPLEMENTATION                    
 */

static void smc_symbol(t_smc* x, t_symbol* key)
{
	DEBUG(post("smc_symbol"););
    kern_return_t result;
    SMCVal_t      val;
    t_atom output_atom;

    SMCOpen();
    result = SMCReadKey(key->s_name, &val);
    if (result == kIOReturnSuccess) {
        // read succeeded - check returned value
        x->key = key;
        if (val.dataSize > 0) {
            if (strcmp(val.dataType, DATATYPE_SP78) == 0) {
                // convert sp78 value to temperature
                int intValue = (val.bytes[0] * 256 + val.bytes[1]) >> 2;
                SETFLOAT(&output_atom, intValue / 64.0);
                outlet_anything(x->data_outlet, key, 1, &output_atom);
            } else if ((strcmp(val.dataType, DATATYPE_UINT8) == 0) ||
                       (strcmp(val.dataType, DATATYPE_UINT16) == 0) ||
                       (strcmp(val.dataType, DATATYPE_UINT32) == 0)) {
                SETFLOAT(&output_atom, _strtoul(val.bytes, val.dataSize, 10));
                outlet_anything(x->data_outlet, gensym(val.key), 1, &output_atom);
            } else if (strcmp(val.dataType, DATATYPE_FPE2) == 0) {
                SETFLOAT(&output_atom, _strtof(val.bytes, val.dataSize, 2));
                outlet_anything(x->data_outlet, gensym(val.key), 1, &output_atom);
            } else {
                UInt32 i;
                t_atom output_list[val.dataSize];
                for (i = 0; i < val.dataSize; i++)
                    SETFLOAT(output_list + i, (unsigned char) val.bytes[i]);
                outlet_anything(x->data_outlet, gensym(val.key), 
                                val.dataSize, output_list);
            }
        }
        
    }
    SMCClose();
}

static void smc_bang(t_smc* x)
{
    smc_symbol(x, x->key);
}

static void smc_keys(t_smc* x)
{
	DEBUG(post("smc_keys"););
    kern_return_t result;
    SMCKeyData_t  inputStructure;
    SMCKeyData_t  outputStructure;

    int           totalKeys, i;
    UInt32Char_t  key;
    SMCVal_t      val;

    SMCOpen();
    totalKeys = SMCReadIndexCount();
    t_atom output_list[totalKeys];
    for (i = 0; i < totalKeys; i++)
    {
        memset(&inputStructure, 0, sizeof(SMCKeyData_t));
        memset(&outputStructure, 0, sizeof(SMCKeyData_t));
        memset(&val, 0, sizeof(SMCVal_t));

        inputStructure.data8 = SMC_CMD_READ_INDEX;
        inputStructure.data32 = i;

        result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);
        if (result != kIOReturnSuccess)
            continue;

        _ultostr(key, outputStructure.key);
        SETSYMBOL(output_list + i, gensym(key));
    }
    SMCClose();
    outlet_anything(x->status_outlet, gensym("keys"), totalKeys, output_list);
}

static void smc_info(t_smc* x)
{
    t_atom output_atom;
    SETSYMBOL(&output_atom, x->key);
    outlet_anything(x->status_outlet, gensym("key"), 1, &output_atom);
    smc_keys(x);
}

static void smc_anything(t_smc* x, t_symbol *s, int argc, t_atom *argv)
{
	DEBUG(post("smc_anything %d", argc););
    if(argc == 0) {
        x->key = s;
        if(x->key != &s_) smc_bang(x);
    } else if(argc == 1) {
            atom_getfloatarg(0, argc, argv);
    }
}

static void *smc_new(t_symbol* s) 
{
	DEBUG(post("smc_new"););
	t_smc *x = (t_smc *)pd_new(smc_class);

    x->key = s;
    x->data_outlet = outlet_new(&x->x_obj, &s_anything);
	x->status_outlet = outlet_new(&x->x_obj, &s_anything);

	return (x);
}

void smc_setup(void) 
{
	smc_class = class_new(gensym("smc"), 
                          (t_newmethod)smc_new,
                          NULL,
                          sizeof(t_smc), 
                          CLASS_DEFAULT,
                          A_DEFSYMBOL,
                          0);
	/* add inlet datatype methods */
	class_addbang(smc_class,(t_method) smc_bang);
	class_addsymbol(smc_class,(t_method) smc_symbol);
	class_addmethod(smc_class,(t_method) smc_info, gensym("info"), 0);
	class_addmethod(smc_class,(t_method) smc_keys, gensym("keys"), 0);
	class_addanything(smc_class,(t_method) smc_anything);
}