~npisanti/grimorio

0affa64f78d46679299fc3310f36c31d2be67c46 — Nicola Pisanti a month ago a0ca07b
porting scripts to fish
42 files changed, 109 insertions(+), 674 deletions(-)

D bin/1mp-exile
D bin/ardour
M bin/batch_wav_to_mp3.sh
M bin/battery_status.sh
M bin/blank.sh
D bin/check_gcc_defines.sh
R bin/{checkjack.sh => check_jack.sh}
M bin/check_repo_updates.sh
M bin/check_screncasting.sh
M bin/cleanmacshit.sh
M bin/cpu_performance.sh
M bin/cpu_powersave.sh
D bin/ctags_oF_geany.sh
M bin/desktop.sh
M bin/display_256_colors.sh
M bin/dotgrid
M bin/eye
M bin/fff
M bin/folderkit
D bin/fritzing.sh
D bin/gcc_defines.sh
M bin/glsl
M bin/glsl_cam
M bin/glsl_drop
M bin/glsl_gif
D bin/lamp_start.sh
D bin/lamp_stop.sh
D bin/left
D bin/love
D bin/masterbus
D bin/miscela
D bin/of-projectgen.sh
D bin/ofgeanybuild.sh
D bin/orcaJS
D bin/orcafork
D bin/ossia.sh
D bin/pilot
D bin/pixelscript
D bin/ronin
D bin/sitter.py
D bin/substrata
D bin/wolframkit
D bin/1mp-exile => bin/1mp-exile +0 -14
@@ 1,14 0,0 @@
#!/bin/bash

exec ~/oF/apps/1mp-exile/band/bin/band & 

pkill -USR1 redshift

sleep 2

cd ~/oF/apps/1mp-exile/
terminator -b  -T 'orca' --geometry 1920x916+0+256 --profile=orcam 

pkill -USR1 redshift

exit

D bin/ardour => bin/ardour +0 -7
@@ 1,7 0,0 @@
#!/bin/bash
if [ "$1" == "" ]; then
    exec ~/apps/ardour/gtk2_ardour/ardev 
else
    exec ~/apps/ardour/gtk2_ardour/ardev  "$@"
fi
exit

M bin/batch_wav_to_mp3.sh => bin/batch_wav_to_mp3.sh +5 -7
@@ 1,14 1,12 @@
#!/bin/bash
#!/usr/bin/fish

SAVEIF=$IFS

IFS=$(echo -en "\n\b")

for file in $(ls *wav)

do 
	name=${file%%.wav}
	lame -V0 -h -b 320 -cbr $name.wav $name.mp3
done
for file in *.wav
	set name ( basename $file .wav )
	lame -V0 -h -b 320 -cbr $file $name.mp3
end

IFS=$SAVEIF

M bin/battery_status.sh => bin/battery_status.sh +9 -9
@@ 1,12 1,12 @@
#!/bin/bash
#!/usr/bin/fish

ETA=$( acpi -b | awk '{print $5}' | sed 's/,//g' )
NOT=$( acpi -b | awk '{print $3}' | sed 's/,//g' )
STATUS=$( acpi -b | awk '{print $3 " " $4}' | sed 's/,//g' )
if [ "$ETA" == "discharging" ] || [ "$NOT" == "Not" ];
then
  STATUS="AC / Full"
fi
echo "$STATUS"
set eta ( acpi -b | awk '{print $5}' | sed 's/,//g' )
set not ( acpi -b | awk '{print $3}' | sed 's/,//g' )
set bat_status ( acpi -b | awk '{print $3 " " $4}' | sed 's/,//g' )
if test "$eta" = "discharging" || test "$not" = "Not"
  set bat_status "AC / Full"
end

echo "$bat_status"

exit

M bin/blank.sh => bin/blank.sh +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/bin/sh

sleep 1
#xset dpms force standby

D bin/check_gcc_defines.sh => bin/check_gcc_defines.sh +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
gcc -dM -E - < /dev/null 
exit

R bin/checkjack.sh => bin/check_jack.sh +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/bin/sh

ps -Leo class,comm,rtprio | grep jack


M bin/check_repo_updates.sh => bin/check_repo_updates.sh +9 -45
@@ 1,51 1,15 @@
#!/bin/bash
declare -a paths
declare -a forks
#!/usr/bin/fish

paths=(
    "oF"
    "apps/Orca-c"
    "apps/Orca"
    "apps/Dotgrid"
    "apps/Ronin"
    "apps/create_ap"
    "apps/FlameGraph"
    "oF/addons/ofxAddonTemplate"
    "oF/addons/ofxBox2d"
    "oF/addons/ofxCv"
    "oF/addons/ofxCvPiCam"
    "oF/addons/ofxEasing"
    "oF/addons/ofxGLWarper"
    "oF/addons/ofxGPIO"
    "oF/addons/ofxMidi"
    "oF/addons/ofxRapidLib"
    "oF/addons/ofxWatchFile"
    "apps/ardour"
)
set paths "apps/Dotgrid" "apps/create_ap" "apps/FlameGraph" "apps/ardour"

#forks=(
#    "apps/Orca-c"
#)

for i in "${paths[@]}"
do
for i in $paths
    cd "$HOME/$i"
    git fetch -q
    status=`git status | sed -n 2p`
    if [ "$status" != "Your branch is up-to-date with 'origin/master'." ]; then
        echo "[ $i ] $status"
    fi
done

#for i in "${forks[@]}"
#do
#    cd "$HOME/$i"
#    git fetch -q upstream
#    status=`git diff master upstream/master`
#    if [ "$status" != "" ]; then
#        echo "[ $i ] there are difference between your fork and upstream"
#    fi
#done

    set repo_status (git status | sed -n 2p)
    
    if test "$repo_status" != "Your branch is up to date with 'origin/master'."
        echo "[ $i ] $repo_status"
   	end
end

exit

M bin/check_screncasting.sh => bin/check_screncasting.sh +7 -7
@@ 1,16 1,16 @@
#!/bin/bash
#!/usr/bin/fish

VIDEO=$( pgrep ffmpeg )
AUDIO=$( pgrep jack_capture )
set VIDEO ( pgrep ffmpeg )
set AUDIO ( pgrep jack_capture )

if [ "$VIDEO" != "" ] && [ "$AUDIO" != "" ]; then
if test "$VIDEO" != "" && test "$AUDIO" != ""
    echo "Audio/Video"
elif [ "$VIDEO" != "" ] ; then
else if test "$VIDEO" != ""
    echo "Video"
elif [ "$AUDIO" != "" ] ; then
else if test "$AUDIO" != ""
    echo "Audio"
else
    echo "Nothing"
fi
end

exit

M bin/cleanmacshit.sh => bin/cleanmacshit.sh +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/bin/sh
find . -name '._*' -delete
find . -name '.DS*' -delete
exit

M bin/cpu_performance.sh => bin/cpu_performance.sh +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/usr/bin/fish

sudo cpufreq-set -c 0 -g performance
sudo cpufreq-set -c 1 -g performance

M bin/cpu_powersave.sh => bin/cpu_powersave.sh +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/usr/bin/fish

sudo cpufreq-set -c 0 -g powersave
sudo cpufreq-set -c 1 -g powersave

D bin/ctags_oF_geany.sh => bin/ctags_oF_geany.sh +0 -19
@@ 1,19 0,0 @@
#!/bin/bash

if [ -d "/home/$USER/oF" ]; then

    cd /home/$USER/oF/addons
    find -type f -name "*.h" -print0 | xargs -0 geany -gP ofx.cpp.tags
    sleep 1
    mv ofx.cpp.tags /home/$USER/.config/geany/tags

    cd /home/$USER/oF/libs/openFrameworks
    find -type f -name "*.h" -print0 | xargs -0 geany -gP of.cpp.tags
    sleep 1
    mv of.cpp.tags /home/$USER/.config/geany/tags

    echo "oF ctags setted"

fi

exit

M bin/desktop.sh => bin/desktop.sh +1 -1
@@ 1,3 1,3 @@
#!/bin/bash
#!/bin/sh
thunar ~/desktop
exit

M bin/display_256_colors.sh => bin/display_256_colors.sh +6 -4
@@ 1,5 1,7 @@
#!/bin/bash
for i in {0..255}; do
     printf "\x1b[38;5;${i}mcolour${i}\x1b[0m\n"
done
#!/usr/bin/fish

for i in (seq 255)
     printf "\x1b[38;5;%imcolour%i\x1b[0m\n" "$i" "$i"
end

exit
\ No newline at end of file

M bin/dotgrid => bin/dotgrid +1 -1
@@ 1,4 1,4 @@
#!/bin/bash
#!/bin/sh
cd ~/apps/Dotgrid/desktop
npm start
exit

M bin/eye => bin/eye +1 -1
@@ 1,3 1,3 @@
#!/bin/bash
#!/bin/sh
rly ~/tools/rl_tools/eye
exit

M bin/fff => bin/fff +2 -2
@@ 1,3 1,3 @@
#!/bin/bash
exec /home/$USER/apps/fff/fff "$@"
#!/usr/bin/fish
exec /home/$USER/apps/fff/fff $argv
exit

M bin/folderkit => bin/folderkit +2 -2
@@ 1,3 1,3 @@
#!/bin/sh
exec /home/$USER/tools/folderkit/bin/folderkit "$@"
#!/usr/bin/fish
exec /home/$USER/tools/folderkit/bin/folderkit $argv
exit

D bin/fritzing.sh => bin/fritzing.sh +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
QT_AUTO_SCREEN_SCALE_FACTOR=0 exec ~/archivio/apps/fritzing-app/Fritzing -parts ~/archivio/apps/fritzing-parts
exit

D bin/gcc_defines.sh => bin/gcc_defines.sh +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
gcc -dM -E - < /dev/null 
exit

M bin/glsl => bin/glsl +14 -8
@@ 1,13 1,19 @@
#!/bin/bash
#!/usr/bin/fish

if [ -z "$1" ]; then
    echo "please give an argument"
if test -z "$argv[1]"
    echo "USAGE: shadername.frag [width height] [downsample]"
else
	
	ABSOLUTE=$PWD
	ABSOLUTE+="/$1"
	set first (string sub -l 1 "$argv[1]") 
	switch "$first"
	case "~"
		set ABSOLUTE "$argv[1]"
	case "/"
		set ABSOLUTE "$argv[1]"
	case "*"
		set ABSOLUTE "$PWD/$argv[1]"
	end

	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shader/main.lua "$ABSOLUTE" $1 $2 $3 $4 
fi
	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shader/main.lua "$ABSOLUTE" $argv[1] $argv[2] $argv[3] $argv[4] 
end

exit

M bin/glsl_cam => bin/glsl_cam +19 -15
@@ 1,21 1,25 @@
#!/bin/bash
#!/usr/bin/fish

if [ -z "$1" ]; then
    echo "please give an argument"
if test -z "$argv[1]"
    echo "USAGE: shadername.frag [ /dev/yourvideodevice ] [width height] [downsample]"
else
	
	ABSOLUTE=$PWD
	ABSOLUTE+="/$1"
	set first (string sub -l 1 "$argv[1]") 
	switch "$first"
	case "~"
		set ABSOLUTE "$argv[1]"
	case "/"
		set ABSOLUTE "$argv[1]"
	case "*"
		set ABSOLUTE "$PWD/$argv[1]"
	end

	DEVICE=""
	if [ -z "$2" ]; then
		DEVICE+="/dev/video0"
	else
		DEVICE+="$2"
	fi
	if test -z "$argv[2]"
		set device "/dev/video0"
	else 
		set device "$argv[2]"
	end

	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shadercam/main.lua "$ABSOLUTE" "$DEVICE"

fi
	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shadercam/main.lua "$ABSOLUTE" $argv[1] "$device" $argv[2] $argv[3] $argv[4] 
end

exit

M bin/glsl_drop => bin/glsl_drop +14 -9
@@ 1,14 1,19 @@
#!/bin/bash
#!/usr/bin/fish

if [ -z "$1" ]; then
    echo "please give an argument"
if test -z "$argv[1]"
    echo "USAGE: shadername.frag [width height] [downsample]"
else
	
	ABSOLUTE=$PWD
	ABSOLUTE+="/$1"
	set first (string sub -l 1 "$argv[1]") 
	switch "$first"
	case "~"
		set ABSOLUTE "$argv[1]"
	case "/"
		set ABSOLUTE "$argv[1]"
	case "*"
		set ABSOLUTE "$PWD/$argv[1]"
	end

	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shaderdrop/main.lua "$ABSOLUTE"

fi
	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shaderdrop/main.lua "$ABSOLUTE" $argv[1] $argv[2] $argv[3] $argv[4] 
end

exit

M bin/glsl_gif => bin/glsl_gif +14 -8
@@ 1,13 1,19 @@
#!/bin/bash
#!/usr/bin/fish

if [ -z "$1" ]; then
    echo "please give an argument"
if test -z "$argv[1]"
    echo "USAGE: shadername.frag [w h fps seconds]"
else
	
	ABSOLUTE=$PWD
	ABSOLUTE+="/$1"
	set first (string sub -l 1 "$argv[1]") 
	switch "$first"
	case "~"
		set ABSOLUTE "$argv[1]"
	case "/"
		set ABSOLUTE "$argv[1]"
	case "*"
		set ABSOLUTE "$PWD/$argv[1]"
	end

	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shader_gif/main.lua "$ABSOLUTE" $2 $3 $4 $5
fi
	exec /home/$USER/tools/raylyeh/raylyeh /home/$USER/tools/rl_tools/shader_gif/main.lua "$ABSOLUTE" $argv[1] $argv[2] $argv[3] $argv[4] $argv[5] 
end

exit

D bin/lamp_start.sh => bin/lamp_start.sh +0 -6
@@ 1,6 0,0 @@
#!/bin/bash
sudo systemctl start apache2
echo "apache2 started"
sudo systemctl start mysql
echo "mysql started"
exit

D bin/lamp_stop.sh => bin/lamp_stop.sh +0 -6
@@ 1,6 0,0 @@
#!/bin/bash
sudo systemctl stop apache2
echo "apache2 stopped"
sudo systemctl stop mysql
echo "mysql stopped"
exit

D bin/left => bin/left +0 -4
@@ 1,4 0,0 @@
#!/bin/bash
cd ~/apps/Left/desktop
npm start
exit

D bin/love => bin/love +0 -3
@@ 1,3 0,0 @@
#!/bin/sh
exec /home/$USER/engines/love-11.3-x86_64.AppImage "$@"
exit

D bin/masterbus => bin/masterbus +0 -3
@@ 1,3 0,0 @@
#!/bin/sh
exec /home/$USER/oF/apps/np-tools/masterbus/bin/masterbus "$@"
exit

D bin/miscela => bin/miscela +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
exec /home/$USER/oF/apps/np-miscela/miscela/bin/miscela "$@"
exit

D bin/of-projectgen.sh => bin/of-projectgen.sh +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
exec ~/oF/projectGenerator-linux64/projectGenerator
exit

D bin/ofgeanybuild.sh => bin/ofgeanybuild.sh +0 -17
@@ 1,17 0,0 @@
#!/bin/bash
pathnow=$(pwd)
base=$(basename "$pathnow")
level="0";

while [ "$base" != "src"  ] && [ "$level" -lt "5" ]
do 
    cd ..
    pathnow=$(pwd)
    base=$(basename "$pathnow")
    let "level += 1"
done
cd ..
#echo $(pwd)
#echo "found!!! $level folders above."
make -j4 -s 2>&1
exit

D bin/orcaJS => bin/orcaJS +0 -4
@@ 1,4 0,0 @@
#!/bin/bash
cd ~/apps/Orca/desktop
npm start
exit

D bin/orcafork => bin/orcafork +0 -18
@@ 1,18 0,0 @@
#!/bin/bash

if [ -z "$1" ]; then
    chrt --rr 79  /home/$USER/apps/orcafork/build/release/orca --strict-timing --undo-limit 20 --margins 1 --osc-port 4444 
else

    ext="${1#*.}"  
    BPM=$(cut -d'.' -f1 <<<$ext)

    if [[ $BPM = "orca" ]]; then
        BPM="120"
    fi

    #FILEPATH=$(realpath "$1")
    chrt --rr 79  /home/$USER/apps/orcafork/build/release/orca --strict-timing --bpm "$BPM" --undo-limit 20 --margins 1 --osc-port 4444 $1
fi

exit

D bin/ossia.sh => bin/ossia.sh +0 -3
@@ 1,3 0,0 @@
#!/bin/bash
QT_AUTO_SCREEN_SCALE_FACTOR=0 exec ~/apps/Score-v1.0.0-b40-amd64.AppImage
exit

D bin/pilot => bin/pilot +0 -4
@@ 1,4 0,0 @@
#!/bin/bash
cd ~/apps/Pilot/desktop
npm start
exit

D bin/pixelscript => bin/pixelscript +0 -3
@@ 1,3 0,0 @@
#!/bin/sh
exec /home/$USER/oF/addons/np-pixelscript/pixelscript/bin/pixelscript "$@"
exit

D bin/ronin => bin/ronin +0 -4
@@ 1,4 0,0 @@
#!/bin/bash
cd ~/apps/Ronin/desktop
npm start
exit

D bin/sitter.py => bin/sitter.py +0 -414
@@ 1,414 0,0 @@
#!/usr/bin/python
# j4cDAC "sitter"
#
# Copyright 2012 Jacob Potter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import socket
import time
import struct

def pack_point(x, y, r, g, b, i = -1, u1 = 0, u2 = 0, flags = 0):
	"""Pack some color values into a struct dac_point.

	Values must be specified for x, y, r, g, and b. If a value is not
	passed in for the other fields, i will default to max(r, g, b); the 
	rest default to zero.
	"""
	
	if i < 0:
		i = max(r, g, b)

	return struct.pack("<HhhHHHHHH", flags, x, y, i, r, g, b, u1, u2)


class ProtocolError(Exception):
	"""Exception used when a protocol error is detected."""
	pass


class Status(object):
	"""Represents a status response from the DAC."""

	def __init__(self, data):
		"""Initialize from a chunk of data."""
		self.protocol_version, self.le_state, self.playback_state, \
		  self.source, self.le_flags, self.playback_flags, \
		  self.source_flags, self.fullness, self.point_rate, \
		  self.point_count = \
			struct.unpack("<BBBBHHHHII", data)

	def dump(self, prefix = " - "):
		"""Dump to a string."""
		lines = [
			"Light engine: state %d, flags 0x%x" %
				(self.le_state, self.le_flags),
			"Playback: state %d, flags 0x%x" %
				(self.playback_state, self.playback_flags),
			"Buffer: %d points" %
				(self.fullness, ),
			"Playback: %d kpps, %d points played" %
				(self.point_rate, self.point_count),
			"Source: %d, flags 0x%x" %
				(self.source, self.source_flags)
		]
		for l in lines:
			print prefix + l


class BroadcastPacket(object):
	"""Represents a broadcast packet from the DAC."""

	def __init__(self, st, ip=None):
		"""Initialize from a chunk of data."""
		self.mac = st[:6]
		self.hw_rev, self.sw_rev, self.buffer_capacity, \
		self.max_point_rate = struct.unpack("<HHHI", st[6:16])
		self.status = Status(st[16:36])
		self.ip = ip

	def dump(self, prefix = " - "):
		"""Dump to a string."""
		lines = [
			"MAC: " + ":".join(
				"%02x" % (ord(o), ) for o in self.mac),
			"HW %d, SW %d" %
				(self.hw_rev, self.sw_rev),
			"Capabilities: max %d points, %d kpps" %
				(self.buffer_capacity, self.max_point_rate)
		]
		for l in lines:
			print prefix + l
		self.status.dump(prefix)

	def macstr(self):
		return "".join("%02x" % (ord(c), ) for c in self.mac)


class DAC(object):
	"""A connection to a DAC."""

	def got_broadcast(self, bp):
		self.last_broadcast = bp
		self.last_broadcast_time = time.time()

	def read(self, l):
		"""Read exactly length bytes from the connection."""
		while l > len(self.buf):
			self.buf += self.conn.recv(4096)

		obuf = self.buf
		self.buf = obuf[l:]
		return obuf[:l]

	def readresp(self, cmd):
		"""Read a response from the DAC."""
		data = self.read(22)
		response = data[0]
		cmdR = data[1]
		status = Status(data[2:])

#		status.dump()

		if cmdR != cmd:
			raise ProtocolError("expected resp for %r, got %r"
				% (cmd, cmdR))

		if response != "a":
			raise ProtocolError("expected ACK, got %r"
				% (response, ))

		self.last_status = status
		return status

	def __init__(self, macstr, bp):
		self.macstr = macstr
		self.firmware_string = "-"
		self.got_broadcast(bp)

		try:
			t1 = time.time()
			self.connect(self.last_broadcast.ip[0])
			t = time.time() - t1
			self.conn_status = "ok (%d ms)" % (t * 500)

			if self.last_broadcast.sw_rev < 2:
				self.firmware_string = "(old)"
			else:
				self.conn.sendall('v')
				self.firmware_string = self.read(32).replace("\x00", " ").strip()
		except Exception, e:
			self.conn_status = str(e)

	def connect(self, host, port = 7765):
		"""Connect to the DAC over TCP."""
		conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		conn.settimeout(0.2)
		conn.connect((host, port))
		self.conn = conn
		self.buf = ""

		# Read the "hello" message
		first_status = self.readresp("?")
		first_status.dump()



	def begin(self, lwm, rate):
		cmd = struct.pack("<cHI", "b", lwm, rate)
		self.conn.sendall(cmd)
		return self.readresp("b")

	def update(self, lwm, rate):
		cmd = struct.pack("<cHI", "u", lwm, rate)
		self.conn.sendall(cmd)
		return self.readresp("u")

	def encode_point(self, point):
		return pack_point(*point)

	def write(self, points):
		epoints = map(self.encode_point, points)
		cmd = struct.pack("<cH", "d", len(epoints))
		self.conn.sendall(cmd + "".join(epoints))
		return self.readresp("d")

	def prepare(self):
		self.conn.sendall("p")
		return self.readresp("p")

	def stop(self):
		self.conn.sendall("s")
		return self.readresp("s")

	def estop(self):
		self.conn.sendall("\xFF")
		return self.readresp("\xFF")

	def clear_estop(self):
		self.conn.sendall("c")
		return self.readresp("c")

	def ping(self):
		self.conn.sendall("?")
		return self.readresp("?")

	def play_stream(self, stream):
		# First, prepare the stream
		if self.last_status.playback_state == 2:
			raise Exception("already playing?!")
		elif self.last_status.playback_state == 0:
			self.prepare()

		started = 0

		while True:
			# How much room?
			cap = 1799 - self.last_status.fullness
			points = stream.read(cap)

			if cap < 100:
				time.sleep(0.005)
				cap += 150

#			print "Writing %d points" % (cap, )
			t0 = time.time()
			self.write(points)
			t1 = time.time()
#			print "Took %f" % (t1 - t0, )

			if not started:
				self.begin(0, 30000)
				started = 1


def find_dac():
	"""Listen for broadcast packets."""

	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.bind(("0.0.0.0", 7654))

	while True:
		data, addr = s.recvfrom(1024)
		bp = BroadcastPacket(data)
		
		print "Packet from %s: " % (addr, )
		bp.dump()


from Tkinter import *
import socket
import Queue
import thread
import time

class DacDisplay(LabelFrame):
	def __init__(self, master):
		LabelFrame.__init__(self, master, width=600, height=400)
		self.grid_propagate(0)

		Label(self, text="IP Address:").grid(row=0, column=0, sticky=N+E)
		Label(self, text="Version:").grid(row=1, column=0, sticky=N+E)
		Label(self, text="Status:").grid(row=2, column=0, sticky=N+E)
		Label(self, text="Source:").grid(row=3, column=0, sticky=N+E)
		Label(self, text="Network:").grid(row=4, column=0, sticky=N+E)
		Label(self, text="Firmware:").grid(row=5, column=0, sticky=N+E)

		self.iplabel = Label(self, text = "")
		self.iplabel.grid(row=0, column=1, sticky=N+W)
		self.verslabel = Label(self, text = "")
		self.verslabel.grid(row=1, column=1, sticky=N+W)
		self.stlabel = Label(self, text = "")
		self.stlabel.grid(row=2, column=1, sticky=N+W) 
		self.srclabel = Label(self, text = "")
		self.srclabel.grid(row=3, column=1, sticky=N+W) 
		self.netlabel = Label(self, text = "")
		self.netlabel.grid(row=4, column=1, sticky=N+W) 
		self.fwlabel = Label(self, text = "")
		self.fwlabel.grid(row=5, column=1, sticky=N+W) 

		self.display_none()

	def display_none(self):
		self['text'] = "Ether Dream"

		for l in self.iplabel, self.verslabel, self.stlabel, self.srclabel, self.netlabel, self.fwlabel:
			l['text'] = ""

	def display_dac(self, dac):
		b = dac.last_broadcast
		self['text'] = "Ether Dream " + b.macstr()[6:]
		self.iplabel['text'] = str(b.ip[0])
		self.verslabel['text'] = "hardware %d, software %d" % (b.hw_rev, b.sw_rev)

		st_str = ""
		if b.status.le_state == 0:
			st_str = "online, "
		else:
			st_str = "ESTOP ACTIVE (%d), " % (b.status.le_flags, )

		if b.status.playback_state == 0:
			st_str += "idle"
		elif b.status.playback_state == 1:
			st_str += "prepared"
		elif b.status.playback_state == 2:
			st_str += "playing (%d buffered, %d played)" % (b.status.fullness, b.status.point_count)
		else:
			st_str += "DAC state %d" % (b.status.playback_state, )

		if b.status.point_rate:
			st_str += ", %d pps" % (b.status.point_rate)

		self.stlabel['text'] = st_str

		if b.status.source == 0:
			src_str = "network"
		elif b.status.source == 1:
			src_str = "file playback: %s, repeat %s" % (
				b.status.source_flags & 1 and "playing" or "not playing",
				b.status.source_flags & 2 and "on" or "off"
			)
		elif b.status.source == 2:
			src_str = "abstract generator: %s" % (
				b.status.source_flags & 1 and "playing" or "not playing",
			)
		else:
			src_str = "unknown %d" % (b.status.source)
			
		self.srclabel['text'] = src_str
		self.netlabel['text'] = dac.conn_status
		self.fwlabel['text'] = dac.firmware_string

class DacTracker(Listbox):
	def __init__(self, master, *args, **kwargs):
		Listbox.__init__(self, master, *args, **kwargs)

		self.dac_list = []
		self.dac_macstr_map = {}

		self.bind("<<ListboxSelect>>", self.update_selection)

	def update_selection(self, lb=None):
		if self.dac_display:
			try:
				dac_obj = self.dac_list[self.index(ACTIVE)]
			except:
				return
			self.dac_display.display_dac(dac_obj)

	def got_packet(self, bp):
		macstr = bp.macstr()
		if macstr not in self.dac_macstr_map:
			new_dac = DAC(macstr, bp)
			self.insert(END, macstr[6:])
			self.dac_list.append(new_dac)
			self.dac_macstr_map[macstr] = new_dac
			dac_obj = new_dac
		else:
			dac_obj = self.dac_macstr_map[macstr]
			dac_obj.got_broadcast(bp)

		if len(self.dac_list) == 1:
			self.selection_set(0)
			self.update_selection()

		def check_on_dac():
			if time.time() - dac_obj.last_broadcast_time < 2:
				return

			idx = self.dac_list.index(dac_obj)
			self.dac_list.remove(dac_obj)
			del self.dac_macstr_map[macstr]
			self.delete(idx)
			self.dac_display.display_none()


		self.after(2000, check_on_dac)



# Set up the basic window
root = Tk()
root.title("Ether Dream")
root.resizable(FALSE, FALSE)
frame = Frame(root)
frame.grid()

disp = DacDisplay(root)
disp.grid(row=0, column=1, padx=5, pady=5)
tracker = DacTracker(root, height=22)
tracker.grid(row=0, column=0, padx=5, pady=5)
tracker.dac_display = disp

# Set up queue checker
packet_queue = Queue.Queue()
def queue_check():
	try:
		while True:
			data, addr = packet_queue.get_nowait()
			tracker.got_packet(BroadcastPacket(data, addr))
	except Queue.Empty:
		root.after(100, queue_check)

root.after(100, queue_check)

# Set up listening socket and thread
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 7654))
def socket_thread():
	while True:
		packet_queue.put(s.recvfrom(1024))
thread.start_new(socket_thread, ())

root.mainloop()

D bin/substrata => bin/substrata +0 -3
@@ 1,3 0,0 @@
#!/bin/sh
exec /home/$USER/oF/apps/np-tools/substrata/bin/substrata "$@"
exit

D bin/wolframkit => bin/wolframkit +0 -3
@@ 1,3 0,0 @@
#!/bin/sh
exec /home/$USER/oF/apps/np-tools/wolframkit/bin/wolframkit "$@"
exit