Philipps 5 mins: Graph-Fun with AJAX and Canvas

Flattr this!

I always searched for an efficient way add dynamic diagrams to a web-project without using flash or other plugin-based magic.
With the support of the canvas tag element in almost all mainstream browser, i thought it would be a good time for creating a short demo how things workout.
You will need at least two Parts for this demo. First of all you will need a Source JSON feed. For this demo i just hacked together a very basis PHP script:

<?php
header('Content-type: application/json');
echo'{';
echo '"value":"' . rand(0, 60) . '"';
echo '}';
?>

The result is something like:

{"value":"34"}

Secondly you need a Webpage, where you want to insert your canvas element, load the data from the json feed and draw the changing values to the canvas element.
For a better performance, we will implementing pulling the data and drawing the data within two parallel cycles. The Common data Storage will be an array of 300 value (for our diagram with a width of 300px).
We are using two additional JS Files. The first we need for creating our XHTTPRequest Object and handling the response within a callback method. The second script is for parsing the JSON Feed as a Javascript Object in a safe way (an ordinary eval works, but is to unsecury).
Our main-script works in several steps:
First we initialize an array with empty elements:

function init(){
    for(var i=0; i < 300; i++){
        randomValues[i] = 0;
    }
}

 


This step is optional, but then you have a nice “zero line” at the beginning.

Secondly we have a method, that pushes a new value to the existing array, and drops the first entry, if the length of the array is greater than 300.

function addValue(arr, value){
    if(arr.push(value) > 300){
        arr.shift();
    }
}

 


The next two methods are necessary for sending our ajax-request and for handling the response in a callback method.
Basically the callback method just calls the addValue method.

The timeout variable is set to 200 ms. So the script calls our backend periodically every 200 ms and then adds a new value to our array.

function pullValue(){
    sendRequest('random.php',handleRandomRequest);
    setTimeout(pullValue, timeout);
}

function handleRandomRequest(req) {
    var text = JSON.parse(req.responseText);
    addValue(randomValues, text.value);
}

The last method is for the drawing functionality:

function draw(){
    ctx.clearRect(0, 0, 300, 60);
    ctx.fillStyle = "rgba(101,101,101, 0.5)";
    ctx.fillRect (0, 0, 300, 60);
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'blue';
    ctx.beginPath();
    ctx.moveTo(1, 60-parseInt(randomValues[0]));
    for (var i=1; i<randomValues.length; i++){
        value = 60-parseInt(randomValues[i]);
        ctx.lineTo(i,value);
    }
    ctx.stroke();
    setTimeout(draw, timeout);
}

ctx is a 2d context of the canvas element.
On every call of the draw method, all elements of the array are painted. The first element is always the start point.
Because the canvas coordinate system has the point 0,0 in the upper left corner but the 0,0 point of our diagram should be in the lower left corner, you have to subtract the array-values from 60 to get the right drawing coordinate.
This method also runs periodically every 200 ms. But it also works for two times for pulling the data an drawing it.

Here you can see the script in action

Preparation for counter update

Flattr this!

So after a long time i plan to give my counter-engine (^^) an update.
The main Problem is, that the counter itself was perfect for ~2000 counts. But now with 5000 count, the presentation of the results is just not readable anymore.
So i plan the following things to do during the next days (i hope i will finish this during tomorrow):

  • using a new drawing method: instead of drawing the whole graph, i will draw just time-slices of a particular periode. So e.g. if you want to plot the current graph with this method, it would be necessary to draw 24 slices with a month periode.
  • to get read of lots of code within the counter/presentation script, i want to use the build-in date-calculation functions of mysql.
    So e.g.
    SELECT something FROM `counts` WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= date_col; Should be perfect :-).
  • To use this functions, i have to use the build-in datetime Datatype. At the moment i am storring all counts with a unix timestamp. To make the move, i have to do three steps:
    1. creating a new field: ALTER TABLE `counts` ADD `created` DATETIME NOT NULL;
    2. migrate the old dates: UPDATE `counts` SET created = from_unixtime(unixtime);
    3. finally i had to change to insert statement within the counter script:
      “INSERT INTO `counts` ( … user_string, created) VALUES … ‘”.$user_string.”‘, NOW()) “;

More next time…

eingescannte Bilder konvertieren und Timestamp setzen

Flattr this!

Da ich die letzten Tage gezwungenermaßen sehr viel Zeit hatte (warum kommt später) und ich irgendwie mal Grund in meine Kisten und Boxen bringen möchte, habe ich angefangen, meine (Papier-) Fotos einzuscannen und in iPhoto zu übertragen.

Die Frage stelle sich mir nun, wie ich aus 200 Tiff Dateien die das aktuelle Datum tragen (also das des Scans) ordentliche Digitalbilder hinkriege, sodass sie A) nicht zuviel Platz wegnehmen und B) nicht alle auf einen Tag datiert sind. Als Datum reicht mir erstmal nur der jeweilige Monat des Jahres.

Nachdem ich von freundlichen Mitmenschen (danke Willem, danke Christoph) mit geeigneten Shellscripten versorgt worden bin, war die Sache mit der Dateigröße vom Tisch der folgende Einzeiler macht das recht gut:

     for i in `ls`; do convert $i neues_verzeichnis/$i.png; done

Nicht vergessen: “neues_Verzeichnis” natürlich anpassen und das ganze (wenn man es denn in eine Datei packt) chmod +x setzen.
Aber das reichte mir ja nicht ^^

Und was mache ich, wenn ich gar nicht mehr anders kann? Ich nutze PHP…. gute, alte, unübersichtliche Scriptsprache.
Well… thats the Code:


    <?php
    if(count($argv) < 2) die(“Usage:\n php -f convert.php — -filetype -month -year\n php -f convert.php — -png -07 – 1997\n _MIND THE — !!_ \n”);
    $sdir = getcwd ();
    echo “Sourcefolder: “.$sdir.” …\n”;
    $tdir = $sdir.”/converted”;
    $ext = substr($argv[1], 1);
    $month = substr($argv[2], 1);
    $year = substr($argv[3], 1);
    echo “$ext-$month-$year\n”;
    $time = mktime(12, 0, 0, $month, 15, $year);
    echo $time.”\n”;
    @mkdir($tdir);
    if ($handle = @opendir($sdir)) {
        while (false !== ($file = readdir($handle)))
            if($file != “.” and $file != “..” and $file != “converted”){
            $filearray = explode(“.”, $file);
            array_pop($filearray);
            $newfile = $tdir.”/”.implode(“.”, $filearray).”.png”;
            echo “convert $sdir/$file $newfile\n”;
            system ( “convert $sdir/$file $newfile” );
            echo “set Date to: “.date(“d.m.y”, $time).”\n”;
            touch ($newfile, $time);
        }
    }
    ?>


Tut genau das was es soll…
Aufgerufen wird er mit

    php -f convert.php

Danach wird einem gesagt, was man an Parametern übergeben kann/soll/darf/muss.
Nun bleibt mir nur noch, mich mit meiner eigenen Vergangenheit in Form von Fotos konfrontiert zu sehen ^^.

Blogged with the Flock Browser

AVM Box: Telefonbuch

Flattr this!

Ich plane in der Zeit zwischen Weihnachten und Neujahr ein wenig am Netzwerk hier umzubauen. Es liegen definitiv zu viele Kabel hier in der Gegen herum.

Letztendlich entschied ich mich für 2 AVM Fritz Boxen (jeweils 2x7170er). Eine würde zwar reichen für Telefonanlage und Internetzugang, allerdings hat man dann zur Not einen zweiten Router zur Verfügung, falls man dies denn haben möchte.

Eine genauere Beschreibung, wie und der aktuelle Stand und der Umbau dann ablaufen wird, kommt dann später, wenn die zweite Box ankommt.Ich plane beide Boxen mit WDS verbinden. Während auf einer Box dann die Telefoniesachen laufen werden, nutzt ich die andere, um das Wlan zu erweitern (damit ich dann mein – hoffentlich bald kommendes AVM Fritz Mini nutzen kann) und um 1 PC und einen Drucker per Ethernet ins Netz einzubinden.

Alles in allem werde ich wohl so 40 m Kabel sparen ^^.

Wieso ich jetzt schon poste? Nunja irgendwie habe ich dann doch schon ein wenig mit dem Teil rum gespielt. Die neueste Firmware drauf gespielt.

Und mich in der Oberfläche umgesehen.Alles in allem sehr schön aufgeräumt und sehr viele Möglichkeiten im Vergleich zu meinem aktuellen (und hin und wieder abstürzenden) SMC Barricade 7004.Da ich mittlerweile 100% mit MacOs laufe (habe zwar noch ne VMware mit Win XP – aber nur für Notfälle), habe ich dann von den ganzen Windows Tools Abstand genommen.

Das Teil hat ja eine Weboberfläche, dass sollte also reichen. Was nun ziemlich ärgerlich ist, ist dass mein Bestreben, meine Adressen an einer zentralen Stelle zu verwalten, einen eigenem, zentralem, Telefonbuch innerhalb der FritzBox gegenüber steht.

Das kann man auch nur manuell per Web-Oberfläche füllen. Mit Hilfe von WireShark und ein paar Testläufen bin ich zu folgendem Trafficschnippsel gekommen:

 Pä˜ÿÿ×POST /cgi-bin/webcm HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.10.5 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6
Content-Type: application/x-www-form-urlencoded
Referer: http://fritz.box/cgi-bin/webcm
Accept: text/xml,application/xml,application/xhtml+xml,text/html;  q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
 
Accept-Language: de-de
Accept-Encoding: gzip, deflate
Content-Length: 1292
Connection: keep-alive
Host: fritz.box
 
ªâjGK �N��N���Jè¨r�Roé4�E�@ƒ=@�@ÍÀ¨²À¨²Öâ�PÙ1Gb+€ÿÿw>
Pä˜ÿÿ×getpage=..%2Fhtml%2Fde%2Fmenus%2Fmenu2.html&……
ÿÿ×APä˜HTTP/1.0 200 OK
Cache-Control: no-cache
Content-type: text/html
Expires: -1
Pragma: no-cache
 

Hierbei ist vor allem der letzten Absatz interessant (habe ich mal gekürzt, weil man eh mit den Sonderzeichen nicht viel lesen konnte).

Es handelt sich um einen einfachen HTTP POST Befehl. Sämtlich Daten werden URL-endcoded übertragen.

Mit ein wenig PHP (im wesentlichen den String URL-decoden und nach &,= splitten) erhalte ich für einen Eintrag nun folgende Schlüssel/Werte Paare:

 getpage = ../html/de/menus/menu2.html

errorpage = ../html/de/menus/menu2.html

var:lang = devar:pagename = fonbuch

var:errorpagename = fonbuch2

var:menu = home

var:pagemaster = fonbuch

time:settings/time = 1198187178,-60

var:showall =

var:showStartIndex =

var:PhonebookEntryNew = Entry0

var:PhonebookEntryXCount = 0

var:PhonebookEntryNewCode = 01

var:PhonebookEntryNumber =

telcfg:settings/Phonebook/Entry0/Name = TESTERT TESTEREI

telcfg:settings/Phonebook/Entry0/Category = 1

telcfg:settings/Phonebook/Entry0/Number0/Type = hometelcfg:settings/Phonebook/Entry0/Number0/Number = 12345678

telcfg:settings/Phonebook/Entry0/Number0/Code = 01

telcfg:settings/Phonebook/Entry0/Number0/Vanity =

telcfg:settings/Phonebook/Entry0/Number1/Type = mobile

telcfg:settings/Phonebook/Entry0/Number1/Number = 87654321

telcfg:settings/Phonebook/Entry0/Number1/Code =

telcfg:settings/Phonebook/Entry0/Number1/Vanity =

telcfg:settings/Phonebook/Entry0/Number2/Type = work

telcfg:settings/Phonebook/Entry0/Number2/Number =

telcfg:settings/Phonebook/Entry0/Number2/Code =

telcfg:settings/Phonebook/Entry0/Number2/Vanity =

telcfg:settings/Phonebook/Entry0/DefaultNumber = 0

So sieht besagte PHP Seite aus:

Die Kombination telcfg:settings/Phonebook/Entry0/Name macht definitivLust auf mehr :-). Aber momentan fehlt mir einfach die Zeit. Aber es wäre zum Beispiel denkbar, ein kleines Java Programm zu schreiben, dass die Kontaktdaten mit dem Adressbuch synchronisiert.

simple iPhoto Gallery Script

Flattr this!

Some time ago, i searched for a very simple possibility for publishing some photos online.
As a Mac User i am recently using iPhoto for collecting and organizing my photos.

I reused some old PHP code and create a simple Script, that searches through some iPhoto Web Exports to build a nice index page with folder previews:

phpGallery Screen1

The folder structure should be as the following:
phpGallery Screen2

As i do not have other language Versions of iPhoto, i do not know, if the scripts works also with other Versions of iPhoto.

Here you can download the very first version of the script:

PHP_Gallery_Script_for_iPhoto06_german

FINALLY: Comments are working again

Flattr this!

A friend of mine told me some minutes ago that the Comments function on this blog still produces some errors, when trying to post a comment. So i decided to stay with the spam and to disable the filter function until i have the time and the infos about the wordpress system to code my own plugin.

I found another project i worked on in the past years. I updated it a little bit and can now present some screen impressions:

First of all what is it?
So i have the big problem of to many files on to big disk space. As a result there is first the problem of finding files and second the high probability to save identical files on several places. Not only small files like the typical 1×1 spacer.png, but also some sound files, hi-res images or movie files. Just in case of the backup of a backup.

So i decided that i need a system, that organizes my files in that way, that i can have a quick view, i may search through all the files and that there is the safety, that a file is just saved onced and all the copies of it should be just links to the original ones.

I end up with a system design that scans a particular folder for new files and copy them into a special ordered file structure. The unique property of a file is its md5 sum. The original file/folder structure is mapped into a DB table.
The system is no at exactly this point. I created a easy low level plugin interface for examining the different file types.
Lateron i will create a class, that make sys links equivalent to the original folder structure and offer them e.g. as a samba share. Even the possibility of a file history is imaginable. At this point the main task is the imense low performance (due a big use of DB queries and redundant method calls) and the definition of a usefull interface.

Here are some screens of the current system:
File-Vault storage Folder
System File Storage

File-Vault picture Viewer
Picture Viewer

File-Vault mysql Viewer
SQL (Text) Viewer with Import Function

File-Vault PHP Viewer
PHP Viewer

File-Vault MP3 Viewer
MP3 Player

mbff

Flattr this!

Vor einiger Zeit habe ich mit der Entwicklung eines Browser Games angefangen.
Zu finden ist eine der ersten Versionen hier:
http://mbff.hausswolff.de

Da mir momentan die Zeit fehlt, es weiter zu entwickeln, und ich eh vorhatte den Server von PHP auf JSP umzustellen, habe ich alle alten Scripte gesammeln und stelle diese hier zum Download bereit.
Der Code ist recht spärlich kommentiert, falls Fragen sind, einfach hier stellen und ich schaue ob ich diese beantworten kann.

mbff-dump-v.0.0.1.0

mbff-planet

mbff-system

mbff-galaxy