3 * UCC (University [of WA] Computer Club) Electronic Accounting System
5 * handler_door.c - Door Relay code
7 * This file is licenced under the 3-clause BSD Licence. See the file
8 * COPYING for full details.
23 #include <semaphore.h>
26 #define DOOR_UNLOCKED_DELAY 10 // Time in seconds before the door re-locks
31 void* Door_Lock(void* Unused);
32 int Door_InitHandler();
33 int Door_CanDispense(int User, int Item);
34 int Door_DoDispense(int User, int Item);
37 tHandler gDoor_Handler = {
43 char *gsDoor_SerialPort; // Set from config in main.c
44 sem_t gDoor_UnlockSemaphore;
45 pthread_t gDoor_LockThread;
48 void* Door_Lock(void* Unused __attribute__((unused)))
52 sem_wait(&gDoor_UnlockSemaphore);
54 int door_serial_handle = InitSerial(gsDoor_SerialPort, 9600);
55 if(door_serial_handle < 0)
57 fprintf(stderr, "Unable to open door serial '%s'\n", gsDoor_SerialPort);
58 perror("Opening door port");
64 tcgetattr(door_serial_handle, &info);
65 info.c_cflag &= ~CLOCAL;
66 tcsetattr(door_serial_handle, TCSANOW, &info);
69 if(write(door_serial_handle, "\xff\x01\x01", 3) != 3) // Relay ON
71 fprintf(stderr, "Failed to write Relay ON (unlock) command, errstr: %s", strerror(errno));
74 sleep(DOOR_UNLOCKED_DELAY);
76 if(write(door_serial_handle, "\xff\x01\x00", 3) != 3) // Relay OFF
78 fprintf(stderr, "Failed to write Relay OFF (lock) command, errstr: %s", strerror(errno));
81 close(door_serial_handle);
85 int Door_InitHandler(void)
87 // Initialize semaphore, triggers door lock release if semaphore is greater than 0
88 sem_init(&gDoor_UnlockSemaphore, 0, 0);
90 pthread_create(&gDoor_LockThread, NULL, &Door_Lock, NULL);
97 int Door_CanDispense(int User, int Item)
100 printf("Door_CanDispense: (User=%i,Item=%i)\n", User, Item);
103 if( Item != 0 ) return -1;
105 if( !(Bank_GetFlags(User) & USER_FLAG_DOORGROUP) )
108 printf("Door_CanDispense: User %i not in door\n", User);
114 printf("Door_CanDispense: User %i can open the door\n", User);
121 * \brief Actually do a dispense from the coke machine
123 int Door_DoDispense(int User, int Item)
126 printf("Door_DoDispense: (User=%i,Item=%i)\n", User, Item);
130 if( Item != 0 ) return -1;
132 // Check if user is in door
133 if( !(Bank_GetFlags(User) & USER_FLAG_DOORGROUP) )
136 printf("Door_CanDispense: User %i not in door\n", User);
142 if(sem_post(&gDoor_UnlockSemaphore))
144 perror("Failed to post \"Unlock Door\" semaphore, sem_post returned");
149 printf("Door_DoDispense: User %i opened door\n", User);