Date Time Convert

Di OpenERP7 date time akan di simpan dalam UTC, ketika saya membuat modul tambahan dan akan disimpan di database secara langsung menggunakan XMLRPC saya harus mengubahnya dulu ke format UTC dan JAM pun disimpan dalam tipe FLOAT karena di openerp7 sudah tidak ada field Time lagi.


'''
Created on Feb 13, 2014

@author: anton
'''
from datetime import datetime
from pytz import timezone

def convertToUTC(str_datetime):
 tz_from = timezone('Asia/Jakarta')
 tz_to = timezone('UTC')
 format_dt='%Y-%m-%d %H:%M:%S'
 dt = datetime.strptime(str_datetime, format_dt)
 current_dt = tz_from.localize(dt, is_dst=False)
 converted_dt = current_dt.astimezone(tz_to)
 return converted_dt.replace(tzinfo=None)

def convertToAsia(str_datetime):
 tz_from = timezone('UTC')
 tz_to = timezone('Asia/Jakarta')
 format_dt='%Y-%m-%d %H:%M:%S'
 dt = datetime.strptime(str_datetime, format_dt)
 current_dt = tz_from.localize(dt, is_dst=False)
 converted_dt = current_dt.astimezone(tz_to)
 return converted_dt.replace(tzinfo=None)
def timeToFloat(str_datetime):
 format_dt ='%Y-%m-%d %H:%M:%S'
 format_time = '%H:%M'
 dt = datetime.strptime(str_datetime, format_dt)
 dt = dt.strftime(format_time)
 h, m = dt.split(":")
 return int(h)+ int(m)/60.0
print convertToUTC('2013-10-7 18:24:58')
print convertToAsia('2013-10-07 11:24:58')
print timeToFloat('2013-10-07 11:24:58')



Posted in OpenERP, Python | 1 Comment

Pilih Linux atau Windows?

Pakai saja keduanya.


Menurut saya pribadi linux dan windows itu hal yang tidak perlu dibandingkan. Masing-masing memiliki kelebihan dan kekurangan. Untuk desktop pekerjaan sehari-hari menurut saya windows masih belum dapat tergantikan karena sudah banyak sekali aplikasi2/tools pihak ketiga yang tersedia baik asli maupun banjakan, jika kita memaksakan user suruh pakai linux pun nantinya malah kita yg repot karena si user banyak tanya.

Untuk di sisi server ini yang kadang membuat kita bingung mau pilih yang mana. menurut saya hal yang perlu di pertimbangkan adalah:
Usernya menggunakan sistem operasi apa?
Server yang akan kita buat untuk apa?
Jika tidak berhubungan secara langsung dengan user misalnya untuk web server, cloud server saya akan lebih memilih Linux Server. Tapi jika yang berhubungan langsung dengan user misalnya Active directory saya akan memilih Windows Server karena
bagaimanapun juga menurut saya Active directorynya si windows server lebih mudah di jalankan jika usernya juga menggunakan windows, dibandingkan jika saya harus menggunakan OpenLDAP. bukannya OpenLDAP tidak bisa di integrasikan dengan Windows tapi bisanya ada saja feature2 yang tidak dapat dijalankan di windows client.

Karena saya senang menggunakan bermacam2 sistem operasi untuk pengembangan software & infrastruktur jadi saya menggunakan keduanya. Misalnya untuk Active Directory menggunakan Windows, File Server Menggunakan SAMBAnya Linux, database menggunakan PostgreSQL nya Linux, Virtualisasi menggunakan Proxmox, ERP Software menggunakan Linux, Email Server menggunakan Linux hampir semua sisanya pakai linux.
kenapa saya tidak menggunakan linux saja semuanya biar seragam? Karena saya masih membutuhkan windows untuk aplikasi2 tertentu yang saya tidak mau repot-repot membuatnya. Misalnya untuk mesin Absensi Sidik Jari SDK yang disediakan bisanya dalam .Net Framework, kalau saya jalankan di linux menggunakan Mono belum tentu jalan, jika saya harus menggunakan bahasa pemrograman lain bisa lama cari-cari bahan untuk dipelajarinya. Untuk mail server juga saya pakai windows karena dari dulu sudah pakai windows, dan kalau saya migrasi ke linux bukannya tidak mungkin tapi itu akan menambah beban kerja saya belum tentu administratornya siap menggunakan mail server linux, belum lagi kalau ada masalah2 kedepannya misalnya email hilang lah, nyangkut, dll,
kalau hanya migrasi saja sih tidak sulit dari windows ke linux tapi operasionalnya apakah sudah siap?. itulah beberapa alasan kenapa saya tetap pakai keduanya intinya biar ga repot dan merepotkan diri sendiri.

Kemudian gimana kalau mau bikin CMS yg diintegrasikan semua infrastruktur itu dengan OpenERP disana kan ada Aplikasi Absensi yg pakai windows, ada File Server pakai Linux,
ada Active directory, dll? jika aplikasi tersebut bisa di panggil langsung dari aplikasi yang kita buat misalnya menggunakan bahasa Python langsung saja gunakan Python,
tapi jika apliaski tersebut SDK nya tidak bisa dipanggil buat saja aplikasi middle ware untuk mengaksesnya. aplikasi middle ware disini terserah mau pakai web service, socket
bebas yang penting bisa di akses.

Saya tinggal di indonesia yang memiliki semboyan Bhinneka Tunggal Ika, jadi untuk sistem operasi pun buat saya tidak perlu ada perdebatan karena walaupun berbeda-beda tetap satu tujuan.

Posted in Uncategorized | 607 Comments

Python + Raspberry PI + Arduino

percobaan pertama saya dengan Aduino membuat robot yang bisa di kontrol darimana saja selama terkoneksi dengan internet.

Arduino : Saya gunakan sebagai Controller mekanik yang berhubungan dengan Motor DC, LED, Servo
Raspberry PI : karena memory Arduino terbatas saya menggunakan Rasp PI ini Sebagai Server yang berhubungan dengan Arduino Secara langsung VIA Serial Port. sedangkan si Rasp PI sendiri berhubungan dengan internet dengan menggunakan USB WiFi

model yang saya gunakan adalah Client Server dimana Ras PI + Arduino Sebagai Server dan PC/Smartphone sebagai Client. sebenarnya cukup sederhana karena saya hanya menggunakan socket connection.

berikut script python untuk Client :


import socket
import sys
import os
import termios
import fcntl
import thread
import time
import pygame

class client_side():
def __init__(self):
self.FL_LED_STATE = False
self.FR_LED_STATE = False
self.HL_LED_STATE = False
self.SERVO_POSITION = 0
self.BACK_MOTOR_FWR_SPEED = 0
self.BACK_MOTOR_REV_SPEED = 0
self.BACK_MOTOR_FWD_SPEED_COUNTER = 0
self.BACK_MOTOR_REV_SPEED_COUNTER = 0
# self.SOUND_FOLDER ='/home/chodet/Music/'
# self.SOUND_FILE = ''
self.SOUND_STATE = True
self.SOUND_INDEX = 0
self.TCP_IP = 'localhost' # Server IP
self.TCP_PORT = int(sys.argv[1])
self.BUFFER_SIZE = 1024

def key_event(self):
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
while 1:
try:
c = sys.stdin.read(1)
break
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
return str(c)

def commanLED(self, cmd):
results = ""
if cmd == 'z':
if self.FL_LED_STATE:
self.FL_LED_STATE = False
# results = "LED:F-LEFT:0"
results = "LED:F-LEFT:0"
else:
self.FL_LED_STATE = True
results ="LED:F-LEFT:1"
if cmd == 'x':
if self.FR_LED_STATE:
self.FR_LED_STATE = False
results = "LED:F-RIGHT:0"
else:
self.FR_LED_STATE = True
results ="LED:F-RIGHT:1"
if cmd == 'c':
if self.FR_LED_STATE and self.FL_LED_STATE:
self.FR_LED_STATE = False
self.FL_LED_STATE = False
results = "LED:F-ALL:0"
else:
self.FR_LED_STATE = True
self.FL_LED_STATE = True
results = "LED:F-ALL:1"
if cmd == 'v':
if self.HL_LED_STATE:
self.HL_LED_STATE = False
results = "LED:HL:0"
else :
self.HL_LED_STATE = True
results = "LED:HL:1"
return results

def commandSERVO(self, pos):
return "SERVO:X:" + str(pos)

def commandMOTOR_FM(self, cmd):
results = ''
if cmd == 'C' :
results = "MOTOR:FM:RIGHT:1"
if cmd == 'D' :
results = "MOTOR:FM:LEFT:1"

return results

def commandMOTOR_STOP(self):
self.BACK_MOTOR_FWR_SPEED = 0
self.BACK_MOTOR_REV_SPEED = 0
return "MOTOR:STOP"

def buttonSPEED_STATE(self, cmd):
if cmd == 'q': # TRUE = INCREASE
if self.BACK_MOTOR_SPEED_STATE:
self.BACK_MOTOR_SPEED_STATE = False
else:
self.BACK_MOTOR_SPEED_STATE = True
return self.BACK_MOTOR_SPEED_STATE

def commandMOTOR_BM(self, cmd):
results = ""
if cmd == 'A':
self.BACK_MOTOR_REV_SPEED_COUNTER = 0
self.BACK_MOTOR_FWD_SPEED_COUNTER +=1
self.BACK_MOTOR_REV_SPEED = 0
if self.BACK_MOTOR_FWD_SPEED_COUNTER >=0 and self.BACK_MOTOR_FWD_SPEED_COUNTER < 6: # self.BACK_MOTOR_FWR_SPEED += 51 self.BACK_MOTOR_FWR_SPEED = 255 if self.BACK_MOTOR_FWD_SPEED_COUNTER >=6 and self.BACK_MOTOR_FWD_SPEED_COUNTER !=11:
# self.BACK_MOTOR_FWR_SPEED -=51
self.BACK_MOTOR_FWR_SPEED =255

if self.BACK_MOTOR_FWD_SPEED_COUNTER == 10:
self.BACK_MOTOR_FWD_SPEED_COUNTER = 0

# print self.BACK_MOTOR_FWR_SPEED, self.BACK_MOTOR_FWD_SPEED_COUNTER
results = "MOTOR:BM:FORWARD:"+ str(self.BACK_MOTOR_FWR_SPEED)

if cmd == 'B':
self.BACK_MOTOR_FWR_SPEED = 0
self.BACK_MOTOR_FWD_SPEED_COUNTER = 0
self.BACK_MOTOR_REV_SPEED_COUNTER +=1
if self.BACK_MOTOR_REV_SPEED_COUNTER >=0 and self.BACK_MOTOR_REV_SPEED_COUNTER < 6: # self.BACK_MOTOR_REV_SPEED += 51 self.BACK_MOTOR_REV_SPEED = 255 if self.BACK_MOTOR_REV_SPEED_COUNTER >=6 and self.BACK_MOTOR_REV_SPEED_COUNTER !=11:
# self.BACK_MOTOR_REV_SPEED -=51
self.BACK_MOTOR_REV_SPEED = 255

if self.BACK_MOTOR_REV_SPEED_COUNTER == 10:
self.BACK_MOTOR_REV_SPEED_COUNTER = 0
# print self.BACK_MOTOR_REV_SPEED, self.BACK_MOTOR_REV_SPEED_COUNTER
results = "MOTOR:BM:REVERSE:"+ str(self.BACK_MOTOR_REV_SPEED)
return results

def main(self):
results = ''

while True:
x = self.key_event()

if x == 'A': #MOTOR GO FORWARD
return self.commandMOTOR_BM(x) +'.'
elif x == 'B': #MOTOR GO REVERSE
return self.commandMOTOR_BM(x)+'.'
elif x == 'C': #MOTOR TURN RIGHT
return self.commandMOTOR_FM(x)+'.'
elif x == 'D': #MOTOR TURN LEFT
return self.commandMOTOR_FM(x)+'.'
elif x == 's': #MOTOR TURN LEFT
return self.commandMOTOR_STOP()+'.'
elif x == 'q': #MOTOR SPEED ENABLE
self.buttonSPEED_STATE(x)+'.'
elif x == 'z':
return self.commanLED(x)+'.'
elif x == 'x':
return self.commanLED(x)+'.'
elif x == 'c':
return self.commanLED(x)+'.'
elif x == 'v':
return self.commanLED(x)+'.'
elif x == 'b':
pos = raw_input("Servo Value: ")
return self.commandSERVO(pos)+'.'
elif x == 'n':
print self.getPlaylist()
self.SOUND_INDEX = int(raw_input("Enter Soud Index: "))
return "SOUND:PLAY:"+ str(self.SOUND_INDEX)
elif x == 'm':
return "SOUND:STOP"
elif x == 'i':
return "SOUND:INDEX"
elif x == 'g':
return "VIDEO:START"

def sendSTREAM(self, cmd):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((self.TCP_IP, self.TCP_PORT))
result = ''
sck.send(str(cmd))
while True:
data = sck.recv(self.BUFFER_SIZE)
if not data:
break
result += data
sck.close()
return result

def getValue(self, cmd, index):
data = cmd.split(':')
i = len(data) -1
if index > i:
index = i
return data[index]

def getPlaylist(self):
data = self.sendSTREAM('SOUND:INDEX')
results = ''
if cs.getValue(data, 0) == 'SOUND':
if cs.getValue(data, 1) == 'INDEX':
playlist = cs.getValue(data, 2)
playlist = playlist.replace('[','')
playlist = playlist.replace(']','')
playlist = playlist.replace('"','')
playlist = playlist.replace("'",'')
playlist = playlist.replace(".mp3",'')
playlist = playlist.replace(".ogg",'')
i = 0
for pl in playlist.split(','):
results += str(i)+':'+pl +'\n'
i +=1
return results

cs = client_side()
while True:
result = cs.sendSTREAM(cs.main())

if cs.getValue(result, 0) == 'SOUND':
if cs.getValue(result, 1) == 'INDEX':
print cs.getPlaylist()
else:
print result

# print cs.main()

berikut script python untuk Server pada Rasp PI :

import SocketServer
import socket
import sys
import os
import termios
import fcntl
import thread
import time
import pygame
import serial

class rc_object():
    def __init__(self):
        self.TCP_IP = 'localhost'
        self.TCP_PORT = 88
        self.BUFFER_SIZE = 1024
        self.SOUND_FOLDER ='/home/chodet/Music/'
        self.SOUND_FILE = []
        self.SOUND_FILE_PATH =''
        self.SOUND_STATE = True
        self.SOUND_INDEX = 0

    def getValue(self, cmd, index):
        data = cmd.split(':')
        i = len(data) -1
        if index > i:
            index = i
        return data[index]

    def commandExecute(self, cmd):
        cmd_data = self.getValue(cmd, 0)
        cmd_command = self.getValue(cmd, 1)
        cmd_val = self.getValue(cmd, 2)
        results = ''
        if cmd_data == 'SOUND':
            results = self.commandSound(cmd)
        elif cmd_data == 'VIDEO':
            return self.getVideo(cmd)
        else:
            self.sendSerial(cmd)
            results = cmd
        print results
        return results

    def getVideo(self, cmd):
        return True

    def sendSerial(self, cmd):
        print 'Serial: '+ cmd
        xport = '/dev/ttyACM'+str(sys.argv[1])
        ser = serial.Serial(xport, 9600)
        ser.write(cmd)
        ser.close()

    def serialMonitor(self):
        xport = '/dev/ttyACM'+str(sys.argv[1])
        ser = serial.Serial('/dev/'+xport, 9600)
        while True:
            print ser.readline()

    def sendSTREAM(self, cmd):
        sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sck.connect((self.TCP_IP, self.TCP_PORT))
        result = ''
        sck.send(str(cmd))
        while True:
            data = sck.recv(self.BUFFER_SIZE)
            if not data:
                break
            result += data
        sck.close()
        return result

    def getPlaylist(self):
        playlist_index = []
        for fn in os.listdir(self.SOUND_FOLDER):
            if fn.endswith('.mp3'):
                playlist_index.append(fn)
            elif fn.endswith('.ogg'):
                playlist_index.append(fn)

        return playlist_index

    def commandSound(self, cmd):
        mp = []
        results = ''
        cmd_data = self.getValue(cmd, 0)
        cmd_command = self.getValue(cmd, 1)
        cmd_val = self.getValue(cmd, 2)
        pgm = pygame
        pgm.mixer.pre_init(44100, -16, 2, 2048)
        pgm.init()

        if cmd_command == 'PLAY':
            if isinstance(int(cmd_val), int):
                self.SOUND_FILE = self.getPlaylist()
                self.SOUND_FILE_PATH = os.path.join(self.SOUND_FOLDER, self.SOUND_FILE[int(cmd_val)])
                if self.SOUND_FILE_PATH.endswith('.mp3'):
                    pgm.mixer.music.load(self.SOUND_FILE_PATH)
                    pgm.mixer.music.play()
                if self.SOUND_FILE_PATH.endswith('.ogg'):
                    pgm.mixer.music.load(self.SOUND_FILE_PATH)
                    pgm.mixer.music.play()
                results = 'PLAY: MP3: ' + self.SOUND_FILE[int(cmd_val)]

        if cmd_command == 'STOP':
            if pgm.mixer.music.get_busy():
                pgm.mixer.music.stop()
                results = 'STOP: MP3'
                pgm.quit()
        if cmd_command == 'INDEX':
            results = 'SOUND:INDEX:'+str(self.getPlaylist())

        return results

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        rc = rc_object()
        results = ''
        self.data = self.request.recv(1024).strip()
        results = rc.commandExecute(str(self.data))
#        print "{} wrote:".format(self.client_address[0])
        self.request.sendall(results)

if __name__ == "__main__":
    HOST, PORT = "localhost", int(sys.argv[2])

    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
    rc = rc_object()
    rc.serialMonitor()

berikut script untuk Arduino :
Library Shifter.h saya gunakan karena saya menggunakan Shift Register
tapi lupa link reference nya dimana.

#include
#include

boolean alreadyConnected = false; // whether or not the client was connected previously
Servo myservo;

#define forwardMotor 3
#define reverseMotor 5

int frontMotorLeft = 9;
int frontMotorRight = 10;
char val;

int led_left = 1;
int led_right = 2;
int led_head = 3;

String data = "";

const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 7;
Shifter shifter(dataPin, latchPin, clockPin, 2);

String inputString ="";
boolean stringComplete = false;

void setup()
{
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  myservo.attach(8);

  inputString.reserve(200);

  Serial.println("System Ready..!");
}

void loop()
{

  if (Serial.available()) {

    while (Serial.available()>0){
      val = Serial.read();
      inputString += val;
      if (val=='.'){
      stringComplete = true;
      }
    }

    if (stringComplete){
      inputString.replace(".", "");
//      Serial.println("data: "+ inputString);

    if (getValue(inputString,':',0) == "LED"){
      ledCommand(inputString);
    } else if (getValue(inputString,':',0) == "MOTOR"){
      motorCommand(inputString);
    } else if (getValue(inputString,':',0) == "SERVO"){
      servoCommand(inputString);
    } else {
    Serial.println("Unknown Command");
    }

    inputString = "";
    stringComplete = false;

    }
  }
}

void motorCommand(String command){
  String default_cmd = getValue(command,':',0);
  String cmd = getValue(command,':',1);
  String cmd_direction = getValue(command,':',2);
  int cmd_speed = getValue(command,':',3).toInt();

  if (cmd == "FM"){ // FRONT MOTOR
    if (cmd_direction == "LEFT"){
        shifter.setPin(frontMotorLeft, cmd_speed);
        shifter.write();
        delay(40);
        shifter.setPin(frontMotorLeft, LOW);
        shifter.write();

    } else if (cmd_direction == "RIGHT"){
        shifter.setPin(frontMotorRight, cmd_speed);
        shifter.write();
        delay(40);
        shifter.setPin(frontMotorRight, LOW);
        shifter.write();

    }
  }
  else if (cmd == "BM"){ // BACK MOTOR
    if (cmd_direction == "FORWARD"){
      analogWrite(reverseMotor, 0);
      analogWrite(forwardMotor, cmd_speed);
    } else if (cmd_direction == "REVERSE"){
      analogWrite(forwardMotor, 0);
      analogWrite(reverseMotor, cmd_speed);
    }
  }
  else if (cmd == "STOP"){
    shifter.setPin(frontMotorLeft, 0);
    shifter.setPin(frontMotorRight, 0);
    analogWrite(forwardMotor, 0);
    analogWrite(reverseMotor, 0);
    shifter.write();
  }

  Serial.println(default_cmd+ ", CMD: " + cmd + ", DIR: " + cmd_direction + ", SPEED: " + String(cmd_speed));
}

void servoCommand(String command){
// USAGE: SERVO:X:180
  String default_cmd = getValue(command,':',0);
  String cmd = getValue(command,':',1);
  int cmd_val = getValue(command,':',2).toInt();
  myservo.write(cmd_val);
  Serial.println(default_cmd + ", POS: "+ cmd + ", VAL: " + String(cmd_val));
}

void ledCommand(String command){
  String default_cmd = getValue(command,':',0);
  String cmd = getValue(command,':',1);
  int cmd_val = getValue(command,':',2).toInt();

    if (cmd == "F-LEFT"){ // FRONT LEFT LED
        shifter.setPin(led_left, cmd_val);
        shifter.write();

    }
    else if (cmd == "F-RIGHT"){ // FRONT RIGHT LED
        shifter.setPin(led_right, cmd_val);
        shifter.write();

    }
    else if (cmd == "F-ALL"){ // FRONT ALL LED
        shifter.setPin(led_left, cmd_val);
        shifter.setPin(led_right, cmd_val);
        shifter.write();
    }
    else if (cmd == "HL"){
        shifter.setPin(led_head, cmd_val);
        shifter.write();
    }
   Serial.println(default_cmd + ", POS: "+ cmd + ", STATE: " + String(cmd_val));

}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){     if(data.charAt(i)==separator || i==maxIndex){         found++;         strIndex[0] = strIndex[1]+1;         strIndex[1] = (i == maxIndex) ? i+1 : i;     }   }   return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

Posted in Arduino, Linux | 5 Comments

Zimbra Split Domain

Server A :

domain1.com

domain2.com

Server B

domain1.com

user@domain2.com mengirim email ke user@domain1.com, tapi email yang dikirim harus dikirim ke Server B karena server A sedang bermasalah atau hanya digunakan untuk cadangan misalnya.

caranya di Server A :

$ zmprov ma user@domain1.com zimbraMailTransport smtp:serverb.domain1.com:25

lebih jelasnya bisa dibaca pada link berikut :

Split_Domain

tips-zimbra-1-domain-beda-lokasi

tips-integrasi-zimbra-dengan-microsoft-exchange-atau-aplikasi-mail-server-lain

Posted in Zimbra | 482 Comments

OpenERP 7 Client error

untuk yang pernah mengalami error pada openerp web client dengan error sebagai berikut :

Script error.

https://apps.openerp.com/web/webclient/js?mods=web_diagram,process,web_graph,web_view_editor,web_calendar,base,web_kanban,base_setup,auth_oauth,mail,email_template,auth_signup,auth_oauth_signup,web_tests,knowledge,document,share,portal,portal_anonymous,web_analytics,loempia,web_gantt:0

error tersebut terlihat jika menggunakan browser firefox, jika menggunakan chrome mungkin berbeda bisanya hanya Script error :0

pada openerp versi 7 mungkin 6 juga termasuk. Module/Apps mencoba menarik data dari https://apps.openerp.com terlihat pada error. entah kenapa terkadang penarikan data dari apps.openerp.com kemungkinan gagal jadi menurut saya disitulah penyebab script error.

solusi yang saya lakukan adalah memaksa openerp tidak manarik data dari apps.openerp.com, yaitu dengan sedikit merubah file javascript yang terdapat dalam /openerp/addons/base/static/src/js/apps.js

script asli apps.js:

openerp.base = function(instance) {

    instance.base.apps_remote = null;
    instance.base.apps_client = null;

    var _t = instance.web._t;

    instance.base.Apps = instance.web.Widget.extend({
        template: 'EmptyComponent',
        remote_action_id: 'loempia.action_embed',
        failback_action_id: 'base.open_module_tree',

        init: function(parent, action) {
            this._super(parent, action);
            var options = action.params || {};

            if (options.apps_user) {
                sessionStorage.setItem('apps.login', options.apps_user);
            }
            if (options.apps_access_token) {
                sessionStorage.setItem('apps.access_token', options.apps_access_token);
            }

            this.params = options; // NOTE read by embedded client action
        },

        get_client: function() {
            // return the client via a deferred, resolved or rejected depending if the remote host is available or not.
            var check_client_available = function(client) {
                var d = $.Deferred();
                var i = new Image();
                i.onerror = function() {
                    d.reject(client);
                };
                i.onload = function() {
                    client.session.session_bind(client.origin).then(function() {
                        // check if client can authenticate
                        client.authenticate().then(
                           function() {     /* done */
                            d.resolve(client);
                        }, function() {     /* fail */
                            if (client.login === 'anonymous') {
                                d.reject(client);
                            } else {
                                sessionStorage.removeItem('apps.login');
                                sessionStorage.removeItem('apps.access_token');
                                client.bind_crendentials(client.dbname, 'anonymous', 'anonymous');
                                client.authenticate().then(
                                   function() {     /* done */
                                    d.resolve(client);
                                }, function() {     /* fail */
                                    d.reject(client);
                                });
                            }
                        });
                    });

                };
                i.src = _.str.sprintf('%s/web/static/src/img/sep-a.gif', client.origin);
                return d.promise();
            };
            if (instance.base.apps_client) {
                return check_client_available(instance.base.apps_client);
            } else {
                var ICP = new instance.web.Model('ir.config_parameter');
                return ICP.call('get_param', ['apps.server', 'https://apps.openerp.com/apps']).then(function(u) {
                    var link = $(_.str.sprintf('<a href="%s"></a>', u))[0];
                    var host = _.str.sprintf('%s//%s', link.protocol, link.host);
                    var dbname = link.pathname;
                    if (dbname[0] === '/') {
                        dbname = dbname.substr(1);
                    }
                    var login = (sessionStorage ? sessionStorage.getItem('apps.login') : null) || 'anonymous';
                    var passwd = (sessionStorage ? sessionStorage.getItem('apps.access_token') : null) || 'anonymous';
                    if (_.isNull(instance.base.apps_remote)) {
                        instance.base.apps_remote = new openerp.init();

                    }
                    var client = new instance.base.apps_remote.web.EmbeddedClient(null, host, dbname, login, passwd);
                    instance.base.apps_client = client;
                    return check_client_available(client);
                });
            }
        },

        destroy: function() {
            if (instance.base.apps_client) {
                instance.base.apps_client.destroy();
            }
            return this._super();
        },

        start: function() {
            var self = this;
            return self.get_client().
                done(function(client) {
                    client.replace(self.$el).
                        done(function() {
                            client.$el.removeClass('openerp');
                            client.do_action(self.remote_action_id);

                        });
                }).
                fail(function(client) {
                    self.do_warn(_t('OpenERP Apps Unreachable'), _t('Showing locally available modules'), true);
                    self.rpc('/web/action/load', {action_id: self.failback_action_id}).done(function(action) {
                        self.do_action(action);
                        instance.webclient.menu.open_action(action.id);
                    });
                });
        },
    });

    instance.base.AppsUpdates = instance.base.Apps.extend({
        remote_action_id: 'loempia.action_embed_updates'
    });

    instance.web.client_actions.add("apps", "instance.base.Apps");
    instance.web.client_actions.add("apps.updates", "instance.base.AppsUpdates");

};

hasil modifikasi sedikit apps.js :

openerp.base = function(instance) {

    instance.base.apps_remote = null;
//    instance.base.apps_client = null;
    instance.base.apps_client = true;

    var _t = instance.web._t;

    instance.base.Apps = instance.web.Widget.extend({
        template: 'EmptyComponent',
        remote_action_id: 'loempia.action_embed',
        failback_action_id: 'base.open_module_tree',

        init: function(parent, action) {
            this._super(parent, action);
            var options = action.params || {};

            if (options.apps_user) {
                sessionStorage.setItem('apps.login', options.apps_user);
            }
            if (options.apps_access_token) {
                sessionStorage.setItem('apps.access_token', options.apps_access_token);
            }

            this.params = options; // NOTE read by embedded client action
        },

        get_client: function() {
            // return the client via a deferred, resolved or rejected depending if the remote host is available or not.
            var check_client_available = function(client) {
                var d = $.Deferred();
                var i = new Image();
                i.onerror = function() {
                    d.reject(client);
                };
                i.onload = function() {
                    client.session.session_bind(client.origin).then(function() {
                        // check if client can authenticate
                        client.authenticate().then(
                           function() {     /* done */
                            d.resolve(client);
                        }, function() {     /* fail */
                            if (client.login === 'anonymous') {
                                d.reject(client);
                            } else {
                                sessionStorage.removeItem('apps.login');
                                sessionStorage.removeItem('apps.access_token');
                                client.bind_crendentials(client.dbname, 'anonymous', 'anonymous');
                                client.authenticate().then(
                                   function() {     /* done */
                                    d.resolve(client);
                                }, function() {     /* fail */
                                    d.reject(client);
                                });
                            }
                        });
                    });

                };
                i.src = _.str.sprintf('%s/web/static/src/img/sep-a.gif', client.origin);
                return d.promise();
            };
            if (instance.base.apps_client) {
                return check_client_available(instance.base.apps_client);
            } else {
                var ICP = new instance.web.Model('ir.config_parameter');
                return ICP.call('get_param', ['apps.server', 'https://apps.openerp.com/apps']).then(function(u) {
                    var link = $(_.str.sprintf('<a href="%s"></a>', u))[0];
                    var host = _.str.sprintf('%s//%s', link.protocol, link.host);
                    var dbname = link.pathname;
                    if (dbname[0] === '/') {
                        dbname = dbname.substr(1);
                    }
                    var login = (sessionStorage ? sessionStorage.getItem('apps.login') : null) || 'anonymous';
                    var passwd = (sessionStorage ? sessionStorage.getItem('apps.access_token') : null) || 'anonymous';
                    if (_.isNull(instance.base.apps_remote)) {
                        instance.base.apps_remote = new openerp.init();

                    }
                    var client = new instance.base.apps_remote.web.EmbeddedClient(null, host, dbname, login, passwd);
                    instance.base.apps_client = client;
                    return check_client_available(client);
                });
            }
        },

        destroy: function() {
            if (instance.base.apps_client) {
//                instance.base.apps_client.destroy();
            }
            return this._super();
        },

        start: function() {
            var self = this;
            return self.get_client().
                done(function(client) {
                    client.replace(self.$el).
                        done(function() {
                            client.$el.removeClass('openerp');
                            client.do_action(self.remote_action_id);

                        });
                }).
                fail(function(client) {
                    self.do_warn(_t('OpenERP Apps Unreachable'), _t('Showing locally available modules'), true);
                    self.rpc('/web/action/load', {action_id: self.failback_action_id}).done(function(action) {
                        self.do_action(action);
                        instance.webclient.menu.open_action(action.id);
                    });
                });
        },
    });

    instance.base.AppsUpdates = instance.base.Apps.extend({
        remote_action_id: 'loempia.action_embed_updates'
    });

    instance.web.client_actions.add("apps", "instance.base.Apps");
    instance.web.client_actions.add("apps.updates", "instance.base.AppsUpdates");

};

hanya itu yang saya lakukan, mungkin anda punya solusi lain yang lebih tepat silahkan di share.

Posted in OpenERP | 530 Comments

Openerp required packages

biar ga lupa disimpen disini aja, paket yang dibutuhkan untuk OpenERP Versi 6 & 7 Ubuntu Server 12.04 64bit

apt-get install python-dateutil python-feedparser python-gdata python-ldap \
    python-libxslt1 python-lxml python-mako python-openid python-psycopg2 \
    python-pybabel python-pychart python-pydot python-pyparsing python-reportlab \
    python-simplejson python-tz python-vatnumber python-vobject python-webdav \
    python-werkzeug python-xlwt python-yaml python-zsi python-docutils python-jinja2 \
    python-mock python-psutil python-unittest2 python-pip && pip install gdata --upgrade
Posted in OpenERP | 14 Comments

Http get auth Basic

import urllib2
import urllib

    def http_get_auth_basic():
            url += urllib.urlencode(datas)
            mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
            mgr.add_password(None, url, server_usernam, server_password)
            handler = urllib2.HTTPBasicAuthHandler(mgr)
            opener = urllib2.build_opener(handler)
            urllib2.install_opener(opener)
            response = urllib2.urlopen(url)
            page = response.read()
Posted in Python | 1,188 Comments

Samba NT Password

saya menggunakan ini untuk membuat NT Password dalam zimbra yang diintegrasikan dengan samba, karena saya mengintegrasikan Zimbra, Samba dalam OpenERP maka dalam membuat account saya perlu menconvert password user menjadi md4 agar client bisa login samba.

import hashlib
p='password'
n= hashlib.new( 'md4',p.encode('utf-16le')).digest().encode('hex')
print n

Posted in Python | 492 Comments

Ping dengan Python

'''
Created on Dec 11, 2012

@author: twindevil
'''
import os
hostname = "192.168.1.1" #example
response = os.system("ping -c 1 " + hostname)

#and then check the response...
if response == 0:
  print  'host up!'
else:
  print  'host down!'
Posted in Python | 508 Comments

Wake On Lan over Network + Mikrotik

Setahu saya Wake on Lan hanya dapat bekerja dalam satu network, sedangkan saya memiliki lebih dari 1 network untuk client-lient yang berbeda.

contoh kasus:

Server : 192.168.1.2

Router A :
interface ether1 : 192.168.1.1/24

Router B :
interface ether1 : 192.168.100.1/24

note : aplikasi wol dengan python ada di Server

jika saya ingin menghidupkan client dengan (IP 192.168.1.10, mac address : 00:00:00:00:11) maka saya bisa langsung menjalankan wol di server tanpa perlu bantuan router. tapi jika saya akan menghidupkan client dengan (IP 192.168.100.1000, mac address : 00:00:00:00:22) saya tidak bisa langsung hanya dengan mengeksekusi wol dari server karena sudah beda network, maknya saya menggunakan router sebagai eksekutornya.
saya membuat script python dengan ssh ke router(mikrotik) dan menjalankan perintah berikut :

/tool wol interface=ether1 00:00:00:00:22

contoh scipt :
script ini berhubungan dengan SSH Client dengan Paramiko untuk koneksi ssh nya


    def addressInNetwork(self, ip, net):
       ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
       netstr, bits = net.split('/')
       netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
       mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
       return (ipaddr & mask) == (netaddr & mask)


    def wake_on_lan(self,ipaddress, macaddress):
        if len(macaddress) == 12:
            pass
        elif len(macaddress) == 12 + 5:
            sep = macaddress[2]
            macaddress = macaddress.replace(sep, '')

        router_interface = ''
        router_ip = ''
        router_user = ''
        router_password = ''
        
        ## Router A
        if self.addressInNetwork(ipaddress, '192.168.1.0/24'):
            router_interface = 'ether1'
            router_ip = '192.168.1.1'
            router_user = 'admin'
            router_password = '***'
        ## Router B
        elif self.addressInNetwork(ipaddress, '192.168.100.0/24'):
            router_interface = 'ether1'
            router_ip = '192.168.100.1'
            router_user = 'admin'
            router_password = '***'

        ro = remote_object()
        ro.server_hostname = router_ip
        ro.server_username = router_user
        ro.server_password = router_password
        
        cmd = 'tool wol interface="'+ router_interface +'" ' + macaddress
        
#        
        ro.ssh_excute(cmd)
        ro.ssh_excute('quit')
Posted in Python | 405 Comments