Search

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

[CPP] Windows Service 간단하게 만들기

















Service.cpp

Service.h




Service 클래스 추가




stdafx.h 에 필요한 헤더파일 추가



#include <iostream>
#include <conio.h>
#include <WinSvc.h>





main.cpp 에 필요한 내용 추가



// ConsoleApplication5.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.

//

 

#include "stdafx.h"

#include "Service.h"

#include "ConsoleApplication5.h"

 

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

 

 

UINT MTServerThread(LPVOID pParam);

class CUpdateService : public CService{

public:

      CWinThread *_thread;

      void main(void){

            CService::Begin(_T("ConsoleApplication5"));

 

            // TODO : 서비스에서 실행 할 작업을 아래에 작성합니다.

 

            CService::End();

      }

protected:

      void OnStarted(){

            _thread = AfxBeginThread(MTServerThread, 0);

      }

      void OnStopped(){

            DWORD dwExitCode;

            GetExitCodeThread(_thread->m_hThread, &dwExitCode);

            WSACleanup();

      }

};

UINT MTServerThread(LPVOID pParam){

      return 0;

 

}

 

 

// 유일한 응용 프로그램 개체입니다.

 

CWinApp theApp;

 

using namespace std;

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

      int nRetCode = 0;

 

      HMODULE hModule = ::GetModuleHandle(NULL);

 

      if (hModule != NULL)

      {

            // MFC를 초기화합니다. 초기화하지 못한 경우 오류를 인쇄합니다.

            if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))

            {

                  // TODO: 오류 코드를 필요에 따라 수정합니다.

                  _tprintf(_T("심각한 오류: MFC를 초기화하지 못했습니다.\n"));

                  nRetCode = 1;

            }

            else

            {

                  // TODO: 응용 프로그램의 동작은 여기에서 코딩합니다.

                  CUpdateService upServ;

                  if (argc == 2){

                        if (_tcscmp(argv[1], _T("-i")) == 0){

                             upServ.Install(_T("ConsoleApplication5"));

                        }

                        else if (_tcscmp(argv[1], _T("-u")) == 0){

                             upServ.Uninstall(_T("ConsoleApplication5"));

                        }

                        return true;

                  }

                  upServ.main();

            }

      }

      else

      {

            // TODO: 오류 코드를 필요에 따라 수정합니다.

            _tprintf(_T("심각한 오류: GetModuleHandle 실패\n"));

            nRetCode = 1;

      }

 

      return nRetCode;

}

 





'Programming > C,CPP,CS' 카테고리의 다른 글

WAVE form wFormatTag IDs  (0) 2018.04.04
CString Tokenize  (0) 2017.10.19
WaitForMultipleObjects  (0) 2017.04.19
How do I add my domain name to my computers host file?  (0) 2017.04.06
[VS2013] 힙이 손상되었습니다.  (0) 2017.04.05
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

아두이노 & CPP 연동


출처 : http://playground.arduino.cc/Interfacing/CPPWindows#.UxLbvuN_uSo




SerialClass.h

#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED

#define ARDUINO_WAIT_TIME 2000

#include 
#include 
#include 

class Serial
{
    private:
        //Serial comm handler
        HANDLE hSerial;
        //Connection status
        bool connected;
        //Get various information about the connection
        COMSTAT status;
        //Keep track of last error
        DWORD errors;

    public:
        //Initialize Serial communication with the given COM port
        Serial(char *portName);
        //Close the connection
        //NOTA: for some reason you can't connect again before exiting
        //the program and running it again
        ~Serial();
        //Read data in a buffer, if nbChar is greater than the
        //maximum number of bytes available, it will return only the
        //bytes available. The function return -1 when nothing could
        //be read, the number of bytes actually read.
        int ReadData(char *buffer, unsigned int nbChar);
        //Writes data from a buffer through the Serial connection
        //return true on success.
        bool WriteData(char *buffer, unsigned int nbChar);
        //Check if we are actually connected
        bool IsConnected();


};

#endif // SERIALCLASS_H_INCLUDED
SerialClass.cpp
#include "SerialClass.h"

Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFile(portName,
            GENERIC_READ ,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             //Set the parameters and check for their proper application
             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
             }
             else
             {
                 //If everything went fine we're connected
                 this->connected = true;
                 //We wait 2s as the arduino board will be reseting
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}

Serial::~Serial()
{
    //Check if we are connected before trying to disconnect
    if(this->connected)
    {
        //We're no longer connected
        this->connected = false;
        //Close the serial handler
        CloseHandle(this->hSerial);
    }
}

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}


bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);

        return false;
    }
    else
        return true;
}

bool Serial::IsConnected()
{
    //Simply return the connection status
    return this->connected;
}
main.cpp
#include 
#include 
#include "SerialClass.h"	// Library described above
#include 

// application reads from the specified serial port and reports the collected data
int main(int argc, _TCHAR* argv[])
{
	printf("Welcome to the serial test app!\n\n");

	Serial* SP = new Serial("\\\\.\\COM3");    // adjust as needed

	if (SP->IsConnected())
		printf("We're connected");

	char incomingData[256] = "";			// don't forget to pre-allocate memory
	//printf("%s\n",incomingData);
	int dataLength = 256;
	int readResult = 0;
	FILE *f;
	f = fopen("TempData.txt","w");

	while(SP->IsConnected())
	{
		readResult = SP->ReadData(incomingData,dataLength);
		//		printf("Bytes read: (-1 means no data available) %i\n",readResult);

		std::string test(incomingData);

		printf("%s",incomingData);

		char* token = strtok(incomingData, " ");
		while (token!=NULL) {
			fprintf(f,"\t%s",token);
			token = strtok(NULL, " ");
		}
		
		// strtok // token
		test = "";

		Sleep(1000);
	}
	fclose(f);
	return 0;
}

'Programming > C,CPP,CS' 카테고리의 다른 글

CString Convert 변환  (0) 2014.03.08
MFC 시리얼 통신 클래스  (0) 2014.03.08
아두이노 기본 세팅  (0) 2014.03.02
CPP 연산자 오버로딩  (0) 2014.01.16
CPP 연산자 오버로딩  (0) 2014.01.16

JAVA Console Token 구현

Programming/JAVA,JSP 2013. 8. 7. 13:37 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		int count = 0;

		for (int i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				count++;
			} else
			{
			}
		}
		String[] textResult = new String[count + 1];

		int i, j, k;
		for (i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				textResult[0] = text.substring(0, i);
				break;
			}
		}
		System.out.print(textResult[0]);
		int lastValue =	0;
		for (k = 1; i < text.length(); k++)
		{
			i = i + 1;
			j = i;
			for (; i < text.length(); i++)
			{
				if (text.charAt(i) == ' ')
				{
					System.out.print("\n");
					textResult[k] = text.substring(j, i);
					lastValue = i;
					break;
				}
			}
		}
		textResult[k-1] = text.substring(lastValue+1 , text.length() );		
		for( String s : textResult )
		{
			System.out.println(s);
		}
	}
}
시스템 라이브러리를 활용
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		
		StringTokenizer st = new StringTokenizer(text, " ");
		
		while(st.hasMoreTokens() )
		{
			System.out.println(st.nextToken());
		}
	}
}