/* mbed UniGraphic library - Device specific class
 * Copyright (c) 2015 Peter Drescher
 * Released under the MIT License: http://mbed.org/license/mit
 */

#include "platform.h"
#include "SSD1322.h"

//////////////////////////////////////////////////////////////////////////////////
// display settings ///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////

#define IC_X_SEGS    480  // SSD1322 SEG has range 0-479 (479-0 if MX=1), check your datasheet, important for the orientation
#define IC_Y_COMS    128  // SSD1322 COM has range 0-127 (127-0 if MY=1), check your datasheet, important for the orientation
#define BPP 4             // SSD1322 has 16 gray levels

#define SSD1322_CMD_ENABLE_GRAY_SCALE_TABLE	0x00
#define SSD1322_CMD_SET_COLUMN_ADDR		0x15
#define SSD1322_CMD_WRITE_RAM			0x5C
#define SSD1322_CMD_READ_RAM			0x5D
#define SSD1322_CMD_SET_ROW_ADDR		0x75
#define SSD1322_CMD_SET_REMAP			0xA0
#define SSD1322_CMD_SET_DISPLAY_START_LINE	0xA1
#define SSD1322_CMD_SET_DISPLAY_OFFSET		0xA2
#define SSD1322_CMD_SET_DISPLAY_MODE_OFF	0xA4
#define SSD1322_CMD_SET_DISPLAY_MODE_ON		0xA5
#define SSD1322_CMD_SET_DISPLAY_MODE_NORMAL	0xA6
#define SSD1322_CMD_SET_DISPLAY_MODE_INVERSE	0xA7
#define SSD1322_CMD_ENABLE_PARTIAL_DISPLAY	0xA8
#define SSD1322_CMD_EXIT_PARTIAL_DISPLAY	0xA9
#define SSD1322_CMD_SET_FUNCTION_SELECTION	0xAB
#define SSD1322_CMD_SET_DISPLAY_OFF		0xAE
#define SSD1322_CMD_SET_DISPLAY_ON		0xAF
#define SSD1322_CMD_SET_PHASE_LENGTH		0xB1
#define SSD1322_CMD_SET_CLOCK_DIVIDER		0xB3
#define SSD1322_CMD_DISPLAY_ENHANCEMENT		0xB4
#define SSD1322_CMD_SET_GPIO			0xB5
#define SSD1322_CMD_SET_SECOND_PRECHARGE_PERIOD	0xB6
#define SSD1322_CMD_SET_GRAY_SCALE_TABLE	0xB8
#define SSD1322_CMD_SET_DEFAULT_LINEAR_GRAY_SCALE_TABLE	0xB9
#define SSD1322_CMD_SET_PRECHARGE_VOLTAGE	0xBB
#define SSD1322_CMD_SET_VCOMH_VOLTAGE		0xBE
#define SSD1322_CMD_SET_CONTRAST_CURRENT	0xC1
#define SSD1322_CMD_MASTER_CURRENT_CONTROL	0xC7
#define SSD1322_CMD_SET_MULTIPLEX_RATIO		0xCA
#define SSD1322_CMD_DISPLAY_ENHANCEMENT_B	0xD1
#define SSD1322_CMD_SET_COMMAND_LOCK		0xFD

// set for some OLED displays
//#define ALTERNATE_OLED_VERSION


static const uint8_t oledInit[] = {
    SSD1322_CMD_SET_COMMAND_LOCK,            1, 0x12, /* Unlock OLED driver IC*/
    SSD1322_CMD_SET_DISPLAY_OFF,             0,
    SSD1322_CMD_SET_CLOCK_DIVIDER,           1, 0x91,//0xF0, //max freq, was 0x91,
    SSD1322_CMD_SET_MULTIPLEX_RATIO,         1, 0x3F, /*duty = 1/64*,64 COMS are enabled*/
    SSD1322_CMD_SET_DISPLAY_OFFSET,          1, 0x00,
    SSD1322_CMD_SET_DISPLAY_START_LINE,      1, 0x00, /*set start line position*/
    SSD1322_CMD_SET_REMAP,                   2, 0x14, // Horizontal address increment,
                                                      // Disable Column Address Re-map,
					              // Enable Nibble Re-map,Scan from COM[N-1] to COM0,
					              // Disable COM Split Odd Even
                                                0x11, // Enable Dual COM mode
    SSD1322_CMD_SET_GPIO, 		     1, 0x00,
    SSD1322_CMD_SET_FUNCTION_SELECTION,      1, 0x01, /* selection external VDD */
    SSD1322_CMD_DISPLAY_ENHANCEMENT,         2, 0xA0, /* enables the external VSL*/
                                                0xfd, /* 0xfd,Enhanced low GS display quality;default is 0xb5(normal),*/
    SSD1322_CMD_SET_CONTRAST_CURRENT,        1, 0xff, /* default is 0x7f*/
    SSD1322_CMD_MASTER_CURRENT_CONTROL,      1, 0x0f,
    /* writeCommand(0xB9); GRAY TABLE,linear Gray Scale*/
    SSD1322_CMD_SET_PHASE_LENGTH,            1, 0xE2,  /*default is 0x74*/
    SSD1322_CMD_DISPLAY_ENHANCEMENT_B,       2, 0x82, 0x20,
#ifdef ALTERNATE_OLED_VERSION
    SSD1322_CMD_SET_PRECHARGE_VOLTAGE,       1, 0x08, /* 0.3xVcc */
    SSD1322_CMD_SET_SECOND_PRECHARGE_PERIOD, 1, 0x0F, /* 15 clocks */
#else
    SSD1322_CMD_SET_PRECHARGE_VOLTAGE,       1, 0x1F, /* 0.6xVcc */
    SSD1322_CMD_SET_SECOND_PRECHARGE_PERIOD, 1, 0x08, /* default */
#endif
    SSD1322_CMD_SET_VCOMH_VOLTAGE,           1, 0x07, /*0.86xVcc;default is 0x04*/
    SSD1322_CMD_SET_DISPLAY_MODE_NORMAL,     0,
    SSD1322_CMD_SET_DISPLAY_ON,              0
};


////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////


//#include "mbed_debug.h"

#define SWAP(a, b)  { a ^= b; b ^= a; a ^= b; }


SSD1322::SSD1322(int Hz, PinName mosi, PinName miso, PinName sclk, PinName CS, PinName reset, PinName DC,
		 const char *name)
    : GraphicsDisplay(name),
      screensize_X(DISPLAY_WIDTH), screensize_Y(DISPLAY_HEIGHT),
      _BPP(BPP), _PAGES(DISPLAY_HEIGHT/8*BPP),
      _IC_X_SEGS(IC_X_SEGS), _IC_Y_COMS(IC_Y_COMS), _IC_PAGES(IC_Y_COMS/8*BPP),
      _spi(mosi, miso, sclk),
      _DC(DC), _CS(CS), _RST(reset)
{
  _RST = 1;
  _DC = 1;
  _CS = 1;
  _spi.format(8, 0);                  // 8 bit spi mode 0
  _spi.frequency(Hz);
  set_auto_up(false);
  foreground(0xFFFF);
  background(0x0000);
  hw_reset();
  init();
  set_orientation(1);
  cls();
  locate(0,0);
  //_internalEventCallback.attach(this, &SSD1322::_cbHandler);
}

void SSD1322::wr_cmd8(unsigned char cmd)
{
  _CS = 0;
  _DC.write(0); // 0=cmd
  _spi.write(cmd);      // write 8bit
  _DC.write(1); // 1=data next
  _CS = 1;
}

void SSD1322::wr_data8(unsigned char data)
{
  _CS = 0;
  _spi.write(data);    // write 8bit
  _CS = 1;

}

void SSD1322::hw_reset()
{
	ThisThread::sleep_for(15);
  _DC = 1;
  _CS = 1;
  _RST = 0;                        // display reset
  ThisThread::sleep_for(2);
  _RST = 1;                       // end reset
  ThisThread::sleep_for(100);
}

void SSD1322::bus_enable(bool enable)
{
  _CS = enable ? 0:1;
}


// monochrome SSD1322 driver ICs does not have ram rotate in hw (swap raw<->columns) like TFT displays
// for portrait views, XY swap will be done in sw in pixel() function
void SSD1322::set_orientation(int o)
{
    orientation = o;
    if (o & 0x01) {
      set_width(screensize_X);
      set_height(screensize_Y);
    } else {
      set_width(screensize_Y);
      set_height(screensize_X);
    }
    switch (o) {
    case (0):// portrait view -90°
      mirrorXY(Y);
      break;
    case (1): // default, landscape view 0°
      mirrorXY(NONE);
      break;
    case (2):// portrait view +90°
      mirrorXY(X);
      break;
    case (3):// landscape view +180°
      mirrorXY(XY);
      break;
    }
}

void SSD1322::mirrorXY(mirror_t mode)
{
  // Horizontal address increment,
  // Disable Column Address Re-map,
  // Enable Nibble Re-map,Scan from COM[N-1] to COM0,
  // Disable COM Split Odd Even
  // Enable Dual COM mode
  unsigned char d;
  switch (mode)
    {
    case(NONE):
      d = 0x14;
      break;
    case(X):
      d = 0x10;
      break;
    case(Y):
      d = 0x16;
      break;
    case(XY):
      d = 0x12;
      break;
    }
  wr_cmd8(SSD1322_CMD_SET_REMAP);
  wr_data8(d);
  wr_data8(0x11);
}

void SSD1322::invert(unsigned char o)
{
    if(o == 0) wr_cmd8(SSD1322_CMD_SET_DISPLAY_MODE_NORMAL);
    else wr_cmd8(SSD1322_CMD_SET_DISPLAY_MODE_INVERSE);
}

void SSD1322::set_contrast(int o)
{
    contrast = o;

    wr_cmd8(SSD1322_CMD_SET_CONTRAST_CURRENT);
    wr_data8(o&0xFF);
}

int SSD1322::get_contrast(void)
{
    return(contrast);
}
void SSD1322::window(int x, int y, int w, int h) {
    // current pixel location
    cur_x = x;
    cur_y = y;
    // window settings
    win_x1 = x;
    win_x2 = x + w - 1;
    win_y1 = y;
    win_y2 = y + h - 1;
}
void SSD1322::window_pushpixel(unsigned short color) {
  pixel(cur_x, cur_y, color);
  cur_x++;
  if(cur_x > win_x2) {
    cur_x = win_x1;
    cur_y++;
    if(cur_y > win_y2) {
      cur_y = win_y1;
    }
  }
}
void SSD1322::window_pushpixel(unsigned short color, unsigned int count) {
  while(count)
    {
      pixel(cur_x, cur_y, color);
      cur_x++;
      if(cur_x > win_x2)
        {
	  cur_x = win_x1;
	  cur_y++;
	  if(cur_y > win_y2)
            {
	      cur_y = win_y1;
            }
        }
      count--;
    }
}

void SSD1322::window_pushpixelbuf(unsigned short* color, unsigned int lenght) {
  while(lenght)
    {
      pixel(cur_x, cur_y, *color++);
      cur_x++;
      if(cur_x > win_x2)
        {
	  cur_x = win_x1;
	  cur_y++;
	  if(cur_y > win_y2)
            {
	      cur_y = win_y1;
            }
        }
      lenght--;
    }
}

unsigned short SSD1322::pixelpos(int x, int y)
{
    if(!(orientation&1)) SWAP(x,y);
    // first check parameter
    if((x >= screensize_X) || (y >= screensize_Y)) return 0;

    unsigned short page = y * _BPP / 8;
    return (x + page*screensize_X);
}

void SSD1322::pixel(int x, int y, unsigned short color)
{
    if(!(orientation&1)) SWAP(x,y);
    // first check parameter
    if((x >= screensize_X) || (y >= screensize_Y)) return;

    /*
    unsigned short page = y * _BPP / 8;
    unsigned char pos = y & ((8 / _BPP) - 1); // position in page
    unsigned char mask = (( 1 << _BPP) - 1);

    buffer[(x + page*screensize_X)] = (buffer[(x + page*screensize_X)] & ~(mask<<(pos*_BPP))) | ((color&mask)<<(pos*_BPP));
    */

    unsigned char cval = _pixelBuffer[(y*128) + x/2];
    if (x&1) {
      cval = (cval & 0xF0) | (color & 0x0F);
    } else {
      cval = (cval & 0x0F) | (color & 0x0F)<<4;
    }
    _pixelBuffer[(y*128) + x/2] = cval;
}

unsigned short SSD1322::pixelread(int x, int y)
{
    if(!(orientation&1)) SWAP(x,y);
    // first check parameter
    if((x >= screensize_X) || (y >= screensize_Y)) return 0;

    unsigned short page = y * _BPP / 8;
    unsigned char pos = y & ((8 / _BPP) - 1); // position in page
    unsigned char mask = (( 1 << _BPP) - 1);

    //FAUX
    return (_pixelBuffer[(x + page*screensize_X)]); // = (_pixelBuffer[(x + page*screensize_X)] & ~(mask<<(pos*_BPP))) | ((color&mask)<<(pos*_BPP));
}



// Set row address 0~64
void SSD1322::set_row_address(unsigned char start_row, unsigned char end_row)
{
  wr_cmd8(SSD1322_CMD_SET_ROW_ADDR);
  start_row &= 0x3F;
  wr_data8(start_row);
  end_row &= 0x3F;
  wr_data8(end_row);
}

// Set col address 0~64  for Gray mode)
void SSD1322::set_column_address(unsigned char start_col, unsigned char end_col)
{
  wr_cmd8(SSD1322_CMD_SET_COLUMN_ADDR);
  start_col = (start_col & 0x3F) + 0x1C;
  wr_data8(start_col); // where does this 0x1C (28) comes from???
  end_col = (end_col & 0x3F) + 0x1C;
  wr_data8(end_col);
}

void SSD1322::copy_to_lcd(void)
{
  unsigned int x, y;
  unsigned int i;
  set_row_address(0);
  set_column_address(0);

  memcpy((void*)_trBuffer,
		 (const void*)_pixelBuffer,
		 DISPLAY_BUFFER_ELEMENTS * sizeof(DISPLAY_BUFFER_TYPE));

  wr_cmd8(SSD1322_CMD_WRITE_RAM);

#ifdef DEVICE_SPI_ASYNCH
  _CS = 0;
  _spi.transfer((uint8_t*) _trBuffer, 64*128, (uint8_t*) NULL, 0, _spiEventCb);
#else
  i = 0;
  for(y=0; y<64; y++)
    for(x=0; x<128; x++)
      wr_data8(_trBuffer[i++]);
#endif
}

void SSD1322::copy_to_lcd(unsigned char from_col, unsigned char to_col,
			  unsigned char from_row, unsigned char to_row)
{
  unsigned int x, y;
  if (to_col>0x3F)
    to_col = 0x3F;
  if (to_row>0x3F)
    to_row = 0x3F;

  memcpy((void*)_trBuffer,
		 (const void*)_pixelBuffer,
		 DISPLAY_BUFFER_ELEMENTS * sizeof(DISPLAY_BUFFER_TYPE));

  set_row_address(from_row, to_row);
  set_column_address(from_col, to_col);

  wr_cmd8(SSD1322_CMD_WRITE_RAM);
  for(y=from_row; y<=to_row; y++) {
    for(x=from_col; x<=to_col; x++) {
      wr_data8(_trBuffer[y*128 + 2*x]);
      wr_data8(_trBuffer[y*128 + 2*x + 1]);
    }
  }
}

unsigned long SSD1322::buffaddr(unsigned int i)
{
  return (unsigned long) &(_pixelBuffer[i]);
}

void SSD1322::clrbuff(const unsigned char value)
{
  memset((void*)_pixelBuffer, value, screensize_X*_PAGES);
}

void SSD1322::fills(const unsigned char value)
{
  clrbuff(value);
  copy_to_lcd();
}

void SSD1322::cls(void)
{
  clrbuff();
  copy_to_lcd();
}


// reset and init the lcd controller
void SSD1322::init()
{
    /* Start Initial Sequence ----------------------------------------------------*/
    for (uint16_t ind=0; ind < sizeof(oledInit); ) {
	wr_cmd8(oledInit[ind++]);
	uint8_t dataSize = oledInit[ind++];
	while (dataSize--) {
	    wr_data8(oledInit[ind++]);
	}
    }
 }
