-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPiFaceRTCFreeBSD.c
1475 lines (1098 loc) · 57.5 KB
/
PiFaceRTCFreeBSD.c
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** PiFaceRTCFreeBSD.c
**
** Created by John Howie on 10/27/15.
**
**
** This source file contains the PiFace Real Time Clock application.
**
** Modifications
**
** 20151027 jh Original.
**
** Copyright (c) 2015, jhowie
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this
** list of conditions and the following disclaimer.
**
** * Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
**
** * Neither the name of FreeBSDPiFaceRTC nor the names of its
** contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
*/
# include <stdbool.h>
# include <sys/cdefs.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <fcntl.h>
# include <sys/ioctl.h>
# include <errno.h>
# include <unistd.h>
# include <sys/utsname.h>
# include <sys/types.h>
# include <sys/time.h>
# include <time.h>
# include <ctype.h>
# include "PiFaceRTC.h"
# include "I2CRoutines.h"
/*
** Funtion prototypes
*/
void Usage (void);
int DisplayPowerFailTime (int busfd, int nBusDevId);
int DisplayPowerRestoreTime (int busfd, int nBusDevId);
int HWSetTimeOfDay (int busfd, int nBusDevId, char *szDatetime, bool bUseComputerClockToSetRTC);
int HWGetTimeOfDay (int busfd, int nBusDevId, bool bDisplayDateTimeAsDateInput, bool bSetComputerClockFromRTC);
int ReadNVRAM (int busfd, int nBusDevId);
int WriteNVRAM (int busfd, int nBusDevId, char *szNVRAMContents);
int ProcessHWClockOption (int busfd, int nBusDevId, char *szOptionsToProcess);
int HWOptionInitRTC (int busfd, int nBusDevId);
int HWOptionBatteryEnable (int busfd, int nBusDevId);
int HWOptionBatteryDisable (int busfd, int nBusDevId);
int HWOptionBatteryGetSetting (int busfd, int nBusDevId);
int HWOptionControlRegistersDisplay (int busfd, int nBusDevId);
int HWOptionCalibrateClock (int busfd, int nBusDevId);
int HWOptionClearNVRAM (int busfd, int nBusDevId);
int HWOptionOscillatorEnable (int busfd, int nBusDevId);
int HWOptionOscillatorDisable (int busfd, int nBusDevId);
int HWOptionOscillatorGetStatus (int busfd, int nBusDevId);
int HWOptionOscillatorGetSetting (int busfd, int nBusDevId);
int HWOptionPowerFailStatus (int busfd, int nBusDevId);
int HWOptionPowerFailClearFlag (int busfd, int nBusDevId);
int HWOptionOscillatorConfigure (int busfd, int nBusDevId, bool bEnable);
int HWOptionBatteryConfigure (int busfd, int nBusDevId, bool bEnable);
void TranslateRTCDateTimeToTm (struct mcp7940n_datetime *pdatetimeRTCClock, struct tm *ptmRTCDateTime);
void TranslateTmToRTCDateTime (struct tm *ptmRTCDateTime, struct mcp7940n_datetime *pdatetimeRTCClock);
struct rtc_option {
char *m_szOption;
int (*m_pOptionFunc)();
} RTCOptions [] = {
{ "init", &HWOptionInitRTC },
{ "bat", &HWOptionBatteryEnable },
{ "nobat", &HWOptionBatteryDisable },
{ "batset", &HWOptionBatteryGetSetting },
{ "cal", &HWOptionCalibrateClock },
{ "clrnvram", &HWOptionClearNVRAM },
{ "control", &HWOptionControlRegistersDisplay },
{ "osc", &HWOptionOscillatorEnable },
{ "noosc", &HWOptionOscillatorDisable },
{ "oscset", &HWOptionOscillatorGetSetting },
{ "oscstat", &HWOptionOscillatorGetStatus },
{ "pwrstat", &HWOptionPowerFailStatus },
{ "clrpwr", &HWOptionPowerFailClearFlag },
{ 0, 0 }
};
char *szDisplayWeekday [] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
char *szDisplayMonth [] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
/* int main (int argc, char **argv)
**
** This is the entry point for the application
*/
int main (int argc, char **argv)
{
int ch, nBusDevId = 0x6f, busfd; // The PiFace RTC bus device id is 0x69 in 7-bit addressing
char *szBusName = (char *) 0, *szOptions = (char *) 0, *szNVRAMContents = (char *) 0;
bool bUseComputerClockToSetRTC = false, bSetComputerClockFromRTC = false,
bDisplayPowerFail = false, bDisplayPowerRestore = false,
bProcessOptions = false, bDisplayDateTimeAsDateInput = false,
bReadNVRAM = false, bWriteNVRAM = false, bMustBeRoot = false;
// Go through the command line arguments
while ((ch = getopt (argc, argv, "b:cdhi:o:prsuw:")) != -1) {
switch (ch) {
case 'b':
// The user wants to set the device id on the bus
nBusDevId = strtol (optarg, (char **) 0, 0);
if (nBusDevId >= 0x80) {
// The bus devid needs to be a 7-bit address for our purposes
Usage ();
exit (1);
}
break;
case 'c':
// The user wants us to use the clock of the computer to set the RTC
bUseComputerClockToSetRTC = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 'd':
// The user wants us to display the date in a format suitable as input to the date command
bDisplayDateTimeAsDateInput = true;
break;
case 'h':
// User wants to display some help
Usage ();
exit (0);
break;
case 'i':
// The user is specifying the bus. The single optarg character tells us which bus we are using
switch (*optarg) {
case '0': szBusName = "/dev/iic0"; break;
case '1': szBusName = "/dev/iic1"; break;
default: Usage (); exit (1); break;
}
break;
case 'o':
// The user wants to process an option
bProcessOptions = true;
szOptions = optarg;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 'p':
// The user wants the powerfail time
bDisplayPowerFail = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 'r':
// The user wants to display the NVRAM contents
bReadNVRAM = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 's':
// The user wants to set the computer clock from the RTC
bSetComputerClockFromRTC = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 'u':
// The user wants the time the power was restored at
bDisplayPowerRestore = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
case 'w':
// The user wants to write to the NVRAM
szNVRAMContents = optarg;
bWriteNVRAM = true;
bMustBeRoot = true; // User must really be root to perform this action
break;
default:
// We received an unknown command line switch
Usage ();
exit (1);
break;
}
}
// Set up argv and argv to process the remainder of the command line
argc -= optind;
argv += optind;
// Check to see if we must be root to proceed. The utility runs as suid root so users
// can query the clock, but most operations require you to actually be root. We set the
// boolean bMustBeRoot when parsing the command line where the operation requires the
// user to be root. Here we check if the boolean is set, or if there are remaining arguments
// on the command line (we assume there is one, and it is a date/time the user wants to set
// the clock to).
if ((bMustBeRoot == true) || (argc >= 1)) {
// Check that we really are root
if (getuid () != 0) {
// We are not running as root. Display and error message and exit
(void) fprintf (stderr, "You must be root to perform action(s).\n");
exit (1);
}
}
// Open the bus device
busfd = OpenI2CDevice (szBusName, nBusDevId);
if (busfd < 0) {
// An error occurred, and we were unable to open the I2C bus device
exit (1);
}
// If the user wanted the powerfail or powerrestore date/time, get it
if (bDisplayPowerFail) {
if (DisplayPowerFailTime (busfd, nBusDevId) < 0) {
// An error occurred
exit (1);
}
exit (0);
}
if (bDisplayPowerRestore) {
if (DisplayPowerRestoreTime (busfd, nBusDevId) < 0) {
// An error occurred
exit (1);
}
exit (0);
}
// Check whether the user wanted to read from or write to the NVRAM
if (bReadNVRAM) {
if (ReadNVRAM (busfd, nBusDevId) < 0) {
// An error occurred
exit (1);
}
exit (0);
}
if (bWriteNVRAM) {
if (WriteNVRAM (busfd, nBusDevId, szNVRAMContents) < 0) {
// An error occurred
exit (1);
}
exit (0);
}
// If the user wanted to process an option, do it now
if (bProcessOptions) {
if (ProcessHWClockOption (busfd, nBusDevId, szOptions) < 0) {
// An error occurred
exit (1);
}
exit (0);
}
// Check to see if the user wants to get the time, or set the time
if (argc == 1 || bUseComputerClockToSetRTC) {
// The user wants to set the time
if (HWSetTimeOfDay (busfd, nBusDevId, argv [0], bUseComputerClockToSetRTC) < 0) {
// An error occurred
exit (1);
}
}
else {
// The user simply wants the date/time
if (HWGetTimeOfDay (busfd, nBusDevId, bDisplayDateTimeAsDateInput, bSetComputerClockFromRTC) < 0) {
// An error occurred
exit (1);
}
}
// Simply close the device
(void) CloseI2CDevice (busfd);
// Return
exit (0);
}
/* int ProcessHWClockOption (int busfd, int nBusDevId, char *OptionsToProcess)
**
** This option is used to process options for the PiFace Real Time Clock
*/
int ProcessHWClockOption (int busfd, int nBusDevId, char *szOptionsToProcess)
{
char *szOption;
struct rtc_option *pOption;
// Process each of the options specified. Get the first option
szOption = strtok (szOptionsToProcess, ",");
while (szOption != (char *) 0) {
// Go through the array of options and option processing functions looking for a match
pOption = RTCOptions;
while (pOption ->m_szOption != (char *) 0) {
// Check to see if we have a match between the option specified and the option at the current location in the array
if (! strcasecmp (szOption, pOption ->m_szOption)) {
// We have a match - process it
(*pOption ->m_pOptionFunc) (busfd, nBusDevId);
break;
}
// Get the next option
pOption ++;
}
// We should only get here because we 'broke' out of the loop after processing an option. We can sanity check, though,
// and display a warning message if we got a bogus option
if (pOption ->m_szOption == (char *) 0) {
// We did get a bogus option
(void) printf ("WARNING: Invalid option %s specified, ignoring and continuing processing!\n", szOption);
}
// Get the next option (if there are any more)
szOption = strtok (0, ",");
}
// We never return anything other than 0
return 0;
}
/* int HWOptionInitRTC (int busfd, int nBusDevId)
**
** This option initializes the Real Time Clock, setting the trim value, the date and time, and
** enabling the battery and external oscillator
*/
int HWOptionInitRTC (int busfd, int nBusDevId)
{
// First, set the TRIM value
if (HWOptionCalibrateClock (busfd, nBusDevId) < 0) {
// An error occurred
(void) fprintf (stderr, "Initialization failed!\n");
return -1;
}
// Now, enable the battery
if (HWOptionBatteryEnable (busfd, nBusDevId) < 0) {
// An error occurred
(void) fprintf (stderr, "Initialization failed!\n");
return -1;
}
// Now, enable the oscillator
if (HWOptionOscillatorEnable (busfd, nBusDevId) < 0) {
// An error occurred
(void) fprintf (stderr, "Initialization failed!\n");
return -1;
}
// Set the date on the RTC using the computer clock
if (HWSetTimeOfDay (busfd, nBusDevId, (char *) 0, true) < 0) {
// An error occurred
(void) fprintf (stderr, "Initialization failed!\n");
return -1;
}
(void) printf ("Initialization successful.\n");
return 0;
}
/* int HWOptionBatteryEnable (int busfd, int nBusDevId)
**
** Set the battery enable flag on the Real Time Clock
*/
int HWOptionBatteryEnable (int busfd, int nBusDevId)
{
return HWOptionBatteryConfigure (busfd, nBusDevId, true);
}
/* int HWOptionBatteryDisable (int busfd, int nBusDevId)
**
** Set the battery enable flag to false on the Real Time Clock
*/
int HWOptionBatteryDisable (int busfd, int nBusDevId)
{
return HWOptionBatteryConfigure (busfd, nBusDevId, false);
}
/* int HWOptionBatteryGetSetting (int busfd, int nBusDevId)
**
** This option is used to get the status of the battery enable flag
*/
int HWOptionBatteryGetSetting (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayBatteryStatus;
char szErrorString [128 +1];
// Clear out the buffer we will read data into
bzero ((void *) &rtcwkdayBatteryStatus, sizeof (struct mcp7940n_rtcwkday));
// Request the data from the RTC
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayBatteryStatus, sizeof (struct mcp7940n_rtcwkday)) < 0 ) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x getting Battery Enable (VBATEN) bit", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Display what was retrieved from memory
(void) printf ("Battery Enable bit is %s.\n", (rtcwkdayBatteryStatus.vbaten ? "Enabled" : "Disabled"));
return 0;
}
/* int HWOptionCalibrateClock (int busfd, int nBusDevId)
**
** This option is used to calibrate the clock. It is typically called only once.
*/
int HWOptionCalibrateClock (int busfd, int nBusDevId)
{
struct mcp7940n_osctrim osctrimTrimValue;
char szErrorString [128 +1];
// Set the trim value. We got the value of 0x47 from the Linux driver and code for the PiFace RTC
osctrimTrimValue.trimval = 0x47;
// Write out the trim value
if (WriteI2CDeviceMemory (busfd, nBusDevId, MCP7940N_OSCTRIM_OFFSET, (void *) &osctrimTrimValue, sizeof (struct mcp7940n_osctrim)) < 0) {
// An error occurred
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x setting trim value", nBusDevId);
(void) perror (szErrorString);
return -1;
}
return 0;
}
/* int HWOptionClearNVRAM (int busfd, int nBusDevId)
**
** Clear the NVRAM on the Real Time Clock
*/
int HWOptionClearNVRAM (int busfd, int nBusDevId)
{
uint8_t NVRAMBuf [64]; // 64 bytes is the size of the NVRAM on the RTC
char szErrorString [128 +1];
// Clear out the buffer we will write data out from (clearing the NVRAM)
bzero ((void *) NVRAMBuf, 64);
// Write the data out to the RTC
if (WriteI2CDeviceMemory (busfd, nBusDevId, MCP7940N_NVRAM_OFFSET, NVRAMBuf, 64) < 0 ) {
// An error occurred. All we can do is display the error
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x", nBusDevId);
(void) perror (szErrorString);
return -1;
}
return 0;
}
/* int HWOptionOscillatorEnable (int busfd, int nBusDevId)
**
** This option is called to enable the external oscillator
*/
int HWOptionOscillatorEnable (int busfd, int nBusDevId)
{
return HWOptionOscillatorConfigure (busfd, nBusDevId, true);
}
/* int HWOptionOscillatorDisable (int busfd, int nBusDevId)
**
** This option is called to disable the external oscillator
*/
int HWOptionOscillatorDisable (int busfd, int nBusDevId)
{
return HWOptionOscillatorConfigure (busfd, nBusDevId, false);
}
/* int HWOptionOscillatorGetSetting (int busfd, int nBusDevId)
**
** This option is used to get the status of the external oscillator
*/
int HWOptionOscillatorGetSetting (int busfd, int nBusDevId)
{
struct mcp7940n_rtcsec rtcsecOscillatorSetting;
char szErrorString [128 +1];
// Clear out the buffer we will read data into
bzero ((void *) &rtcsecOscillatorSetting, sizeof (struct mcp7940n_rtcsec));
// Request the data from the RTC
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCSEC_OFFSET, (void *) &rtcsecOscillatorSetting, sizeof (struct mcp7940n_rtcsec)) < 0 ) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Display what was retrieved from memory
(void) printf ("Oscillator is %s.\n", (rtcsecOscillatorSetting.st ? "Enabled" : "Disabled"));
return 0;
}
/* int HWOptionOscillatorGetStatus (int busfd, int nBusDevId)
**
** This option is used to get the status of the external oscillator
*/
int HWOptionOscillatorGetStatus (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayOscillatorStatus;
char szErrorString [128 +1];
// Clear out the buffer we will read data into
bzero ((void *) &rtcwkdayOscillatorStatus, sizeof (struct mcp7940n_rtcwkday));
// Request the data from the RTC
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayOscillatorStatus, sizeof (struct mcp7940n_rtcwkday)) < 0 ) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Display what was retrieved from memory
(void) printf ("%s\n", (rtcwkdayOscillatorStatus.oscrun ? "Oscillator is enabled and running." : "Oscillator has stopped or been disabled."));
return 0;
}
/* int HWOptionPowerFailStatus (int busfd, int nBusDevId)
**
** Get the power fail status flag value
*/
int HWOptionPowerFailStatus (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayPowerFailStatus;
char szErrorString [128 +1];
// Clear out the buffer we will read data into
bzero ((void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday));
// Request the data from the RTC
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday)) < 0 ) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x getting Power Fail Status (PWRFAIL) bit", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Display what was retrieved from memory
(void) printf ("Power Fail Status bit is %s.\n", (rtcwkdayPowerFailStatus.pwrfail ? "Enabled" : "Disabled"));
return 0;
}
/* int HWOptionPowerFailClearFlag (int busfd, int nBusDevId)
**
** This option is used to clear the power fail flag
*/
int HWOptionPowerFailClearFlag (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayPowerFailStatus;
char szErrorString [128 +1];
// Clear out the buffer we will read data into
bzero ((void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday));
// Request the data from the RTC
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday)) < 0 ) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x getting Power Fail Status (PWRFAIL) bit", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Check that the Power Fail status bit is set
if (rtcwkdayPowerFailStatus.pwrfail == 0) {
// The bit is not set, so simply display a message and return
(void) printf ("The Power Fail Status (PWRFAIL) bit is not set.\n");
return 0;
}
// Clear the flag and write the byte back to the RTC
rtcwkdayPowerFailStatus.pwrfail = 0;
// This is a little risky as we should really turn off the oscillator input,
// to make sure that the day of week does not rollover
//
// TODO: Fix this...
if (WriteI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday)) < 0) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x writing cleared Power Fail Status (PWRFAIL) bit", nBusDevId);
(void) perror (szErrorString);
return -1;
}
return 0;
}
/* int HWOptionControlRegistersDisplay (int busfd, int nBusDevId)
**
** This function is called to display the values of the control registers
*/
int HWOptionControlRegistersDisplay (int busfd, int nBusDevId)
{
struct mcp7940n_control controlControlRegisters;
char szErrorString [128 +1];
// Zero out the control registers ahead of call to read them
bzero (&controlControlRegisters, sizeof (struct mcp7940n_control));
// Read the control registers
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_CONTROL_OFFSET, (void *) &controlControlRegisters, sizeof (struct mcp7940n_control)) < 0) {
// An error occurred, display details and exit
(void) sprintf (szErrorString, "ioctl I2CRDWR for nBusDevId 0x%02x reading control registers", nBusDevId);
(void) perror (szErrorString);
return -1;
}
// Display the control registers
(void) printf ("Square Wave Clock Output Frequency Select: %d\n", controlControlRegisters.sqwfs);
(void) printf ("Coarse Trim Enable: %d\n", controlControlRegisters.crstrim);
(void) printf ("External Oscillator Input: %d\n", controlControlRegisters.extosc);
(void) printf ("Alarm 0 Module Enable: %d\n", controlControlRegisters.alm0en);
(void) printf ("Alarm 1 Module Enable: %d\n", controlControlRegisters.alm1en);
(void) printf ("Square Wave Output Enable: %d\n", controlControlRegisters.sqwen);
(void) printf ("Logic Level for General Purpose Output: %d\n", controlControlRegisters.out);
// Just return
return 0;
}
/* int DisplayPowerFailTime (int busfd, int nBusDevId)
**
** Retrieve the power fail time from the Real Time Clock, and display it
*/
int DisplayPowerFailTime (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayPowerFailStatus;
struct mcp7940n_pwrdn_timestamp timestampPowerDown;
// Before we attempt to retrieve the power down timestamp, check to see if the PWRFAIL flag is
// set or cleared. If it has been cleared we assume that there is no power down time to read
bzero (&rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday));
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday)) < 0) {
// An error occurred, and we could not read the PWRFAIL flag
(void) perror ("Unable to read PWRFAIL flag, assuming no power down data/time information available.\n");
return -1;
}
// Check to make sure that the PWRFAIL flag is set
if (rtcwkdayPowerFailStatus.pwrfail == 0) {
// This is not an error, per se. The PWRFAIL flag is cleared, so we assume that there is no power fail
// data available for us to read
(void) printf ("No power down date/time information available (PWRFAIL bit is cleared).\n");
return 0;
}
// Read the power down date and time from the RTC
bzero (×tampPowerDown, sizeof (struct mcp7940n_pwrdn_timestamp));
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCPWRDN_OFFSET, (void *) ×tampPowerDown, sizeof (struct mcp7940n_pwrdn_timestamp)) < 0) {
// An error occurred
(void) perror ("Unable to read power down date/time from real time clock.\n");
return -1;
}
// Display the date and time we just read in
(void) printf ("%s %s %d %02d:%02d UTC\n",
szDisplayWeekday [(timestampPowerDown.pwrdnmth.wkday -1)],
szDisplayMonth [((timestampPowerDown.pwrdnmth.mthten *10) + timestampPowerDown.pwrdnmth.mthone -1)],
((timestampPowerDown.pwrdndate.dateten *10) + timestampPowerDown.pwrdndate.dateone),
((timestampPowerDown.pwrdnhour.twentyfourhour.twelvetwentyfour == 0)
? ((timestampPowerDown.pwrdnhour.twentyfourhour.hrten * 10) + timestampPowerDown.pwrdnhour.twentyfourhour.hrone)
: (((timestampPowerDown.pwrdnhour.twelvehour.hrten * 10) + timestampPowerDown.pwrdnhour.twelvehour.hrone) + (timestampPowerDown.pwrdnhour.twelvehour.ampm == 1 ? 12 : 0))),
((timestampPowerDown.pwrdnminute.minten * 10) + timestampPowerDown.pwrdnminute.minone));
return 0;
}
/* int DisplayPowerRestoreTime (int busfd, int nBusDevId)
**
** Retrieve the power restore time from the Real Time Clock, and display it
*/
int DisplayPowerRestoreTime (int busfd, int nBusDevId)
{
struct mcp7940n_rtcwkday rtcwkdayPowerFailStatus;
struct mcp7940n_pwrup_timestamp timestampPowerUp;
// Before we attempt to retrieve the power up timestamp, check to see if the PWRFAIL flag is
// set or cleared. If it has been cleared we assume that there is no power down time to read
bzero (&rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday));
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCWKDAY_OFFSET, (void *) &rtcwkdayPowerFailStatus, sizeof (struct mcp7940n_rtcwkday)) < 0) {
// An error occurred, and we could not read the PWRFAIL flag
(void) perror ("Unable to read PWRFAIL flag, assuming no power up data/time information available.\n");
return -1;
}
// Check to make sure that the PWRFAIL flag is set
if (rtcwkdayPowerFailStatus.pwrfail == 0) {
// This is not an error, per se. The PWRFAIL flag is cleared, so we assume that there is no power fail
// data available for us to read
(void) printf ("No power up date/time information available (PWRFAIL bit is cleared).\n");
return 0;
}
// Read the power up date and time from the RTC
bzero (×tampPowerUp, sizeof (struct mcp7940n_pwrup_timestamp));
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCPWRUP_OFFSET, (void *) ×tampPowerUp, sizeof (struct mcp7940n_pwrup_timestamp)) < 0) {
// An error occurred
(void) perror ("Unable to read power down date/time from real time clock.\n");
return -1;
}
// Display the date and time we just read in
(void) printf ("%s %s %d %02d:%02d UTC\n",
szDisplayWeekday [(timestampPowerUp.pwrupmth.wkday -1)],
szDisplayMonth [((timestampPowerUp.pwrupmth.mthten *10) + timestampPowerUp.pwrupmth.mthone -1)],
((timestampPowerUp.pwrupdate.dateten *10) + timestampPowerUp.pwrupdate.dateone),
((timestampPowerUp.pwruphour.twentyfourhour.twelvetwentyfour == 0)
? ((timestampPowerUp.pwruphour.twentyfourhour.hrten * 10) + timestampPowerUp.pwruphour.twentyfourhour.hrone)
: (((timestampPowerUp.pwruphour.twelvehour.hrten * 10) + timestampPowerUp.pwruphour.twelvehour.hrone) + (timestampPowerUp.pwruphour.twelvehour.ampm == 1 ? 12 : 0))),
((timestampPowerUp.pwrupminute.minten * 10) + timestampPowerUp.pwrupminute.minone));
return 0;
}
/* int HWSetTimeOfDay (int busfd, int nBusDevId, char *szDateTime, bool bUseComputerClockToSetRTC)
**
** Set the Real Time Clock with the datetime value passed to us
*/
int HWSetTimeOfDay (int busfd, int nBusDevId, char *szDateTime, bool bUseComputerClockToSetRTC)
{
struct mcp7940n_datetime datetimeRTCClock;
struct timeval tComputerDateTime;
struct timezone tzComputerTimezone;
struct tm tmRTCDateTime, *ptmComputerDateTime;
time_t timeComputerDateTime;
struct mcp7940n_rtcwkday rtcwkdayOscillatorStatus;
int nRetryCount, nDateTimeLength;
char *pszDateTimeDigit;
// Get the current date/time from the RTC. It might not be valid, but we need the various
// flags and other settings mixed amongst the date registers
if (ReadI2CDeviceMemory (busfd, nBusDevId, MCP7940N_RTCDATETIME_OFFSET, (void *) &datetimeRTCClock, sizeof (struct mcp7940n_datetime)) < 0) {
// An error occurred, and we could not read the current date/time
(void) perror ("Unable to read current date/time from real time clock");
return -1;
}
// Check to see if we are to parse the command line, or if we are to use the computer clock
if (bUseComputerClockToSetRTC) {
// Get the current date/time from the computer
if (gettimeofday (&tComputerDateTime, &tzComputerTimezone) < 0) {
// An error occurred, and all we can do is display an error message and return
(void) perror ("gettimeofday");
return -1;
}
// Convert the date/time from seconds into a broken out structure we can use
if ((ptmComputerDateTime = gmtime (&tComputerDateTime.tv_sec)) == (struct tm *) 0) {
// An error occurred, so display an error message and return
(void) perror ("gmtime");
return -1;
}
}
else {
// Copy over the date and time read in from the RTC to a tm structure. It will be easier for us to
// manipulate it in that format
bzero ((void *) &tmRTCDateTime, sizeof (struct tm));
TranslateRTCDateTimeToTm (&datetimeRTCClock, &tmRTCDateTime);
// The RTC stores date/time as UTC, but the user will enter the date and time as local time (we
// assume). Convert the time to local time.
timeComputerDateTime = timegm (&tmRTCDateTime);
if ((ptmComputerDateTime = localtime (&timeComputerDateTime)) == (struct tm *) 0) {
// An error occurred, so display an error message and return
(void) perror ("localtime");
return -1;
}
bcopy (ptmComputerDateTime, &tmRTCDateTime, sizeof (struct tm));
// Get the length of the date/time specified on the command line
nDateTimeLength = strlen (szDateTime);
if (nDateTimeLength %2 == 1) {
// The string supplied on the command line is an odd length, so we assume it ends in
// the characters ".SS", where SS is the seconds in the date/timer we have to write
// to the RTC. We validate that assumption, though
if ((szDateTime [(nDateTimeLength -3)] != '.') || (! isdigit (szDateTime [(nDateTimeLength -2)])) || (! isdigit (szDateTime [(nDateTimeLength -1)]))) {
// The date/time specified on the command line is not in the format we expected
goto dateformaterror; // Ugly hack
}
// Strip off the seconds
tmRTCDateTime.tm_sec = (digittoint (szDateTime [(nDateTimeLength -2)]) * 10) + digittoint (szDateTime [(nDateTimeLength -1)]);
if (tmRTCDateTime.tm_sec > 59)
goto dateformaterror;
nDateTimeLength -= 3; // Strip off the seconds from the length, for our next calculation
}
// We can figure out what we got based on the length of the date and time (minus seconds if processed)
pszDateTimeDigit = szDateTime;
switch (nDateTimeLength) {
case 12: // Century, Months, Days, Hours and Minutes
// Do nothing and fall through as the RTC does not understand century
if (! isdigit (pszDateTimeDigit [0]) || (! isdigit (pszDateTimeDigit [1])))
goto dateformaterror;
pszDateTimeDigit += 2; // Remove the century from the calculation and fall through
case 10: // Years, Months, Days, Hours and Minutes
// Extract the years from the date specified
if (! isdigit (pszDateTimeDigit [0]) || (! isdigit (pszDateTimeDigit [1])))
goto dateformaterror;
tmRTCDateTime.tm_year = (digittoint (pszDateTimeDigit [0]) * 10) + digittoint (pszDateTimeDigit [1]) + 100; // We assume a base of 2000
pszDateTimeDigit += 2; // Remove the years from the calcultaion and fall through
case 8: // Months, Days, Hours and Minutes
// Extract the months from the date specified
if (! isdigit (pszDateTimeDigit [0]) || (! isdigit (pszDateTimeDigit [1])))
goto dateformaterror;
tmRTCDateTime.tm_mon = ((digittoint (pszDateTimeDigit [0]) * 10) + digittoint (pszDateTimeDigit [1]) -1);
if (tmRTCDateTime.tm_mon > 12)
goto dateformaterror;
pszDateTimeDigit += 2; // Remove the months from the calculation and fall through
case 6: // Days, Hours and Minutes
// Extract the days from the date specified
if (! isdigit (pszDateTimeDigit [0]) || (! isdigit (pszDateTimeDigit [1])))
goto dateformaterror;
tmRTCDateTime.tm_mday = (digittoint (pszDateTimeDigit [0]) * 10) + digittoint (pszDateTimeDigit [1]);
if (tmRTCDateTime.tm_mday > 31)
goto dateformaterror;
pszDateTimeDigit += 2; // Remove the months from the calculation and fall through
case 4: // Hours and Minutes
// Extract the hours from the date specified
if (! isdigit (pszDateTimeDigit [0]) || (! isdigit (pszDateTimeDigit [1])))