I made a simple webserver using c. I can connect to it via a web browser and it works fine.
The goal of this webserver was to exploit it. So I wrote a simple python script that sends malicious data to the server. However, I only get an error message on the server saying: "Bad file descriptor".
C-Server Main:
int main(void) {
int sockfd, new_sockfd, yes=1;
struct sockaddr_in host_addr, client_addr;
socklen_t sin_size;
printf("Accepting web requests on port %d\n", PORT);
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
error_and_exit("in socket");
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
error_and_exit("setting socket option SO_REUSEADDR");
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT);
host_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(host_addr.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
error_and_exit("binding to socket");
if (listen(sockfd, 20) == -1)
error_and_exit("listening on socket");
while(1) { // Accept loop
sin_size = sizeof(struct sockaddr_in);
new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
if(new_sockfd == -1)
error_and_exit("accepting connection");
handle_connection(new_sockfd, &client_addr);
}
return 0;
}
python code:
import socket
import struct
import sys
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 8000)
sock.connect(server_address)
shellcode =(....)
values = ....
try:
sock.sendall(values)
finally:
sock.close()
Notes:
1.
the accept function (from <sys/socket.h>) in the while(1) loop returns -1, calling error_and_exit("accepting connection"). So the Server never executes handle_connection for my python client.
2.
Code for error_and_exit function:
void error_and_exit(char *message) {
char error_message[100];
strcpy(error_message, " Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}
Related
i try to create a client written in c++ and a server using python flask. The task is simple, client connect and get data from server, then display it on console. I have two piece of code:
Server:
from flask import Flask
app = Flask(__name__)
#app.route('/hello')
def hello():
return "hello".encode("utf-16")
if __name__ == "__main__":
app.run(debug=True,host="127.0.0.1")
Client:
BOOL bResults = FALSE;
bool ret = false;
DWORD dwDownloaded = 0;
WCHAR wDataRecv[1024] = {0};
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
DWORD dwSize = 0;
HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0); # open session to connect
hConnect = WinHttpConnect(hSession, L"localhost", (port == 0) ? INTERNET_DEFAULT_HTTP_PORT : port, 0); # connect to localhost with port 80 or custom port (this time i use port 5000)
if (!hConnect)
goto Free_And_Exit;
hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/hello", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (hRequest) {
bResults = WinHttpSendRequest(hRequest, NULL, 0,WINHTTP_NO_REQUEST_DATA, 0,0, 0);# send GET request
}
if (bResults)
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (bResults)
{
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
std::cout << "WinHttpQueryDataAvailable failed with code: " << GetLastError();
}
if (!WinHttpReadData(hRequest, wDataRecv, dwSize, &dwDownloaded)) {
std::cout << "WinHttpReadData failed with code: " << GetLastError();
}
std::wcout << wDataRecv; # wcout wont print anything to console
}
Free_And_Exit: #clean up
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
return ret;
I noticed that the data return from server like:
b'\xfe\xff\hello'
Why 0xFEFF is there ?
Its is BOM (byte order mark). I just need to decode from the client or use:
return "hello".encode('UTF-16LE') # not UTF-16
I am trying to make a messenger program (that currently has a ton of bugs so please dismiss them) and for some reason, the server wont let the clients connect. I have tried changing the port, but nothing works. I get the following error (for my client, which is in python) (this is on a mac, but I have tried the client on a windows computer, still nothing):
Traceback (most recent call last):
File "msgclient.py", line 31, in <module>
Program()
File "msgclient.py", line 8, in __init__
self.s.connect((IP, PORT))
ConnectionRefusedError: [Errno 61] Connection refused
Here is the code for the server (written in c):
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#define MAXCLIENTS 256
#define MAXMSG 269
#define PORT 9989
void forward(int clientslist[MAXCLIENTS], char* msg) {
int x;
for (x=0; x < MAXCLIENTS; x++){
send(clientslist[x], msg, sizeof(msg), 0);
}
return;
}
int main(){
int s = socket(AF_INET, SOCK_STREAM, 0);
int clients[MAXCLIENTS];
int clientcounter = 0;
fd_set socketlist, readlist;
FD_ZERO(&socketlist);
FD_SET(s, &socketlist);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;
bind(s, (struct sockaddr*) &server, sizeof(server));
listen(s, MAXCLIENTS);
int clientsocket;
int i;
int rc;
int max = s;
void* msg = (char *) malloc(MAXMSG+1);
void* usr = (char *) malloc(14);
while (1){
readlist = socketlist;
select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
for (i=0; i<max+1; i++){
if(FD_ISSET(i, &readlist)){
if (i == s){
clientsocket = accept(s, NULL, NULL);
FD_SET(clientsocket, &socketlist);
clients[clientcounter] = clientsocket;
clientcounter++;
rc = recv(clientsocket, usr, 10, 0);
printf("Connection received from %s\n", usr);
usr = "\0";
if (clientsocket > max+1){
max = clientsocket;
}
} else {
rc = recv(i, msg, MAXMSG, 0);
if (rc > 0){
forward(clients, msg);
} else{
close(i);
msg = "\0";
}
}
}
}
}
return 0;
}
and the client (written in python):
import socket
class Program:
def __init__(self):
IP = socket.gethostbyname(socket.gethostname())
PORT = 9989
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((IP, PORT))
self.user = self.username()
self.s.send(bytes(self.user, "utf-8"))
while True:
received = self.s.recv(269)
received = received.decode("utf-8")
print(received)
self.enter()
def username(self):
name = str(input("Enter a username (10 character max): "))
if len(name) > 10:
print("Username is larger than 10; try again")
self.username()
return name;
def enter(self):
msg = str(input("Enter a message>> "))
if msg != "":
self.s.send(bytes(f"{self.user}>> {msg}", "utf-8"))
if __name__ == "__main__":
Program()
regarding the function:
void forward(int clientslist[MAXCLIENTS], char* msg)
and
send(clientslist[x], msg, sizeof(msg), 0);
The expression: sizeof(msg) will return a value (depending on your underlying hardware and certain compiler parameters) of 4 or 8, Not what you want. Suggest passing the actual number of bytes to transmit.
regarding the function:
void forward(int clientslist[MAXCLIENTS], char* msg)
and the statement:
return;
The return; statement is completely unnecessary. Suggest removing that statement.
regarding:
int s = socket(AF_INET, SOCK_STREAM, 0);
This statement can fail. Always check (if socket < 0) then handle the error
regarding:
server.sin_addr.s_addr = INADDR_ANY;
INADDR_ANY has the value: "0.0.0.0" which cannot be directly assigned. Suggest:
server.sin_addr.s_addr = htonl(INADDR_ANY);
OT: regarding:
bind(s, (struct sockaddr*) &server, sizeof(server));
and
listen(s, MAXCLIENTS);
These functions can fail. Always check the returned value to assure the operation was successful.
OT: regarding:
void* msg = (char *) malloc(MAXMSG+1);
and similar statements. In C, the returned type is void* which can be assigned to any pointer. Casting just clutters the code and is error prone. even this statement has an error in the cast. Suggest removing that cast.
regarding:
readlist = socketlist;
select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
for (i=0; i<max+1; i++)
{
if(FD_ISSET(i, &readlist))
{
if (i == s)
{
This code sequence forces serial handling of the incoming sockets. Much better to generate a 'thread pool', then use accept() and pass the resulting client socket to an idle thread. The thread then performs all the communication with the client, then, when finishing with the client, closes the client socket.
regarding:
select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
There must already be an open socket to the client, which there is none, so no communication occurs.
there may be other problems, but this should aim you in the right direction.
I'm trying to connect a Flask server with C++ client through a socket connection:
Server:
from flask import Flask
from os.path import dirname, abspath
from queue import Queue
import base64
import cv2
import numpy as np
from PIL import Image
import io
from object_detection import detect_object
d = dirname(dirname(abspath(__file__)))
app = Flask(__name__)
app.queue = Queue()
#app.route("/")
def home():
return "Hello"
#app.route("/")
def test_live(message):
app.queue.put(message['data'])
img_bytes = base64.b64decode(app.queue.get())
img_np = np.array(Image.open(io.BytesIO(img_bytes)))
img_np = detect_object(img_np)
frame = cv2.imencode('.jpg', cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB))[
1
].tobytes()
base64_bytes = base64.b64encode(frame)
base64_string = base64_bytes.decode('utf-8')
if __name__ == '__main__':
app.run(app, host = '127.0.0.1', port = 5000, debug = True)
C++ client
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
using namespace cv;
void main()
{
string ipAddress = "127.0.0.1"; // IP Address of the server
int port = 5000; // Listening port # on the server
// Initialize WinSock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0)
{
cerr << "Can't start Winsock, Err #" << wsResult << endl;
return;
}
// Create socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
// Connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return;
}
// Do-while loop to send and receive data
char buf[4096];
string userInput;
do
{
// Prompt the user for some text
cout << "> ";
getline(cin, userInput);
if (userInput.size() > 0) // Make sure the user has typed in something
{
// Send the text
Mat frame;
frame = imread(userInput.c_str(), IMREAD_COLOR);
int imgSize = frame.total() * frame.elemSize();
int sendResult = send(sock, (const char*) frame.data, imgSize, 0);
if (sendResult != SOCKET_ERROR)
{
// Wait for response
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
// Echo response to console
cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
}
}
}
} while (userInput.size() > 0);
// Gracefully close down everything
closesocket(sock);
WSACleanup();
}
I'm getting this error on the server when I try to send a image from the client:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [10/Feb/2020 11:45:40] code 400, message Bad request syntax ('54043/0.--+*/--1//2-.2-./+**(\'#! \x19\x1c\x1a\x12\x19\x16\x0f\x1a\x17\x13 \x1e\x14%"\x16*+\x17,-\x180.\x1830\x1b63\x1c96\x1b:7\x1c;8\x1e?;\x1eA= C?\x1fGB#JH&QN*WT-\\Y2_\\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z\'VS\'TQ\'OM%LJ\x1eCA\x1c<;\x1654\x17//\x15--\x13--\x1400\x13++')
127.0.0.1 - - [10/Feb/2020 11:45:40] "54043/0.--+*/--1//2-.2-./+**('#! %"*+,-0.306396:7;8?;A= C?GB#JH&QN*WT-\Y2_\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z'VS'TQ'OM%LJCA<;54//----00++" HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [10/Feb/2020 11:46:00] code 400, message Bad request syntax ('54043/0.--+*/--1//2-.2-./+**(\'#! \x19\x1c\x1a\x12\x19\x16\x0f\x1a\x17\x13 \x1e\x14%"\x16*+\x17,-\x180.\x1830\x1b63\x1c96\x1b:7\x1c;8\x1e?;\x1eA= C?\x1fGB#JH&QN*WT-\\Y2_\\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z\'VS\'TQ\'OM%LJ\x1eCA\x1c<;\x1654\x17//\x15--\x13--\x1400\x13++')
127.0.0.1 - - [10/Feb/2020 11:46:00] "54043/0.--+*/--1//2-.2-./+**('#! %"*+,-0.306396:7;8?;A= C?GB#JH&QN*WT-\Y2_\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z'VS'TQ'OM%LJCA<;54//----00++" HTTPStatus.BAD_REQUEST -
I have read that's because my client is trying to connect via HTTPS but I don't find how to change it.
Thanks for your help
I have a multicast packet from a capture using tcpdump. I can replay the packet using tcpreplay -i eth0 on.pcap and I can receive it on another machine using tcpdump.
I have tried c code and python code to try and capture this packet without success. I've tried both on MacOS and Raspian (Rpi 3b).
https://mega.nz/#!ELAgBSDL!XZ3EXCkDBsLLwFn8J1ofWuMm4Z7sssOZPuZVEpmRqvs
here is a c code example:
/*
multicast.c
The following program sends or receives multicast packets. If invoked
with one argument, it sends a packet containing the current time to an
arbitrarily chosen multicast group and UDP port. If invoked with no
arguments, it receives and prints these packets. Start it as a sender on
just one host and as a receiver on all the other hosts
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdio.h>
#define EXAMPLE_PORT 2068
#define EXAMPLE_GROUP "226.2.2.2"
main(int argc)
{
struct sockaddr_in addr;
int addrlen, sock, cnt;
struct ip_mreq mreq;
char message[50];
/* set up socket */
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
perror("socket");
exit(1);
}
bzero((char *)&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(EXAMPLE_PORT);
addrlen = sizeof(addr);
if (argc > 1)
{
/* send */
addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP);
while (1)
{
time_t t = time(0);
sprintf(message, "time is %-24.24s", ctime(&t));
printf("sending: %s\n", message);
cnt = sendto(sock, message, sizeof(message), 0,
(struct sockaddr *) &addr, addrlen);
if (cnt < 0)
{
perror("sendto");
exit(1);
}
sleep(5);
}
}
else
{
/* receive */
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0)
{
perror("bind");
exit(1);
}
mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof(mreq)) < 0)
{
perror("setsockopt mreq");
exit(1);
}
while (1)
{
cnt = recvfrom(sock, message, sizeof(message), 0,
(struct sockaddr *) &addr, &addrlen);
if (cnt < 0)
{
perror("recvfrom");
exit(1);
}
else if (cnt == 0)
{
break;
}
printf("%s: message = \"%s\"\n", inet_ntoa(addr.sin_addr), message);
}
}
}
Here is a python example:
#!/usr/bin/env python
import socket
import binascii
import sys
MCAST_GRP = '226.2.2.2'
MCAST_PORT = 2068
MCAST_IFACE = '192.168.168.200'
def joinMcast(mcast_addr,port,if_ip):
"""
Returns a live multicast socket
mcast_addr is a dotted string format of the multicast group
port is an integer of the UDP port you want to receive
if_ip is a dotted string format of the interface you will use
"""
#create a UDP socket
mcastsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#allow other sockets to bind this port too
mcastsock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#explicitly join the multicast group on the interface specified
mcastsock.setsockopt(socket.SOL_IP,socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(mcast_addr)+socket.inet_aton(if_ip))
#finally bind the socket to start getting data into your socket
mcastsock.bind((mcast_addr,port))
return mcastsock
def main():
sock = joinMcast(MCAST_GRP, MCAST_PORT, MCAST_IFACE)
while True:
print >>sys.stderr, '\nwaiting to receive message'
print sock.recv(1024)
if __name__ == '__main__':
main()
First of all I want to mention that I've gone through a lot of socket threading tutorials before attempting to integrate it into my own GUI, but I still consider myself fairly new to the subject.
I have a server written in python that opens a socket and starts a thread over localhost, and listens over the port for a client:
def StartThread():
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
tcpsock.listen(5)
print "Waiting for incoming connections from client..."
(conn, (ip,port)) = tcpsock.accept()
print 'Got connection from ', (ip,port)
newthread = ClientThread(ip,port,conn, 1)
newthread.start()
return newthread
Here is the ClientThread class:
class ClientThread(Thread):
def __init__(self,ip,port,sock, status):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
self.status = 1
print " New thread started for "+ip+":"+str(port)
After I run the server code, I click a button on my C++ GUI which runs the client code StartConnection() based off the Microsoft Winsock client template.
void CPSR_CRSDlg::OnBnClickedInit2()
{
if(!checkTimerStarted())
// Set mmtimer to aquire the data
{
m_ntimerID = timeSetEvent( TIMERINTRRVAL,
1,
timerHandler,
0,
TIME_PERIODIC);
SetTimer(1,TIMERINTRRVAL_2,NULL);
m_bTimer_started = true;
}
StartConnection();
}
The connection does start successfully and the python code prints the address of the connection and the thread, but then my GUI freezes, so that I can't click any of the other buttons to actually send data over the connection.
Why does my application freeze? Am I not instantiating the thread correctly?
The StartConnection() code is off the msdn website but here is my slightly modified version if needed:
void StartConnection(){
//printf("Connection Starting... \n");
WSADATA wsaData;
ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int argc = 2;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", "client");
return;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
//iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
iResult = getaddrinfo("localhost", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return;
}
return;
}
void StopConnection(){
closesocket(ConnectSocket);
WSACleanup();
return;
}
void SendJointValues(double *joints){
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
j = parseJSON(joints[0],joints[1],joints[2],joints[3], \
joints[4],joints[5]);
int x = send(ConnectSocket, j, strlen(j), 0);
//iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
}
Edit:
The GUI does respond again after I send data via the server, and the client then successfully sends back one iteration of data. But after this exchange the GUI freezes again until more data is sent.
Here is the send+receive portion of the server:
def receiveData(self):
while (self.status == 1):
joints = [0,0,0,0,0,0]
self.sock.sendall('send')
print "Data Sent!"
data = self.sock.recv(4096)
print "Data received: ", data
self.checkStatus(data)
print "Status is: ", self.status
if (self.status == 1):
data_loaded = json.loads(data)
joints = self.createJointArr(data_loaded['Joints'])
time.sleep(0.5)
print joints
return joints
And the SendJointValues() in the client is called in this Timer function:
void CPSR_CRSDlg::OnTimer(UINT_PTR nIDEvent)
{
CString str;
long Position;
double engPosition;
double dblPosition;
double dblSpeed;
bool ret;
// Arch
USB4_01.Controller_3.getEncoderPosition(Position);
countTodegree(Position,engPosition,ARCH);
str.Format(_T("%10.2f"),engPosition);
m_staPosArch.SetWindowText(str);
// Wrist Pitch
USB4_01.Controller_2.getEncoderPosition(Position);
countTodegree(Position,engPosition,TILT);
str.Format(_T("%10.2f"),engPosition);
m_staPosPitch.SetWindowText(str);
// Linear
USB4_02.Controller_1.getEncoderPosition(Position);
countTodegree(Position,engPosition,LINEAR);
str.Format(_T("%10.2f"),engPosition);
m_staPosLinear.SetWindowText(str);
// Turret
USB4_02.Controller_2.getEncoderPosition(Position);
countTodegree(Position,engPosition,TURRET);
str.Format(_T("%10.2f"),engPosition);
m_staPosTurret.SetWindowText(str);
// Roll
USB4_02.Controller_4.getEncoderPosition(Position);
countTodegree(Position,engPosition,ROLL);
str.Format(_T("%10.2f"),engPosition);
m_staPosRoll.SetWindowText(str);
// Drill/Tool
USB4_02.Controller_3.getEncoderPosition(Position);
countTodegree(-Position,engPosition,DRILL);
str.Format(_T("%10.2f"),engPosition);
m_staPosDrill.SetWindowText(str);
// For Penetrate joint
if(JntPenetration.isInitialized())
{
// Get Position feedback
ret = JntPenetration.getPosition(dblPosition);
if(ret) // get position feedback successfully
{
Position = (long) dblPosition;
countTodegree(Position,engPosition,PENETRATE);
str.Format(_T("%10.2f"),engPosition);
m_staPosPenetrate.SetWindowText(str);
m_dCurentPentrationPosition = engPosition;
}
// Get Speed feedback;
if(m_bDrilling_started)
{
// Penetration position close enough AND At least on cycle reached
if( (abs(engPosition - m_dDrilling_target_position) < 0.1) &&(m_Direction_Changed == true))
m_bPenetrationStopped = true;
else
m_bPenetrationStopped = false;
//JntPenetration.getSpeed(dblSpeed);
//if(dblSpeed < .05 )
// m_bPenetrationStopped = true;
//else
// m_bPenetrationStopped = false;
}
}
SendJointValues(JointArray);
// For drilling motion control
if(m_bDrilling_started)
drilingProcedure();
CDialog::OnTimer(nIDEvent);
}