shithub: pronterfs

ref: ca59c67aaaddd3409efa08ab1299821274559768
dir: pronterfs/machine.c

View raw version
#include <u.h>
#include <libc.h>
#include <thread.h>
#include <bio.h>
#include "machine.h"

char *filename;
Channel *chan;

int running;

int
initmachine(char* file, Channel *c)
{
	filename = file;
	
	chan = c;
	return 1;
}

void
machineloop(void *c)
{
	Channel *ch = (Channel*)c;
	int cmd;
	int fd;
	Biobuf *bin, *bout;
	void *buf;
	
	fd = open(filename, ORDWR);
	if (fd < 0) {
		sysfatal("can't open device file: %r");
	}
	
	bin = Bfdopen(fd, OREAD);
	bout = Bfdopen(fd, OWRITE);
	if (!(bin && bout))
		sysfatal("can't Bfdopen: %r");
	
	while (1) {
		if (nbrecv(ch, &cmd)) {
		
			if (running) {
				switch (cmd) {
				case M_Start:
					break;
				case M_Stop:
					running = 0;
#ifdef SIMULATE
					Bprint(bout, "; stopped\n");
#endif
					break;
				case M_Status:
					break;
				}
			} else {
				switch (cmd) {
				case M_Start:
					running = 1;
#ifdef SIMULATE
					Bprint(bout, "; started\n");
#endif
					break;
				case M_Stop:
					break;
				case M_Status:
					break;
				}
			}

		}
		
		// discard everything the printer sends
		while (Bbuffered(bin) > 0)
			Brdline(bin, '\n');
		
		if (!running)
			continue;
		
		// machinery: write program code
		if (program.pc >= program.data + program.size) {
			running = 0;
			continue;
		}
		
		char* endl = strchr(program.pc, '\n');
		if (endl == nil) {
			endl = program.data + program.size - 1;
		}
		long nbytes = endl - program.pc + 1;
		int n = Bwrite(bout, program.pc, nbytes);
		
		if (n != nbytes)
			continue;
		
		program.pc = endl + 1;
		
		Bflush(bout);
		
		// read ok
		buf = Brdline(bin, '\n');
		if (buf) {
			if (strncmp(buf, "ok", 2) == 0) {
				;
			}
			//free(buf);
		}
	}
}


void
startmachine()
{
	int cmd = M_Start;
	send(chan, &cmd);
}

void
stopmachine()
{
	int cmd = M_Stop;
	send(chan, &cmd);
}