/* $Id$ * $URL$ * * LCD4Linux driver for 4D Systems Display Graphics Modules * * Copyright (C) 2008 Sven Killig * Modified from sample code by: * Copyright (C) 2005 Michael Reinelt * Copyright (C) 2005, 2006, 2007 The LCD4Linux Team * * This file is part of LCD4Linux. * * LCD4Linux 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; either version 2, or (at your option) * any later version. * * LCD4Linux 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* * * exported fuctions: * * struct DRIVER drv_D4D * */ #include "config.h" #include #include #include #include #include #include #include #include #include "debug.h" #include "cfg.h" #include "qprintf.h" #include "udelay.h" #include "plugin.h" #include "widget.h" #include "widget_text.h" #include "widget_icon.h" #include "widget_bar.h" #include "drv.h" #include "drv_generic_text.h" #include "drv_generic_graphic.h" #include "drv_generic_serial.h" static char Name[] = "D4D"; char NAME_[20]; int FONT = 1, MODE = 0, EXTRA = 0, SECTOR = 0, SECTOR_SIZE, NOPOWERCYCLE = 0; /* int CONTRAST_; */ #define address_mmsb(variable) ((variable >> 24) & 0xFF) #define address_mlsb(variable) ((variable >> 16) & 0xFF) #define address_lmsb(variable) ((variable >> 8) & 0xFF) #define address_llsb(variable) (variable & 0xFF) #define address_hi(variable) ((variable >> 16) & 0xFF) #define address_mid(variable) ((variable >> 8) & 0xFF) #define address_lo(variable) (variable & 0xFF) #define msb(variable) ((variable >> 8) & 0xFF) #define lsb(variable) (variable & 0xFF) RGBA FG_COL_ = {.R = 0x00,.G = 0x00,.B = 0x00,.A = 0xff }; RGBA BG_COL_ = {.R = 0xff,.G = 0xff,.B = 0xff,.A = 0xff }; short int FG_COLOR, BG_COLOR; int RGB_24to16(int red, int grn, int blu) { return (((red >> 3) << 11) | ((grn >> 2) << 5) | (blu >> 3)); } int RGB_24to8(int red, int grn, int blu) { return (((red >> 5) << 5) | ((grn >> 5) << 2) | (blu >> 6)); } /****************************************/ /*** hardware dependant functions ***/ /****************************************/ static int drv_D4D_open(const char *section) { int fd; fd = drv_generic_serial_open(section, Name, 0); if (fd < 0) return -1; fcntl(fd, F_SETFL, 0); /* blocking read */ return 0; } static int drv_D4D_close(void) { drv_generic_serial_close(); return 0; } static void drv_D4D_receive_ACK() { char ret[1]; while (drv_generic_serial_read(ret, sizeof(ret)) != 1) usleep(1); /* loop should be unneccessary */ if (ret[0] == 0x15) { error("NAK!"); } else if (ret[0] != 6) { error("no ACK!"); } } static void drv_D4D_send_nowait(const char *data, const unsigned int len) { drv_generic_serial_write(data, len); } static void drv_D4D_send(const char *data, const unsigned int len) { drv_D4D_send_nowait(data, len); drv_D4D_receive_ACK(); } static void drv_D4D_send_nowait_extra(const char *data, const unsigned int len, unsigned char pos1, unsigned char pos2) { /* possibly leave out bytes at pos1 and pos2 for older protocol format */ if (EXTRA) { drv_D4D_send_nowait(data, len); } else { unsigned int i; char send[1]; for (i = 0; i < len; i++) { if (!pos1 || i != pos1) { if (!pos2 || i != pos2) { send[0] = data[i]; drv_generic_serial_write(send, 1); } } } } } static void drv_D4D_send_extra(const char *data, const unsigned int len, char pos1, char pos2) { drv_D4D_send_nowait_extra(data, len, pos1, pos2); drv_D4D_receive_ACK(); } static void drv_D4D_clear(void) { char cmd[] = { 'E' }; drv_D4D_send(cmd, sizeof(cmd)); } static void drv_D4D_write(const int row, const int col, const char *data, int len) { char out[len]; char user_char[len]; int user_x[len]; int user_y[len]; int i, k = 0; if (!SECTOR) { /* font in ROM */ for (i = 0; i < len; i++) { if (data[i] >= 31 && data[i] < CHAR0) { out[i] = data[i]; } else if (data[i] == 'µ') { /* mu */ if (FONT == 2) out[i] = 31; /* undocumented */ else if (FONT == 0) out[i] = 'u'; else out[i] = 127; /* undocumented */ } else { out[i] = ' '; if (data[i] == '°') user_char[k] = 0; /* degree */ else user_char[k] = data[i] - CHAR0; user_x[k] = (col + i) * XRES; user_y[k] = row * YRES; k++; } } char cmd[] = { 's', col, row, FONT, msb(FG_COLOR), lsb(FG_COLOR) }; /* normal chars */ drv_D4D_send_nowait(cmd, sizeof(cmd)); if (len > 256) len = 256; drv_D4D_send_nowait(out, len); char cmdNull[1]; cmdNull[0] = 0; drv_D4D_send(cmdNull, 1); char cmd_user[] = { 'D', 0, 0, 0, 0, 0, msb(FG_COLOR), lsb(FG_COLOR) }; /* user defined symbols */ for (i = 0; i < k; i++) { cmd_user[2] = user_char[i]; cmd_user[3] = user_x[i]; cmd_user[4] = msb(user_y[i]); cmd_user[5] = lsb(user_y[i]); drv_D4D_send_extra(cmd_user, sizeof(cmd_user), 1, 4); } } else { /* font on SD card */ int sec; char cmd_sd[] = { '@', 'I', 0, msb(row * YRES), lsb(row * YRES), XRES, msb(YRES), lsb(YRES), 16, 0, 0, 0 }; for (i = 0; i < len; i++) { cmd_sd[2] = (col + i) * XRES; sec = SECTOR + (unsigned char) data[i] * SECTOR_SIZE; cmd_sd[9] = address_hi(sec); cmd_sd[10] = address_mid(sec); cmd_sd[11] = address_lo(sec); drv_D4D_send_extra(cmd_sd, sizeof(cmd_sd), 3, 6); } } } static void drv_D4D_defchar(const int ascii, const unsigned char *matrix) { /* error("drv_D4D_defchar"); */ char cmd[11]; int i; cmd[0] = 'A'; cmd[1] = 0; cmd[2] = ascii - CHAR0; for (i = 0; i < 8; i++) { cmd[i + 3] = *matrix++; } drv_D4D_send_extra(cmd, sizeof(cmd), 1, 0); } static void drv_D4D_blit(const int row, const int col, const int height, const int width) { /* error("drv_D4D_blit(%i, %i, %i, %i)",row, col, height, width); */ int r, c; RGBA rgb, pixel0_0, pixel; short int color; char colorArray[2]; /* optimization: single colour rectangle? */ pixel0_0 = drv_generic_graphic_rgb(0, 0); char unicolor = 1; for (r = row; r < row + height; r++) { if (!unicolor) break; for (c = col; c < col + width; c++) { if (!unicolor) break; pixel = drv_generic_graphic_rgb(r, c); if (pixel0_0.R != pixel.R || pixel0_0.G != pixel.G || pixel0_0.B != pixel.B || pixel0_0.A != pixel.A) unicolor = 0; } } if (unicolor) { color = RGB_24to16(pixel0_0.R, pixel0_0.G, pixel0_0.B); char row2 = row + height - 1; char cmdRect[] = { 'r', col, msb(row), lsb(row), col + width - 1, msb(row2), lsb(row2), msb(color), lsb(color) }; drv_D4D_send_extra(cmdRect, sizeof(cmdRect), 2, 5); } else { char cmd[] = { 'I', col, msb(row), lsb(row), width, msb(height), lsb(height), MODE }; drv_D4D_send_nowait_extra(cmd, sizeof(cmd), 2, 5); for (r = row; r < row + height; r++) { for (c = col; c < col + width; c++) { rgb = drv_generic_graphic_rgb(r, c); if (MODE == 8) { colorArray[0] = RGB_24to8(rgb.R, rgb.G, rgb.B); drv_D4D_send_nowait(colorArray, 1); } else { color = RGB_24to16(rgb.R, rgb.G, rgb.B); colorArray[0] = msb(color); drv_D4D_send_nowait(colorArray, 1); /* doesn't werk if sent together (error: "partial write(/dev/tts/1): len=2 ret=1") */ /* colorArray[1]=lsb(color); */ colorArray[0] = lsb(color); drv_D4D_send_nowait(colorArray, 1); } /* drv_D4D_send_nowait(colorArray, MODE/8); */ } } drv_D4D_receive_ACK(); } } static int drv_D4D_contrast(int contrast) { if (contrast < 0) contrast = 0; if (contrast > 15) contrast = 15; char cmd[] = { 'Y', 2, contrast }; drv_D4D_send(cmd, sizeof(cmd)); /* CONTRAST_=contrast; */ return contrast; } static int drv_D4D_start(const char *section) { /* error("drv_D4D_start()"); */ int contrast; int xres_cfg = -1, yres_cfg = -1; char *s; char *color; if (drv_D4D_open(section) < 0) { return -1; } char cmd[] = { 'U' }; drv_D4D_send(cmd, sizeof(cmd)); char getVersion[] = { 'V', 0 }; drv_D4D_send_nowait(getVersion, sizeof(getVersion)); char answer[5]; drv_generic_serial_read(answer, sizeof(answer)); char *ids[] = { "uOLED", "uLCD", "uVGA" }; char *id; if (answer[0] <= 2) id = ids[(int) answer[0]]; else id = "Unknown"; qprintf(NAME_, sizeof(NAME_), "%s H%u S%u", id, (int) answer[1], (int) answer[2]); int res[2]; int i; for (i = 0; i < 2; i++) { switch ((unsigned char) answer[3 + i]) { case 0x22: res[i] = 220; break; case 0x28: res[i] = 128; break; case 0x32: res[i] = 320; EXTRA = 1; break; case 0x60: res[i] = 160; break; case 0x64: res[i] = 64; break; case 0x76: res[i] = 176; break; case 0x96: res[i] = 96; break; case 0x24: /* undocumented? */ res[i] = 240; break; default: error("Can't detect display dimensions!"); return -1; } } DCOLS = res[0]; DROWS = res[1]; cfg_number(section, "Mode", 0, 0, 16, &MODE); s = cfg_get(section, "Font", NULL); if (s == NULL || *s == '\0') { error("%s: no '%s.Font' entry from %s", Name, section, cfg_source()); return -1; } if (sscanf(s, "%dx%d", &xres_cfg, &yres_cfg) < 1 || xres_cfg < 0) { error("%s: bad %s.Font '%s' from %s", Name, section, s, cfg_source()); free(s); return -1; } if (yres_cfg == -1) { /* font on SD card */ SECTOR = xres_cfg * 512; char setAddress[] = { '@', 'A', address_mmsb(SECTOR), address_mlsb(SECTOR), address_lmsb(SECTOR), address_llsb(SECTOR) }; drv_D4D_send(setAddress, sizeof(setAddress)); char answer1[1]; char readByte[] = { '@', 'r' }; drv_D4D_send_nowait(readByte, sizeof(readByte)); drv_generic_serial_read(answer1, sizeof(answer1)); XRES = answer1[0]; drv_D4D_send_nowait(readByte, sizeof(readByte)); drv_generic_serial_read(answer1, sizeof(answer1)); YRES = answer1[0]; SECTOR = xres_cfg + 1; SECTOR_SIZE = ceil((double) XRES * (double) YRES * 2.0 / 512.0); } else { XRES = xres_cfg; YRES = yres_cfg; } if (MODE == 0) { color = cfg_get(section, "foreground", "ffffff"); if (color2RGBA(color, &FG_COL_) < 0) { error("%s: ignoring illegal color '%s'", Name, color); } if (color) free(color); FG_COLOR = RGB_24to16(FG_COL_.R, FG_COL_.G, FG_COL_.B); color = cfg_get(section, "background", "000000"); if (color2RGBA(color, &BG_COL_) < 0) { error("%s: ignoring illegal color '%s'", Name, color); } if (color) free(color); BG_COLOR = RGB_24to16(BG_COL_.R, BG_COL_.G, BG_COL_.B); DCOLS = DCOLS / XRES; DROWS = DROWS / YRES; switch (yres_cfg) { /* font in ROM */ case 8: switch (xres_cfg) { case 6: FONT = 0; break; case 8: FONT = 1; break; default: error("%s: unknown width in %s.Font '%s' from %s", Name, section, s, cfg_source()); return -1; }; break; case 12: FONT = 2; break; case 16: FONT = 3; break; case -1: break; default: error("%s: unknown height in %s.Font '%s' from %s", Name, section, s, cfg_source()); return -1; } } info("XRES=%i, YRES=%i; DCOLS=%i, DROWS=%d; FONT=%d, SECTOR=%i, SECTOR_SIZE=%i\n", XRES, YRES, DCOLS, DROWS, FONT, SECTOR, SECTOR_SIZE); cfg_number(section, "NoPowerCycle", 0, 1, 65536, &NOPOWERCYCLE); if (!NOPOWERCYCLE) { char powerOn[] = { 'Y', 3, 1 }; drv_D4D_send(powerOn, sizeof(powerOn)); /*char background[] = {'B', msb(BG_COLOR), lsb(BG_COLOR)}; drv_D4D_send(background, sizeof(background)); */ } char opaque[] = { 'O', 1 }; drv_D4D_send(opaque, sizeof(opaque)); char penSize[] = { 'p', 0 }; drv_D4D_send(penSize, sizeof(penSize)); if (!MODE) { unsigned char buffer[] = { 0x18, 0x24, 0x24, 0x18, 0, 0, 0, 0 }; /* degree */ drv_D4D_defchar(CHAR0, buffer); CHARS--; CHAR0++; } if (cfg_number(section, "Contrast", 0, 0, 255, &contrast) > 0) { drv_D4D_contrast(contrast); } drv_D4D_clear(); return 0; } int drv_D4D_text_draw(WIDGET * W) { short int FG_COLOR_old = FG_COLOR, BG_COLOR_old = BG_COLOR; int ret; RGBA fg, bg; fg = W->fg_valid ? W->fg_color : FG_COL_; bg = W->bg_valid ? W->bg_color : BG_COL_; FG_COLOR = RGB_24to16(fg.R, fg.G, fg.B); BG_COLOR = RGB_24to16(bg.R, bg.G, bg.B); ret = drv_generic_text_draw(W); FG_COLOR = FG_COLOR_old; BG_COLOR = BG_COLOR_old; return ret; } int lastVal[40 * 40 * 2]; /* ToDo: MAX_WIDGETS*2 */ int drv_D4D_bar_draw(WIDGET * W) { /* optimizations: - draw filled rectangles instead of user defined bar characters - cache last values */ WIDGET_BAR *Bar = W->data; int row, col, len, res, max, val1, val2; DIRECTION dir; STYLE style; row = W->row; col = W->col; dir = Bar->direction; style = Bar->style; len = Bar->length; res = dir & (DIR_EAST | DIR_WEST) ? XRES : YRES; max = len * res; val1 = Bar->val1 * (double) (max); val2 = Bar->val2 * (double) (max); if (val1 < 1) val1 = 1; else if (val1 > max) val1 = max; if (val2 < 1) val2 = 1; else if (val2 > max) val2 = max; short int FG_COLOR_old = FG_COLOR, BG_COLOR_old = BG_COLOR; RGBA fg, bg; fg = W->fg_valid ? W->fg_color : FG_COL_; bg = W->bg_valid ? W->bg_color : BG_COL_; FG_COLOR = RGB_24to16(fg.R, fg.G, fg.B); BG_COLOR = RGB_24to16(bg.R, bg.G, bg.B); char cmd[9]; cmd[0] = 'r'; int val[2]; val[0] = val1; val[1] = val2; int i, vals; int lastValIndex0 = row * DCOLS + col; int cells = DROWS * DCOLS; if (val1 == val2 && lastVal[lastValIndex0] == lastVal[lastValIndex0 + cells]) vals = 1; else vals = 2; for (i = 0; i < vals; i++) { int lastValIndex = lastValIndex0 + cells * (i /*+1 */ ); int y1 = row * YRES + (YRES / 2) * i; cmd[2] = msb(y1); cmd[3] = lsb(y1); int y2 = y1 + (YRES) / vals - 1; cmd[5] = msb(y2); cmd[6] = lsb(y2); if (val[i] > lastVal[lastValIndex]) { cmd[1] = col * XRES + lastVal[lastValIndex]; cmd[4] = cmd[1] + val[i] - lastVal[lastValIndex] - 1; cmd[7] = msb(FG_COLOR); cmd[8] = lsb(FG_COLOR); drv_D4D_send_extra(cmd, sizeof(cmd), 2, 5); } else if (val[i] < lastVal[lastValIndex]) { cmd[1] = col * XRES + val[i] - 1 + 1; cmd[4] = cmd[1] + lastVal[lastValIndex] - val[i]; cmd[7] = msb(BG_COLOR); cmd[8] = lsb(BG_COLOR); drv_D4D_send_extra(cmd, sizeof(cmd), 2, 5); } lastVal[lastValIndex] = val[i]; } FG_COLOR = FG_COLOR_old; BG_COLOR = BG_COLOR_old; return 0; } /****************************************/ /*** plugins ***/ /****************************************/ static void plugin_contrast(RESULT * result, RESULT * arg1) { double contrast; contrast = drv_D4D_contrast(R2N(arg1)); SetResult(&result, R_NUMBER, &contrast); } /****************************************/ /*** widget callbacks ***/ /****************************************/ /* using drv_generic_text_draw(W) */ /* using drv_generic_text_icon_draw(W) */ /* using drv_generic_text_bar_draw(W) */ /* using drv_generic_gpio_draw(W) */ /****************************************/ /*** exported functions ***/ /****************************************/ int drv_D4D_list(void) { printf("4D Systems Display Graphics Modules"); return 0; } int drv_D4D_init(const char *section, const int quiet) { /* error("drv_D4D_init()"); */ WIDGET_CLASS wc; int ret; info("%s: %s", Name, "$Rev$"); if ((ret = drv_D4D_start(section)) != 0) return ret; if (EXTRA) CHARS = 64; else CHARS = 32; CHAR0 = 128; GOTO_COST = 7; if (MODE) { drv_generic_graphic_real_blit = drv_D4D_blit; } else { drv_generic_text_real_write = drv_D4D_write; drv_generic_text_real_defchar = drv_D4D_defchar; } if (!quiet) { char buffer[40]; qprintf(buffer, sizeof(buffer), "%s %dx%d", NAME_, DCOLS, DROWS); if (MODE) { if (drv_generic_graphic_greet(buffer, "www.4dsystems.com.au")) { sleep(3); drv_generic_graphic_clear(); } } else { if (drv_generic_text_greet(buffer, "www.4dsystems.com.au")) { sleep(3); drv_D4D_clear(); } } } if (MODE) { if ((ret = drv_generic_graphic_init(section, Name)) != 0) return ret; } else { if ((ret = drv_generic_text_init(section, Name)) != 0) return ret; if ((ret = drv_generic_text_icon_init()) != 0) return ret; if ((ret = drv_generic_text_bar_init(0)) != 0) return ret; drv_generic_text_bar_add_segment(0, 0, 255, 32); wc = Widget_Text; wc.draw = drv_D4D_text_draw; widget_register(&wc); wc = Widget_Icon; wc.draw = drv_generic_text_icon_draw; widget_register(&wc); wc = Widget_Bar; wc.draw = drv_D4D_bar_draw; widget_register(&wc); } AddFunction("LCD::contrast", 1, plugin_contrast); return 0; } int drv_D4D_quit(const int quiet) { /* error("drv_D4D_quit()"); */ info("%s: shutting down.", Name); if (MODE == 0) drv_generic_text_quit(); if (!NOPOWERCYCLE) { drv_D4D_clear(); } if (!quiet) { if (MODE) drv_generic_graphic_greet("goodbye!", NULL); else drv_generic_text_greet("goodbye!", NULL); } /* fade */ /*int i; for(i=CONTRAST_;i>=0;i--) { drv_D4D_contrast(i); usleep(1000); } */ if (MODE) drv_generic_graphic_quit(); if (!NOPOWERCYCLE) { char powerDown[] = { 'Y', 3, 0 }; drv_D4D_send(powerDown, sizeof(powerDown)); } debug("closing connection"); drv_D4D_close(); return (0); } DRIVER drv_D4D = { .name = Name, .list = drv_D4D_list, .init = drv_D4D_init, .quit = drv_D4D_quit, }; >472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
/* $Id$
 * $URL$
 *
 * mpd informations v0.82
 *
 * Copyright (C) 2006 Stefan Kuhne <sk-privat@gmx.net>
 * Copyright (C) 2007 Robert Buchholz <rbu@gentoo.org>
 * Copyright (C) 2008 Michael Vogt <michu@neophob.com>
 * Copyright (C) 2006 The LCD4Linux Team <lcd4linux-devel@users.sourceforge.net>
 *
 * This file is part of LCD4Linux.
 *
 * LCD4Linux 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; either version 2, or (at your option)
 * any later version.
 *
 * LCD4Linux 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, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

/* 
 * changelog v0.5 (20.11.2007):
 *   changed: 	mpd::artist(), mpd::title(), mpd::album()
 *              init code, call only if a function is used.
 *   removed: 	"old style" functions, duplicate code
 *   fixed: 	strdup() mem leaks
 *   added:	getstate, function which return player status: play/pause/stop
 *		getVolume, funtcion which returns the mpd volume
 *		getFilename, return current filename
 *
 * 
 * changelog v0.6 (05.12.2007):
 *  changed:    -connection handling
 *              -verbose "NO TAG" messages
 *              -init code
 *  added:      -added password support (MPD_PASSWORD env variable)
 *              -mpd::getSongsInDb - how many songs are in the mpd db?
 *              -mpd::getMpdUptime - uptime of mpd
 *              -mpd::getMpdPlayTime - playtime of mpd
 *              -mpd::getMpdDbPlayTime - playtime of all songs in mpd db
 *              -basic error handler..
 *		-mpd configuration in lcd4linux.conf
 *		-formatTime* - use those functions to format time values
 *  removed:    -reprand method
 *
 *
 * changelog v0.7 (14.12.2007):
 *  changed:	-connection handling improved, do not disconnect/reconnect for each query
 *               -> uses less ressources
 *
 * changelog v0.8 (30.01.2008):
 *  changed:  -libmpd is not needed anymore, use libmpdclient.c instead
 *  fixed:    -getMpdUptime()
 *            -getMpdPlaytime()
 *            -type definition
 *  added:    -mpd::getSamplerateHz
 *            -getAudioChannels
 *
 * changelog v0.83 (26.07.2008):
 *  added:    -mpd::cmd* commands
 *
 */

/*

TODO: 
 -what happens if the db is updating? 

*/

#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>

#include "debug.h"
#include "plugin.h"
#include "cfg.h"
/* struct timeval */
#include <sys/time.h>

/* source: http://www.musicpd.org/libmpdclient.shtml */
#include "libmpdclient.h"

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif

#define TIMEOUT_IN_S 10
#define ERROR_DISPLAY 5

/* current song */

static int l_totalTimeSec;
static int l_elapsedTimeSec;
static int l_bitRate;
static int l_repeatEnabled;
static int l_randomEnabled;
static int l_state;
static int l_volume;
static int l_numberOfSongs;
static unsigned long l_uptime;
static unsigned long l_playTime;
static unsigned long l_dbPlayTime;
static int l_playlistLength;
/* pos in playlist */
static int l_currentSongPos;
static unsigned int l_sampleRate;
static int l_channels;

static mpd_Song *currentSong;

/* connection information */
static char host[255];
static char pw[255];
static int iport;
static int plugin_enabled;
static int waittime;
struct timeval timestamp;

static mpd_Connection *conn;
static char Section[] = "Plugin:MPD";
static int errorcnt = 0;


static int configure_mpd(void)
{
    static int configured = 0;

    char *s;

    if (configured != 0)
	return configured;

    /* read enabled */
    if (cfg_number(Section, "enabled", 0, 0, 1, &plugin_enabled) < 1) {
	plugin_enabled = 0;
    }

    if (plugin_enabled != 1) {
	info("[MPD] WARNING: Plugin is not enabled! (set 'enabled 1' to enable this plugin)");
	configured = 1;
	return configured;
    }

    /* read server */
    s = cfg_get(Section, "server", "localhost");
    if (*s == '\0') {
	info("[MPD] empty '%s.server' entry from %s, assuming 'localhost'", Section, cfg_source());
	strcpy(host, "localhost");
    } else
	strcpy(host, s);

    free(s);

    /* read port */
    if (cfg_number(Section, "port", 6600, 1, 65536, &iport) < 1) {
	info("[MPD] no '%s.port' entry from %s using MPD's default", Section, cfg_source());
    }

    /* read minUpdateTime in ms */
    if (cfg_number(Section, "minUpdateTime", 500, 1, 10000, &waittime) < 1) {
	info("[MPD] no '%s.minUpdateTime' entry from %s using MPD's default", Section, cfg_source());
    }


    /* read password */
    s = cfg_get(Section, "password", "");
    if (*s == '\0') {
	info("[MPD] empty '%s.password' entry in %s, assuming none", Section, cfg_source());
	memset(pw, 0, sizeof(pw));
    } else {
	strcpy(pw, s);
	free(s);
    }

    debug("[MPD] connection detail: [%s:%d]", host, iport);
    configured = 1;
    return configured;
}


static int mpd_update()
{
    int ret = -1;
    struct timeval now;

    /* reread every 1000 msec only */
    gettimeofday(&now, NULL);
    int timedelta = (now.tv_sec - timestamp.tv_sec) * 1000 + (now.tv_usec - timestamp.tv_usec) / 1000;

    if (timedelta < waittime) {
	/* debug("[MPD] waittime not reached...\n"); */
	return 1;
    }

    /* check if configured */
    if (configure_mpd() < 0) {
	return -1;
    }
    /* check if connected */
    if (conn == NULL || conn->error) {
	if (conn) {
	    if (errorcnt < ERROR_DISPLAY)
		debug("[MPD] Error: [%s], try to reconnect to [%s]:[%i]\n", conn->errorStr, host, iport);
	    mpd_closeConnection(conn);
	} else
	    debug("[MPD] initialize connect to [%s]:[%i]\n", host, iport);

	conn = mpd_newConnection(host, iport, TIMEOUT_IN_S);
	if (conn->error) {
	    if (errorcnt < ERROR_DISPLAY)
		error("[MPD] connection failed, give up...");
	    if (errorcnt == ERROR_DISPLAY)
		error("[MPD] stop logging, until connection is fixed!");
	    errorcnt++;
	    gettimeofday(&timestamp, NULL);
	    return -1;
	}
	errorcnt = 0;
	debug("[MPD] connection fixed...");
    }

    mpd_Status *status = NULL;
    mpd_Stats *stats = NULL;
    mpd_InfoEntity *entity;

    mpd_sendCommandListOkBegin(conn);
    mpd_sendStatsCommand(conn);

    if (conn->error) {
	error("[MPD] error: %s", conn->errorStr);
	return -1;
    }

    mpd_sendStatusCommand(conn);
    mpd_sendCurrentSongCommand(conn);
    mpd_sendCommandListEnd(conn);

    stats = mpd_getStats(conn);
    if (stats == NULL) {
	error("[MPD] error mpd_getStats: %s", conn->errorStr);
	goto cleanup;
    }

    mpd_nextListOkCommand(conn);
    if ((status = mpd_getStatus(conn)) == NULL) {
	error("[MPD] error mpd_nextListOkCommand: %s", conn->errorStr);
	goto cleanup;
    }

    mpd_nextListOkCommand(conn);
    while ((entity = mpd_getNextInfoEntity(conn))) {
	mpd_Song *song = entity->info.song;

	if (entity->type != MPD_INFO_ENTITY_TYPE_SONG) {
	    mpd_freeInfoEntity(entity);
	    continue;
	}
	if (currentSong != NULL)
	    mpd_freeSong(currentSong);

	currentSong = mpd_songDup(song);
	mpd_freeInfoEntity(entity);
    }

    l_elapsedTimeSec = status->elapsedTime;
    l_totalTimeSec = status->totalTime;
    l_repeatEnabled = status->repeat;
    l_randomEnabled = status->random;
    l_bitRate = status->bitRate;
    l_state = status->state;
    l_volume = status->volume;
    l_playlistLength = status->playlistLength;
    l_currentSongPos = status->song + 1;
    l_sampleRate = status->sampleRate;
    l_channels = status->channels;

    l_numberOfSongs = stats->numberOfSongs;
    l_uptime = stats->uptime;
    l_playTime = stats->playTime;
    l_dbPlayTime = stats->dbPlayTime;


    /* sanity checks */
    if (l_volume < 0 || l_volume > 100)
	l_volume = 0;

    if (l_bitRate < 0)
	l_bitRate = 0;

    if (l_elapsedTimeSec > l_totalTimeSec || l_elapsedTimeSec < 0)
	l_elapsedTimeSec = 0;
    ret = 0;

  cleanup:
    if (stats != NULL)
	mpd_freeStats(stats);

    if (status != NULL)
	mpd_freeStatus(status);

    if (conn->error) {
	error("[MPD] error: %s", conn->errorStr);
	return -1;
    }

    mpd_finishCommand(conn);
    if (conn->error) {
	error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	return -1;
    }

    gettimeofday(&timestamp, NULL);
    return ret;
}


static void elapsedTimeSec(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_elapsedTimeSec;
    SetResult(&result, R_NUMBER, &d);
}


static void totalTimeSec(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_totalTimeSec;
    SetResult(&result, R_NUMBER, &d);
}

static void bitRate(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_bitRate;
    SetResult(&result, R_NUMBER, &d);
}


static void getRepeatInt(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_repeatEnabled;
    SetResult(&result, R_NUMBER, &d);
}


static void getRandomInt(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_randomEnabled;
    SetResult(&result, R_NUMBER, &d);
}

/* if no tag is availabe, use filename */
static void getArtist(RESULT * result)
{
    mpd_update();
    if (currentSong != NULL) {
	if (currentSong->artist != NULL) {
	    SetResult(&result, R_STRING, currentSong->artist);
	} else {
	    if (currentSong->file != NULL)
		SetResult(&result, R_STRING, currentSong->file);
	    else
		SetResult(&result, R_STRING, "");
	}
    } else
	SetResult(&result, R_STRING, "");

}

static void getTitle(RESULT * result)
{
    mpd_update();
    if (currentSong != NULL) {
	if (currentSong->title != NULL) {
	    SetResult(&result, R_STRING, currentSong->title);
	} else
	    SetResult(&result, R_STRING, "");
    } else
	SetResult(&result, R_STRING, "");

}

static void getAlbum(RESULT * result)
{
    mpd_update();
    if (currentSong != NULL) {
	if (currentSong->album != NULL)
	    SetResult(&result, R_STRING, currentSong->album);
	else
	    SetResult(&result, R_STRING, "");
    } else
	SetResult(&result, R_STRING, "");
}

static void getFilename(RESULT * result)
{
    mpd_update();
    if (currentSong != NULL) {
	if (currentSong->file != NULL)
	    SetResult(&result, R_STRING, currentSong->file);
	else
	    SetResult(&result, R_STRING, "");
    } else
	SetResult(&result, R_STRING, "");

}

/*  
    return player state:
	0=unknown
	1=play
	2=pause
	3=stop
*/
static void getStateInt(RESULT * result)
{
    double ret;

    mpd_update();

    switch (l_state) {
    case MPD_STATUS_STATE_PLAY:
	ret = 1;
	break;
    case MPD_STATUS_STATE_PAUSE:
	ret = 2;
	break;
    case MPD_STATUS_STATE_STOP:
	ret = 3;
	break;
    default:
	ret = 0;
	break;
    }

    SetResult(&result, R_NUMBER, &ret);
}


static void getVolume(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_volume;
    /* return 0..100 or < 0 when failed */
    SetResult(&result, R_NUMBER, &d);
}

/* return the # of songs in the mpd db .. */
static void getSongsInDb(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_numberOfSongs;
    SetResult(&result, R_NUMBER, &d);
}

static void getMpdUptime(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_uptime;
    SetResult(&result, R_NUMBER, &d);
}

static void getMpdPlayTime(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_playTime;
    SetResult(&result, R_NUMBER, &d);
}

static void getMpdDbPlayTime(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_dbPlayTime;
    SetResult(&result, R_NUMBER, &d);
}

static void getMpdPlaylistLength(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_playlistLength;
    SetResult(&result, R_NUMBER, &d);
}

static void getCurrentSongPos(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_currentSongPos;
    SetResult(&result, R_NUMBER, &d);
}

static void getAudioChannels(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_channels;
    SetResult(&result, R_NUMBER, &d);
}

static void getSamplerateHz(RESULT * result)
{
    double d;
    mpd_update();
    d = (double) l_sampleRate;
    SetResult(&result, R_NUMBER, &d);
}


static void nextSong()
{
    mpd_update();
    if (currentSong != NULL) {
	mpd_sendNextCommand(conn);
	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void prevSong()
{
    mpd_update();
    if (currentSong != NULL) {
	mpd_sendPrevCommand(conn);
	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void stopSong()
{
    mpd_update();
    if (currentSong != NULL) {
	mpd_sendStopCommand(conn);
	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void pauseSong()
{
    mpd_update();
    if (currentSong != NULL) {
	if (l_state == MPD_STATUS_STATE_PAUSE) {
	    mpd_sendPauseCommand(conn, 0);
	} else {
	    mpd_sendPauseCommand(conn, 1);
	}

	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void volUp()
{
    mpd_update();
    if (currentSong != NULL) {
	l_volume += 5;
	if (l_volume > 100)
	    l_volume = 100;
	mpd_sendSetvolCommand(conn, l_volume);
	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void volDown()
{
    mpd_update();
    if (currentSong != NULL) {
	if (l_volume > 5)
	    l_volume -= 5;
	else
	    l_volume = 0;
	mpd_sendSetvolCommand(conn, l_volume);
	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}

static void toggleRepeat()
{
    mpd_update();
    if (currentSong != NULL) {

	l_repeatEnabled = !l_repeatEnabled;
	mpd_sendRepeatCommand(conn, l_repeatEnabled);

	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}


static void toggleRandom()
{
    mpd_update();
    if (currentSong != NULL) {

	l_randomEnabled = !l_randomEnabled;
	mpd_sendRandomCommand(conn, l_randomEnabled);

	mpd_finishCommand(conn);
	if (conn->error) {
	    error("[MPD] error mpd_finishCommand: %s", conn->errorStr);
	}
    }
}


static void formatTimeMMSS(RESULT * result, RESULT * param)
{
    long sec;
    char myTime[6] = " ";

    sec = R2N(param);

    if ((sec >= 0) && (sec < 6000)) {
	const int minutes = (int) (sec / 60);
	const int seconds = (int) (sec % 60);
	sprintf(myTime, "%02d:%02d", minutes, seconds);
    } else if (sec >= 6000) {
	strcpy(myTime, "LONG");
    } else
	strcpy(myTime, "ERROR");

    /* store result */
    SetResult(&result, R_STRING, myTime);
}

static void formatTimeDDHHMM(RESULT * result, RESULT * param)
{
    long sec;
    char myTime[16] = " ";

    sec = R2N(param);

    if (sec >= 0) {
	int days = sec / 86400;
	int hours = (sec % 86400) / 3600;
	int minutes = (sec % 3600) / 60;
	sprintf(myTime, "%dd%02dh%02dm", days, hours, minutes);	/* 3d 12:33h */
    } else
	strcpy(myTime, "ERROR");

    /* store result */
    SetResult(&result, R_STRING, myTime);
}



int plugin_init_mpd(void)
{
    int check;
    debug("[MPD] v0.83, check lcd4linux configuration file...");

    check = configure_mpd();
    if (plugin_enabled != 1)
	return 0;

    if (check)
	debug("[MPD] configured!");
    else
	debug("[MPD] error, NOT configured!");

    /* when mpd dies, do NOT exit application, ignore it! */
    signal(SIGPIPE, SIG_IGN);
    gettimeofday(&timestamp, NULL);

    AddFunction("mpd::artist", 0, getArtist);
    AddFunction("mpd::title", 0, getTitle);
    AddFunction("mpd::album", 0, getAlbum);
    AddFunction("mpd::file", 0, getFilename);
    AddFunction("mpd::totalTimeSec", 0, totalTimeSec);
    AddFunction("mpd::elapsedTimeSec", 0, elapsedTimeSec);
    AddFunction("mpd::bitRate", 0, bitRate);
    AddFunction("mpd::getSamplerateHz", 0, getSamplerateHz);
    AddFunction("mpd::getAudioChannels", 0, getAudioChannels);
    AddFunction("mpd::getRepeatInt", 0, getRepeatInt);
    AddFunction("mpd::getRandomInt", 0, getRandomInt);
    AddFunction("mpd::getStateInt", 0, getStateInt);
    AddFunction("mpd::getVolume", 0, getVolume);
    AddFunction("mpd::getSongsInDb", 0, getSongsInDb);
    AddFunction("mpd::getMpdUptime", 0, getMpdUptime);
    AddFunction("mpd::getMpdPlayTime", 0, getMpdPlayTime);
    AddFunction("mpd::getMpdDbPlayTime", 0, getMpdDbPlayTime);
    AddFunction("mpd::getMpdPlaylistLength", 0, getMpdPlaylistLength);
    AddFunction("mpd::getMpdPlaylistGetCurrentId", 0, getCurrentSongPos);

    AddFunction("mpd::cmdNextSong", 0, nextSong);
    AddFunction("mpd::cmdPrevSong", 0, prevSong);
    AddFunction("mpd::cmdStopSong", 0, stopSong);
    AddFunction("mpd::cmdTogglePauseSong", 0, pauseSong);
    AddFunction("mpd::cmdVolUp", 0, volUp);
    AddFunction("mpd::cmdVolDown", 0, volDown);
    AddFunction("mpd::cmdToggleRandom", 0, toggleRandom);
    AddFunction("mpd::cmdToggleRepeat", 0, toggleRepeat);

    AddFunction("mpd::formatTimeMMSS", 1, formatTimeMMSS);
    AddFunction("mpd::formatTimeDDHHMM", 1, formatTimeDDHHMM);

    return 0;
}


void plugin_exit_mpd(void)
{
    if (plugin_enabled == 1) {
	debug("[MPD] disconnect from mpd");
	if (currentSong != NULL)
	    mpd_freeSong(currentSong);
	mpd_closeConnection(conn);
    }
}