summaryrefslogtreecommitdiff
path: root/netfs/comms.cpp
blob: 86a7313497483cf0b081aebf5eda68b5111d0d66 (plain)
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
#include <queue>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "threads.h"
#include "comms.h"
#include "msgtypes.h"

Semaphore outQueueSl(0);
Semaphore outQueueSu(30);
Semaphore inQueueS(0);
Mutex outQueueM;
Mutex inQueueM;
std::queue<PacketPtr> outQueue;
std::queue<PacketPtr> inQueue;

Packet::Packet(uint8_t i, DataPayloadPtr p) :
	index(i),
	data(p)
{
}
void
sendPacket(PacketPtr p)
{
	outQueueSu.wait();
	outQueueSl.post();
	AutoMutex am(outQueueM);
	outQueue.push(p);
}

void
packetSender(FILE * host)
{
	while (1) {
		outQueueSl.wait();
		AutoMutex am(outQueueM);
		// We can indicate an exit request by posting the semaphore without putting
		// anything in the queue
		if (outQueue.size() == 0) {
			break;
		}
		outQueue.front()->write(host);
		outQueueSu.post();
	}
}

Packet::Packet(FILE * host)
{
	if (fread(&index, sizeof(index), 1, host) != 1) {
		// error
	}
	DataPayload::TypeID t = 0;
	if (fread(&t, sizeof(t), 1, host) != 1) {
		// error
	}
	data = MsgFacs()[t]();
	data->Read(host);
}
void
Packet::write(FILE * host) const
{
	if (fwrite(&index, sizeof(index), 1, host) != 1) {
		// error
	}
	DataPayload::TypeID t = data->dataTypeID();
	if (fwrite(&t, sizeof(t), 1, host) != 1) {
		// error
	}
	data->Send(host);
	if (fflush(host) != 0) {
		//
	}
}

PacketPtr
recvPacket()
{
	inQueueS.wait();
	AutoMutex am(inQueueM);
	PacketPtr rtn = inQueue.front();
	inQueue.pop();
	return rtn;
}

ContentBase::~ContentBase()
{
}