sync.bzz (Source)

# Calculates the next flash time based on the offset received
function receiveOffset() {
	neighbors.listen("offset", function(vid, value, rid){
		t = iteration + value 
		c = next_flash + FLASH_PERIOD/2
		d = t + FLASH_PERIOD/2

		if((next_flash < t) and c > t) {
			next_flash = next_flash + 1
		}
		else if((next_flash > t) and (next_flash < d)) {
			next_flash = next_flash - 1
		}
	})
}

# Send own offset to neighbors
function sendOffset() {
	if(next_flash >= iteration) {
		offset = next_flash - iteration
	} else {
		offset = 0
	}
	neighbors.broadcast("offset", offset)
}

# Executed at init time
function init() { 
	iteration = 0
	FLASH_PERIOD = 30
	FLASH_LENGTH = 3
	rng.setseed(id)
	next_flash = rng.uniform(1,200) % 30
	 # random number generator goes here instead of ID
	receiveOffset()
}

# Executed every time step
function step() {
	log(id, next_flash)
	iteration = iteration + 1
	if(iteration > next_flash) {
		next_flash = iteration + FLASH_PERIOD
	}

	a = iteration + FLASH_PERIOD
	b = next_flash + FLASH_LENGTH

	if(a < b) {
		setleds(255,0,0)
	} else {
		setleds(0,0,0)
	}

	if(iteration > 50 and iteration % 10 == 0) {
		sendOffset()
	}
}

# Executed once when the robot (or the simulator) is reset.
function reset() {
}
# Execute at exit
function destroy() {
}