1 /* 2 * Copyright 2012, Adrien Destugues, pulkomandy@gmail.com 3 * Distributed under the terms of the MIT licence. 4 */ 5 6 7 #include <stdio.h> 8 9 #include "SerialApp.h" 10 11 #include "SerialWindow.h" 12 13 14 SerialApp::SerialApp() 15 : 16 BApplication(SerialApp::kApplicationSignature) 17 { 18 fWindow = new SerialWindow(); 19 20 fSerialLock = create_sem(0, "Serial port lock"); 21 thread_id id = spawn_thread(PollSerial, "Serial port poller", 22 B_LOW_PRIORITY, this); 23 resume_thread(id); 24 } 25 26 27 void SerialApp::ReadyToRun() 28 { 29 fWindow->Show(); 30 } 31 32 33 void SerialApp::MessageReceived(BMessage* message) 34 { 35 switch(message->what) 36 { 37 case kMsgOpenPort: 38 { 39 const char* portName; 40 message->FindString("port name", &portName); 41 fSerialPort.Open(portName); 42 release_sem(fSerialLock); 43 break; 44 } 45 case kMsgDataRead: 46 { 47 // forward the message to the window, which will display the 48 // incoming data 49 fWindow->PostMessage(message); 50 break; 51 } 52 case kMsgDataWrite: 53 { 54 const char* bytes; 55 ssize_t size; 56 57 message->FindData("data", B_RAW_TYPE, (const void**)&bytes, &size); 58 fSerialPort.Write(bytes, size); 59 } 60 default: 61 BApplication::MessageReceived(message); 62 } 63 } 64 65 66 /* static */ 67 status_t SerialApp::PollSerial(void*) 68 { 69 SerialApp* application = (SerialApp*)be_app; 70 char buffer[256]; 71 72 for(;;) 73 { 74 ssize_t bytesRead; 75 76 bytesRead = application->fSerialPort.Read(buffer, 256); 77 if (bytesRead == B_FILE_ERROR) 78 { 79 // Port is not open - wait for it and start over 80 acquire_sem(application->fSerialLock); 81 } else if (bytesRead > 0) { 82 // We read something, forward it to the app for handling 83 BMessage* serialData = new BMessage(kMsgDataRead); 84 serialData->AddData("data", B_RAW_TYPE, buffer, bytesRead); 85 be_app_messenger.SendMessage(serialData); 86 } 87 } 88 89 // Should not reach this line anyway... 90 return B_OK; 91 } 92 93 const char* SerialApp::kApplicationSignature 94 = "application/x-vnd.haiku.SerialConnect"; 95 96 97 int main(int argc, char** argv) 98 { 99 SerialApp app; 100 app.Run(); 101 } 102