Newer
Older
invertedlogic / LGN-IP3870 / qtpyui / device-files / utils.py
@John Ryland John Ryland on 19 Jan 2009 105 KB LG project files
import runtime
import os
import signal
import os.path
from setting import setting
import time, ntptime
import evas
import config
from roxiadebug import *
import status
import profile
#MMW
import stat
#end of MMW

from mmedia import Mmedia 


GETTEXT_MARKER = chr(3)	#통신프로그램의 끝을 의미(아스키 3 = ETX)

#timer
class Timer:
	def __init__(self, timeout, cb, *args):
		self.timer = runtime.evas.timeout_add(timeout, cb, *args)

	def __del__(self):
		if self.timer:
			runtime.evas.timeout_remove(self.timer)

class Idle:
	def __init__(self, cb, *args):
		self.tag = runtime.evas.idle_add(cb, *args)

	def __del__(self):
		if self.tag:
			runtime.evas.idle_remove(self.tag)

class Input:
	def __init__(self, fd, cb, *args):
		self.tag = runtime.evas.input_add(fd, evas.INPUT_READ, cb, *args)

	def __del__(self):
		if self.tag:
			runtime.evas.input_remove(self.tag)


def insert_translation_mark(s):
	return GETTEXT_MARKER + s + GETTEXT_MARKER


def changefile_gif(filename):
	import imghdr
	result = imghdr.what(filename)
	ext = ''
	if not result:
		ext = get_ext(filename)
		result = ext.lower()
		if ext.lower() == 'wbmp':
			pass

	if result in ('bmp', 'gif', 'jpeg', 'jpg', 'png'):
		#if result in ('bmp', 'gif'):
		if result in ('bmp'):
			import uiconfig
			if not os.access(uiconfig.gif_tempdir, os.R_OK):
				make_dir(uiconfig.gif_tempdir)
			remove_dir(uiconfig.gif_tempdir)
			gif_name = ''
			gif_name = filename.split('/')[-1]
			dot = gif_name.rfind('.')
			if dot >=0:
				gif_name = gif_name[:dot]
			gif_name = uiconfig.gif_tempdir + gif_name+'.png'
			os.system('imlib2_conv ' + '%r'%filename + ' ' + '%r'%gif_name)
			for i in range(30):
				if os.path.exists(gif_name):
					break
			return gif_name
		else:
			return filename
	else:
		return '/usr/local/lgvp/images/image_error.png'

#이미지를 그려준다
# KA: [20080314] phonebook UI
def put_image(name, pos, img_rg = [0, 0], img_dir=''):
	x,y = pos
	if name != '':
		runtime.evas.image_cache_flush()

		# shchun: safety code when name == None
		if len(name) == 0 or not os.access(name, os.R_OK):
			import uiconfig
			if not img_dir:
				img_dir = uiconfig.image_dir
			name = img_dir + name
			#assert os.access(name, os.R_OK)
		name = changefile_gif(name)
	else:
		pass
	image = runtime.evas.image(pos=(x,y), file=name)
	w, h = image.size_get()
	if img_rg != [0,0]:
		w, h = img_rg
	image.smooth_scale_set(0)
	image.fill_set(0, 0, w, h)
	image.size = w, h
	image.show()
	return image

def image_file_resize(in_file, out_file, width, height):
	return runtime.mmedia.image_file_resize(in_file, out_file, width, height)
	
#이미지 사이즈를 넘어온 인자값인 size로 변환한 이미지 오브젝트를 리턴한다
def put_image_sized(name, pos, size):
	if not os.access(name, os.R_OK):
		import uiconfig
		name = uiconfig.image_dir + name
		#assert os.access(name, os.R_OK)
	name = changefile_gif(name)
	image = runtime.evas.image(pos=pos, file=name)
	image.size = size
	w, h = size
	image.fill_set(0, 0, w, h)
	image.smooth_scale_set(0)
	image.show()
	return image

#이미지를 넘어온 인자값인 pos를 중심으로 하여 이미지를 그린다
def put_image_centered(name, pos):
	x,y = pos
	if not os.access(name, os.R_OK):
		import uiconfig
		name = uiconfig.image_dir + name
		#assert os.access(name, os.R_OK)
	name = changefile_gif(name)
	image = runtime.evas.image(file=name)
	w, h = image.size_get()
	x -= w/2
	y -= h/2
	image.pos = x,y
	image.size = w, h
	image.smooth_scale_set(0)
	image.fill_set(0, 0, w, h)
	image.show()
	return image

def image_sized(image, pos, size):
	image.pos = pos
	image.size = size
	image.smooth_scale_set(0)
	#image.fill_set(pos[0], pos[1], size[0],  size[1])
	image.fill_set(0,0, size[0],  size[1])
	image.show()
	return True
	
def image_center_sized2(image, pos, size):
	x, y = pos[0] - size[0]/2, pos[1] - size[1]/2
	image.pos = x, y
	image.size = size
	image.smooth_scale_set(0)
	#image.fill_set(pos[0], pos[1], size[0],  size[1])
	image.fill_set(0,0, size[0],  size[1])
	image.show()
	return True
	
#이미지를 max_w, max_h의 사이즈 안에 들어가게 사이즈 조정을 하고 center_x, center_y를 중심으로 그린다
def image_center_sized(image, center_x, center_y, max_w, max_h):
	orig_w, orig_h = image.size_get()
	w = min(max_w, orig_w)
	h = min(max_h, orig_h)
	if orig_w > w or orig_h > h:
		orig_w = float(orig_w)
		orig_h = float(orig_h)
		ratio = max(orig_w/w, orig_h/h)
		w = int(orig_w/ratio)
		h = int(orig_h/ratio)
	x,y = center_x - w / 2, center_y - h/2
	image.pos = x, y
	image.size = w, h
	image.smooth_scale_set(0)
	image.fill_set(0, 0, w, h)

#디렉토리 내의 파일들을 (파일이름, 파일크기, 최근 상태변화 시간) 튜플로 리턴
def get_file_lists(dirname):
	alists = []
	for d in os.listdir(dirname):
		if d == 'bluetooth_tmp.file':
			continue

		stat = os.stat(dirname + d)
		# stat[0] : inode protection mode
		if stat[0] & 0100000:	#regular file
			# stat[6] : ST_SIZE(file size)
			# stat[8] : ST_MTIME(last modification time)
			# stat[9] : ST_CTIME(LINUX:last metadata chage, Windows:creation time)
			#alists.append((d, stat[6], stat[9]))
			alists.append((d, stat[6], stat[8]))
	alists.sort()
	return alists

def get_img_file_lists(dirname):
	alists = []
	for d in os.listdir(dirname):
		if d == 'bluetooth_tmp.file':
			continue
			
		if not d.lower().endswith('.jpg') and not d.lower().endswith('.png') and not d.lower().endswith('.gif') :
			continue

		stat = os.stat(dirname + d)
		# stat[0] : inode protection mode
		if stat[0] & 0100000:	#regular file
			# stat[6] : ST_SIZE(file size)
			# stat[9] : ST_CTIME(creation time)
			alists.append((d, stat[6], stat[9]))
	alists.sort()
	return alists

def get_ext_img_file_lists(dirname):
	alists = []
	for d in os.listdir(dirname):
		if d == 'bluetooth_tmp.file':
			continue
			
#		if not d.lower().endswith('.jpg') and not d.lower().endswith('.png') and not d.lower().endswith('.gif') :
		if not d.lower().endswith('.jpg') and not d.lower().endswith('.png'):
			continue

		file = dirname + d

		# 1024x768 보다 큰 이미지는 skip
		'''
		tmp_w, tmp_h = get_img_size(file)
		if tmp_w * tmp_h > 1024* 768:
			continue
		'''
		
		stat = os.stat(file)
		# stat[0] : inode protection mode
		if stat[0] & 0100000:	#regular file
			# stat[6] : ST_SIZE(file size)
			# stat[9] : ST_CTIME(creation time)
			alists.append((d, stat[6], stat[9]))
	alists.sort()
	return alists
	


#디렉토리 내의 특정 확장자인 파일들을 (파일이름, 파일크기, 최근 상태변화 시간) 튜플로 리턴
def get_ext_file_lists(dirname, ext):
	alists = []
	for d in os.listdir(dirname):
		if d == 'bluetooth_tmp.file':
			continue

		if not d.lower().endswith(ext) :
			continue
		
		stat = os.stat(dirname + d)
		# stat[0] : inode protection mode
		if stat[0] & 0100000:	#regular file
			# stat[6] : ST_SIZE(file size)
			# stat[9] : ST_CTIME(creation time)
			alists.append((d, stat[6], stat[9]))
	alists.sort()
	return alists
#dirname 디렉토리 안의 파일들의 갯수를 리턴
def get_file_count(dirname):
	lists = get_file_lists(dirname)
	if config.utils_debug:
		print 'dirname, count:', len(lists)
	return len(lists)

#특정 파일의 파일 사이즈를 리턴
def get_file_size(filename):
	try:
		return os.stat(filename)[6]
	except:
		return 0


#특정 파일의 수정 시간을 리턴
def get_mdate(filename):
	return os.stat(filename)[8]

#timidity_command = "timidity --loop --no-anti-alias -E WPVSETOZ -s 8000Hz -EFresamp=d " + \
#		   "--no-mod-wheel --no-portamento --no-vibrato --no-trace-text-meta " + \
#		   "--output-mono --no-overlap-voice --no-temper-control --no-trace --quiet=y -W-"

#midiplay_command = "midiplay -1 20"

class MelodyPlayer:
	def __init__(self):
		self.pid = None
		self.amr = None
		self.mp3 = None
		self.amr_record = None
		self.camera_pid = None
		self.videopid_record = None
		self.videopid = None
		self.video_record_save = False
		self.old_sigchild = None # 0은 SIG_DFL이므로 조심
		self.old_dspg_state = None

		self.thumb_yuv = None
		self.thumb_png = None
		self.thumb_filename = ''
		self.dspg_state = None
# answer delay 06.05.17
# self.tag_play_tup = 1 : wav
# self.tag_play_tup = 2 : amr
# otherwise : not used.
		self.tag_play_tup = 0
		self.camera_ok_timer = None
		self.camera_cnt = 0
		self.position = None
		self.preview_wait_EC = False
		self.amr_chg = None
# KA: [20070816] play DTMF
		self.dtmf_play_pid = None

		self.viewfinder = None
		#self.msgPlayTimer = None



	def play_ring(self, file, loop=True, change_state=True, videopos=(56, 80, 204, 256), vol_index=None):
		'''
		if profile.ip_mode == 0:	# PSTN mode
			self.play(file, loop, change_state, videopos)
		else:
			
			if status.incoming_umts_call: # answer delay - ring from UMTS - do not use TUP - 06.06.14
				#if status.caller_number.startswith(config.UMTS_MNC_NUM):
				if config.utils_debug: print '### debug UMTS - status.caller_number=', status.caller_number
				self.play(file, loop, change_state, videopos)
			else:
				self.play(file, loop, change_state, videopos, onTup=True)
		'''
		#runtime.mmedia.audio_stop()

		# mmf file downloaded from browser
		runtime.mmedia.audio_stop()
		if file.endswith('mmf'):
			os.system('cp \"%s\" /mfs/ram/mmf/temp.mmf'%file)
			file = '/mfs/ram/mmf/temp.mmf'
			
		if vol_index != None:
			# print "[yylee debug] ring volume:", vol_index
			vol = config.ring_volume[vol_index-1]
		else:
			# print "[yylee debug] ring volume:", setting.ringer_volume
			vol = config.ring_volume[setting.ringer_volume-1]

		# 녹음벨 소리 보정
		if file.endswith('amr'):
			vol += 3
			
		runtime.SP_context.SP_stereoPlayback()

		if setting.ringer_volume == 0 and vol_index == None:
			return

		if file.endswith('mmf'):
			runtime.mmedia.audio_play_sync(file, vol)
		else:
			runtime.mmedia.audio_play(file, vol, loop)

	def stop_ring(self):
		# print "[yylee debug] utils.stop_ring invoked"	
		runtime.mmedia.audio_stop()
		runtime.SP_context.SP_stereoStopPlayback()
		#runtime.mmedia.unload()

	def play_alarm(self, file, loop=True, change_state=True, videopos=(56, 80, 204, 256), vol_index=None):
		'''
		if profile.ip_mode == 0:	# PSTN mode
			self.play(file, loop, change_state, videopos)
		else:
			
			if status.incoming_umts_call: # answer delay - ring from UMTS - do not use TUP - 06.06.14
				#if status.caller_number.startswith(config.UMTS_MNC_NUM):
				if config.utils_debug: print '### debug UMTS - status.caller_number=', status.caller_number
				self.play(file, loop, change_state, videopos)
			else:
				self.play(file, loop, change_state, videopos, onTup=True)
		'''

		runtime.mmedia.audio_stop()
		if vol_index != None:
			# print "[yylee debug] alarm volume:", vol_index
			runtime.SP_context.SP_stereoPlayback()
			runtime.mmedia.audio_play(file, config.alarm_volume[vol_index-1], loop)
		else:
			# print "[yylee debug] alarm volume:", setting.alarm_volume
			runtime.SP_context.SP_stereoPlayback()
			runtime.mmedia.audio_play(file, config.alarm_volume[setting.alarm_volume-1], loop)

	def stop_alarm(self):
		# print "[yylee debug] utils.stop_alarm invoked"	
		runtime.mmedia.audio_stop()
		runtime.SP_context.SP_stereoStopPlayback()
		#runtime.mmedia.unload()

	def play_stereo(self, file, loop=True, vol_index=None, gallery=False):
		# mmf file downloaded from browser
		runtime.mmedia.audio_stop()
		if file.endswith('mmf'):
			os.system('cp \"%s\" /mfs/ram/mmf/temp.mmf'%file)
			file = '/mfs/ram/mmf/temp.mmf'

		runtime.SP_context.SP_stereoPlayback()

		# gallery flag는 IP3870의 Mic.가 KT의 당량 기준에 따라 작게 세팅되어있으므로 , 이를 보정하기 위해
		# audio gallery에서 크게 재생해 주기 위함.
			
		if vol_index != None:
			if gallery:
				vol = config.stereo_volume[vol_index-1]+3
			else:
				vol = config.stereo_volume[vol_index-1]
		else:		
			if gallery:
				vol = config.stereo_volume[setting.stereo_volume-1]+3
			else:
				vol = config.stereo_volume[setting.stereo_volume-1]

		if file.endswith('mmf'):
			runtime.mmedia.audio_play_sync(file, vol)
		else:
			runtime.mmedia.audio_play(file, vol, loop)

	def play(self, file, loop=True, change_state=True, videopos=(0, 0, 272, 480), onTup=False, case=1):
		#status.supervision_not_allowed = 1 # vpark 11.03
		roxia_trace('MelodyPlayer.play() ~~~~~~~~~~~~~~~~~~~~')
		if self.pid:
			if config.utils_debug:
				print '**********play_melody: kill old timidity'
			self.stop(self.pid)
		# 다시 한번 확인해보자. stop. (06.05.16)
		elif self.tag_play_tup != 0:	# not playing wav nor amr
			#self.stop(onTup=True, tagp=self.tag_play_tup)
			self.stop(onTup=True)

		# options - waiting 에서의 melody play 시에는 ST_RINGER 모드로 바꾸지 않게끔
#		if change_state:
#			if status.phone_status not in (status.Disconnected, status.Dialing, status.PPPConnected):
#				if config.utils_debug:
#					print 'WARNING: melody play called when calling', runtime.manager.stage
#				return
# Please modify here --KA
#			self.old_dspg_state = runtime.dspg.get_state()
# KA: [20070724] .3gp인 경우 dspg_state: ST_MENU_REC 그럼 Volume ?? 
#			if file.lower().endswith('.3gp'):
#				runtime.dspg.set_state(runtime.dspg.ST_MENU_REC)
#			else:
#				runtime.dspg.set_state(runtime.dspg.ST_RINGER)
#				setting.set_volume(setting.ringer_volume)

		if config.utils_debug:
			print 'play melody', file, 'loop =', loop, ', self.tag_play_tup=', self.tag_play_tup
# answer delay 06.05.23
		self.tag_play_tup = 0
		if not loop and not file.lower().endswith('.amr') and not file.lower().endswith('.3gp') and file != config.for_one_ring_melody:
			def sigchld_handler(signum, stack):
				if config.utils_debug:
					print 'sigchild handler: pid=', self.pid
				os.waitpid(self.pid, 0)
				self.pid = None
				signal.signal(signal.SIGCHLD, self.old_sigchild)
				self.old_sigchild = None
				if self.old_dspg_state != None:
					runtime.dspg.set_state(self.old_dspg_state)
					self.old_dspg_state = None
			self.old_sigchild = signal.signal(signal.SIGCHLD, sigchld_handler)

		if file.lower().endswith('.amr'):
			if onTup==True and profile.ip_mode != 0:
				if config.utils_debug:
					print '=========================================='
					print '**** utils.call play_amr_on_tup *****'
				setting.set_volume(setting.ringer_volume)
				self.tag_play_tup = self.play_amr_on_tup(file)
				return self.pid
			else:
				return self.amr_play(file, loop)

		if file.lower().endswith('.3gp') or file.lower().endswith('.mid'):
			#print 'ka.... file=', file
		# KA: [20070724] audio_play 추가
			#if file.lower().startswith('/usr/local/lgvp/audios') or  file.lower().endswith('arec.3gp'):
			if file.lower().startswith('/usr/local/lgvp/audios') or  file.lower().endswith('arec.mp4'):
				#print 'ka.............audio'
				return self.audio_play(file, videopos, loop)
			else:
				#print 'ka............video'
				return self.video_play(file, videopos, loop)

#		if file.lower().endswith('.mid'):
#			runtime.dspg.set_state(runtime.dspg.ST_MIDI)
#			setting.set_volume(setting.ringer_volume)

		if file.lower().endswith('.mp3') or file.lower().endswith('.mp4'):
			return self.play_mp3(file, videopos, loop)

#ka...3800 ringplay-playulaw-wav / Not call Tup
#		if file.lower().endswith('.wav') and onTup==True and profile.ip_mode != 0:
#			if config.utils_debug:
#				print '=========================================='
#				print '**** utils.call play_wav_on_tup *****'
#				print '**** playing file : ', config.audio_root_dir + file
#				print '**** profile.ip_mode = ', profile.ip_mode
#			self.tag_play_tup = self.play_wav_on_tup(file)
#ka...3800 Temporary 2007.04.04 For play ring  using playulaw
#			return self.pid



# KA: [20080219] wav 파일만 아래 루틴을..  --- ringplay가 이곳을 안타게 되고 toneplay만 ~~
		# KA: [20080213] wav play
#		spkOffHook = runtime.SP_context.SPK_OffHook()
#		if spkOffHook.next():
#			spkOffHook.next()
#		runtime.SP_context.SP_startPlayback()
#		setting.set_volume(device=case)
		#runtime.SP_context.SP_stereoPlayback()
		# KA: [20080213] wav play ==

		self.pid = os.fork()

		if self.pid == 0:
#			try:
			#self.tag_play_tup = 0
			midi_loop = 0
			midiplay_command = ""
			if file.endswith('.mid'):
				if loop:
					midi_loop = -1
				else:
					midi_loop = 1
				file =(file,)
				midiplay_command = "midiplay %d %d" % (midi_loop, config.MIDI_VOLUME)
			else:
# KA: [20080226] tone play --> playulaw로 임시 변경 
				devices = runtime.SP_context.getCurrentDevice()
#				if not devices: # default --1 -- ringing
#					play_path	 = '1'
#					runtime.SP_context.SP_stopPlayback()
#					spkOnHook = runtime.SP_context.SPK_OnHook()
#					if spkOnHook.next():
#						spkOnHook.next()
#						spkOnHook.next()
#				else:
				play_path = '1'
				for device in devices:
					from mmiSoundPath import SP_State
					if device == SP_State.DEVICE_HS:
						play_path = '0'
					elif device == SP_State.DEVICE_SPK:
						play_path = '1'
					else:#device == SP_State.DEVICE_HSS1_TS1:
						play_path = '2'
# KA: [20080226] tone play --> playulaw로 임시 변경 ==
				if loop:
					file = ('--loop', file, play_path)
				else:
					file = (file, play_path)

			filename = file[-2]
			if filename.lower().endswith('.mid'):
				command = ('midiplay',) + tuple(midiplay_command.split()) + file
			elif filename.lower().endswith('.wav'):
				command = ('playulaw','playulaw') + file
			elif filename.lower().endswith('.imy'):
				command = ('playimy','playimy') + file
			else:
				if config.utils_debug:
					print 'I cannot play this file', file
				os._exit(1)
			roxia_trace('play command:#', command)
			os.execlp(*command)
#			except:
#				os._exit(1)

		if config.utils_debug:
			print 'player: pid=', self.pid, 'child handler', self.old_sigchild
		return self.pid

	#Roxia Begin cmlim 06.06.14
	#def stop(self, pid='', onTup=False):
	def stop(self, pid='', onTup=False, bmwi=False):
	#Roxia End cmlim 06.06.14
		if config.utils_debug:
			print 'utils.stop() onTup = ', onTup
			print 'utils.stop() tag_play_tup = ', self.tag_play_tup

#ka...3800 Temporary 2007.04.04 For play ring  using playulaw
		onTup = False
		if onTup == True and runtime.vdciapp != None and self.tag_play_tup != 0 :
			if self.tag_play_tup==1:	# wav
				self.stop_on_tup()
			elif self.tag_play_tup==2:	# amr
				self.stop_amr_on_tup()

			self.tag_play_tup = 0
			if not config.dual_audio_volume:
					if status.phone_status != status.VoiceConnected:
						setting.set_volume(setting.audio_volume)
		else:
#ka...3800 Temporary 2007.04.04 For play ring using playulaw
			if self.tag_play_tup==1:	# wav
				self.stop_on_tup()
				
			if config.utils_debug: print 'STOP media!!!!!! in utils.stop()!'
			# eicho add 06.05.29
			if self.camera_ok_timer:
				self.camera_ok_timer = None
			'''
			if self.camera_pid:
				if config.utils_debug: print 'camera preview_stop()'
				self.preview_stop()
			'''
			self.preview_stop()
			
			if not self.pid:
				return
			if pid != '' and self.pid != pid:
				return
			if config.utils_debug:
				print 'child handler', self.old_sigchild
			if self.old_sigchild != None:
				if config.utils_debug:
					print 'sigchild reset'
				signal.signal(signal.SIGCHLD, self.old_sigchild)
				self.old_sigchild = None
			if config.utils_debug:
				print 'stop melody: pid =', self.pid

			if self.amr != None:
				self.amr_end()
				return

			
			# KT DEMO 20080125
			if self.mp3 != None:
				self.mp3_end()
				return
			elif self.videopid != None:
				#Roxia Begin cmlim 06.06.14
				#self.video_end(False)
				if bmwi and (runtime.manager.stage.name == 'videorecordstage' or runtime.manager.stage.name == 'video preview'):
					pass
				else:
					self.video_end(False)
				#Roxia End cmlim 06.06.14
				return
	
			# eicho add 06.05.27
			elif self.camera_pid:
				self.preview_stop()
				return
			# eicho add 06.06.02
			elif self.amr_chg != None:
				#self.stop_change_amr()
				self.change_amr_end()

			else:
				# KA: [20080219]
#				print 'ka...######## NO PID ---- wav!!'
#				runtime.SP_context.SP_stopPlayback()
#				spkOnHook = runtime.SP_context.SPK_OnHook()
#				if spkOnHook.next():
#					spkOnHook.next()
#					spkOnHook.next()
				

				
				# 0418 - vol 조절을 kill 한 다음으로 순서 변경
				try:
					os.kill(self.pid, signal.SIGKILL)
					if config.utils_debug:
						print 'now call waitpid', self.pid
					os.waitpid(self.pid, 0)
				except:
					if config.utils_debug:
						print 'fail to kill!!!'

#				if not config.dual_audio_volume:
#					if status.phone_status != status.VoiceConnected:
#						setting.set_volume(setting.audio_volume)
# end

		'''
		if config.utils_debug:
			print 'before dspg_state = ', runtime.dspg.get_state()
		
		state = runtime.dspg.get_state()
		if self.old_dspg_state != None and \
			state != runtime.dspg.ST_V_HS_OFFHK_LPLAY and state != runtime.dspg.ST_HS_OFFHK:
			runtime.dspg.set_state(self.old_dspg_state)
			self.old_dspg_state = None
		
		if config.utils_debug:
			print 'after dspg_state = ', runtime.dspg.get_state()
		'''
		self.pid = None
		#status.supervision_not_allowed = 0

	def playing(self):
# answer delay 06.05.17
		if self.tag_play_tup != 0:
			return True
		return self.pid


	def play_video(self, file, xres, yres, xpos, ypos, vol_index=None, gallery=False):
		if vol_index == None:
			vol_index = setting.stereo_volume
		if gallery:
			vol = config.stereo_volume[vol_index-1] + 3
		else:
			vol = config.stereo_volume[vol_index-1]
		runtime.SP_context.SP_stereoPlayback()
		runtime.mmedia.unload()
		runtime.mmedia.video_play(file, vol, xres, yres, xpos, ypos)

	def stop_video(self):
		# print "[yylee debug] utils.stop_video invoked"	
		runtime.mmedia.video_stop()
		runtime.SP_context.SP_stereoStopPlayback()
		#runtime.mmedia.unload()
		
	#def msgPlayClear(self):
	#	self.msgPlayTimer = None
		
	def play_message_effect(self, message_effect_file=None, vol_index=None):
		path = config.message_effect_dir
		if setting.message_effect_file:
			message_effect_file = setting.message_effect_file
		else:
			message_effect_file = config.message_effect_default
			
		def file_check():
			filename = message_effect_file.split(path)[1]
			# 무음.wav인 경우 음원이 존재하더라도 play하지 않는다.
			if filename[-5] not in ('1', '2', '3', '4', '5'):
				return False
			for name in os.listdir(path):
				if name == filename:
					return True
			return False
					
		if not file_check():
			return

		# 5초내에 들어오는 메시지는 소리를 무시
		#if self.msgPlayTimer:
		#	return			
		#self.msgPlayTimer = Timer(5*1000, self.msgPlayClear)
		
		from mmiSoundPath import SP_Context
		from dectHandler import DectCallManager
		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		# 통화 중과 아닌 경우를 기준으로 구분한다.
		# autoanswering과 transfering은 제외한다. 
		if (baseStatus == SP_Context.CONNECTED or dectStatus == DectCallManager.CONNECTED) and \
			status.AutoAnswering == False and dectStatus != DectCallManager.TRANSFER_RINGING and baseStatus != SP_Context.TRANSFER_RINGING:
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_WAV, code2=config.MESG_PLAY_START_TUP, mesg1=message_effect_file, mesg2='1')
		else:
			devices = runtime.SP_context.getCurrentDevice()
			play_path = '1'
			for device in devices:
				from mmiSoundPath import SP_State
				if device == SP_State.DEVICE_HS:
					play_path = '0'
				elif device == SP_State.DEVICE_SPK:
					play_path = '1'
				else:#device == SP_State.DEVICE_HSS1_TS1: 
					play_path = '1'

			# QA: SMS볼륨, 효과음 볼륨을 따르도록 한다. 
			vol = setting.effect_volume

			command = 'playulaw' + ' '  + message_effect_file + ' ' + play_path + ' ' + str(vol)
			os.system(command)

	def play_effect(self, is_ok, effect_index=None, vol_index=None):
		dir = ''

		if effect_index == None:
			effect_index = setting.setting_effect_index

		if effect_index == 0: # Mute
			return True

		if effect_index == 1:
			dir = config.effect_dir + '01/'
		elif effect_index == 2:
			dir = config.effect_dir + '02/'
		elif effect_index == 3:
			dir = config.effect_dir + '03/'
		else:
			print "[yylee error] setting effect setting error - index:", setting.setting_effect_index
			return False

		path = dir
		if is_ok == 1:
			path += 'OK.mp3'
		else:
			path += 'NOK.mp3'

		runtime.SP_context.SP_stereoPlayback()
		
		runtime.mmedia.audio_stop()
		
		if vol_index != None:
			runtime.mmedia.audio_play(path, config.effect_sound[vol_index-1])
		else:
			runtime.mmedia.audio_play(path, config.effect_sound[setting.effect_volume-1])

	
	def play_keytone(self, key, keytone_index=None, vol_index=None):

		#######################################################
		# need to add some stage constraints not to play keytone in some stages.
		curr_stage_name = runtime.manager.stage.get_name()

		if curr_stage_name == 'myann':
			# print "[yylee debug] not to play keyton for browser in the ",curr_stage_name
			if vol_index != None:
				pass
			elif keytone_index != None:
				pass
			elif key == config.Red:
				# print "[yylee debug] play RED keyton for browser in the ",curr_stage_name
				pass
			else:
				return True
				
		if curr_stage_name == 'videorecordstage' or\
			curr_stage_name == 'video preview' or\
			curr_stage_name == 'videoplaystage' or\
			curr_stage_name == 'incomingcall' or\
			curr_stage_name == 'callconnecting' or\
			curr_stage_name == 'AudioCallConnecting'or\
			curr_stage_name == 'AudioCallConnected' or\
			curr_stage_name == 'AudioCallTerminated' or \
			curr_stage_name == 'VideoCallConnecting' or\
			curr_stage_name == 'VideoCallConnected' or\
			curr_stage_name == 'VideoCallTerminated' or\
			curr_stage_name == 'VideoCallImpossible' or\
			curr_stage_name == 'directaudiocalling' or\
			curr_stage_name == 'directvideocalling' or\
			curr_stage_name == 'CallConference' or\
			curr_stage_name == 'SecondIncomingCall' or\
			curr_stage_name == 'TwoCallOneHold' or\
			curr_stage_name == 'CallHold' or\
			curr_stage_name == 'BackToConnected' or\
			curr_stage_name == 'ReleaseHoldBackToConnected' or\
			curr_stage_name == 'photorelatedstage' or\
			curr_stage_name == 'audioreadystage' or\
			curr_stage_name == 'display alarm stage' or\
			curr_stage_name == 'audiorelatedstage' or\
			curr_stage_name == 'B2H_TransferStage' or\
			curr_stage_name == 'enblock edit' or\
			curr_stage_name == 'H2B_Transfer' or \
			curr_stage_name == 'new_select_effect':
			#curr_stage_name == 'audio volume' or\
			#curr_stage_name == 'new_select_bell' or\
			#curr_stage_name == 'handset volume' or\
			#curr_stage_name == 'EditGroupBell' or\
			#curr_stage_name == 'speaker volume' or\
			#curr_stage_name == 'stereo volume' or\
			#curr_stage_name == 'keytone volume' or\
			#curr_stage_name == 'effect volume' or\
			#curr_stage_name == 'alarm volume' or\
			#curr_stage_name == 'new_select_effect' or\
			#curr_stage_name == 'EditGroup' or\
			#curr_stage_name == 'addphonebook' or\

			# print "[yylee debug] not to play keyton in the ",curr_stage_name
			'''
			if vol_index != None:
				pass
			elif keytone_index != None:
				pass
			else:
				return True
			'''
			#print 'ka...........key/vol_index/keytone_index=', key, keytone_index, keytone_index
			if vol_index == None and keytone_index == None:
				return True
			else:
				pass

		# OffHook 상태로 DialTone을 듣고 있는 경우에는 keytone play를 하지 않는다. 
		try:   
			if '0' in open('/proc/driver/hook_sense').read():  
				return True
		except:
			pass
		# 통화중인 경우에 keytone play는 하지 않는다.
		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		from mmiSoundPath import SP_Context
		if baseStatus != SP_Context.IDLE:
			return True
		
		# Enblock Stage 위에 올려지는 stage는 keytone play를 하지 않는다. 
		if runtime.manager.find_stage('enblock edit'):
			return True

		if keytone_index == None:
			keytone_index = setting.button_effect_index
			
		if keytone_index == 0: # Mute
			return True

		if curr_stage_name == 'CheckPassword' or\
			curr_stage_name == 'password setting stage':
			key = '*'
		#######################################################

		# print "[yylee debug] play keytone: %s index:%d" % (key,keytone_index)


		dir = ''
		if keytone_index == 1:
			dir = config.keytone_dir + '01/'
		elif keytone_index == 2:
			dir = config.keytone_dir + '02/'
		elif keytone_index == 3:
			dir = config.keytone_dir + '03/'
		elif keytone_index == 4:
			dir = config.keytone_dir + '04/'
		else:
			print "[yylee error] buttone effect setting error - index:", keytone_index
			return False

		path = dir
		if key == '1':
			path += '1.mp3'
		elif key == '2':
			path += '2.mp3'
		elif key == '3':
			path += '3.mp3'
		elif key == '4':
			path += '4.mp3'
		elif key == '5':
			path += '5.mp3'
		elif key == '6':
			path += '6.mp3'
		elif key == '7':
			path += '7.mp3'
		elif key == '8':
			path += '8.mp3'
		elif key == '9':
			path += '9.mp3'
		elif key == '0':
			path += '0.mp3'
		elif key == '*':
			path += 'star.mp3'
		elif key == '#':
			path += 'sharp.mp3'
		elif key in ('Up', 'Down'):
			path += 'updown.mp3'
		elif key in ('Left', 'Right'):
			path += 'leftright.mp3'
		elif key == 'OK':
			path += 'ok.mp3'
		elif key == '\b' or key == 'CLR':
			path += 'clear.mp3'
		elif key == config.Green:
			path += 'green.mp3'
		elif key == config.Red:
			path += 'red.mp3'
		elif key in ('F1', 'F2', 'SOFT3', 'SOFT4', 'F7', 'F8', 'F9', 'F10', 'DOWNTOWN', 'INFORMATION'): 
			path += 'soft.mp3'
		else:
			return True
			

		print 'PLAY PLAY PLAY'
		from mmiSoundPath import SP_State
		currentDevices = runtime.SP_context.getCurrentDevice()
		if len(currentDevices) == 1 and SP_State.DEVICE_HS in currentDevices:
			pass
		else:
			runtime.SP_context.SP_stereoPlayback()
		if vol_index != None:
			runtime.mmedia.audio_play(path, config.keytone[vol_index-1])
		else:
			runtime.mmedia.audio_play(path, config.keytone[setting.keytone_volume-1])

	def amr_play(self, filename, loop=True):
		#status.supervision_not_allowed = 1
		if filename.lower().endswith('.mp4'):
			_loop = -1
			if not loop:
				_loop = 1
			runtime.SP_context.SP_stereoPlayback()
			# yylee: cleanup ept resources before recply
			runtime.mmedia.unload()
			runtime.mmedia.audio_play(filename, config.stereo_volume[setting.stereo_volume])
			self.amr = 9999
			self.pid = self.amr
			return self.pid
		'''
		if filename.lower().endswith('.amr'):
			_loop = -1
			if not loop:
				_loop = 1

			# yylee: cleanup ept resources before recply
			runtime.mmedia.unload()

			com = "/usr/local/bin/recply %d 1 1 "%_loop + "%r"%filename
			self.amr = os.popen(com, "w")
			self.pid = self.amr
			return self.pid
		'''

	def amr_record_ready(self, testmode=False):
		#status.supervision_not_allowed = 1
		#tmp_file = '/usr/local/lgvp/arec.mp4'
		tmp_file = '/usr/local/lgvp/arec.amr'
		 
		try:
			#remove('/usr/local/lgvp/arec.amr')
			remove(tmp_file)
		except:
			pass

# KA: [20080328] for testmode 미리 path를 변경한 경우 device존재 
		if testmode:
			devices = runtime.SP_context.getCurrentDevice()
			if not devices:
				path = 0
				spkOffHook = runtime.SP_context.SPK_OffHook()
				if spkOffHook.next():
					spkOffHook.next()
			else:
				# 현재는 OnHook case만 존재
				path = 1
		else:
			path = 0
			spkOffHook = runtime.SP_context.SPK_OffHook()
			if spkOffHook.next():
				spkOffHook.next()
# KA: [20080328] for testmode ==
		
		runtime.SP_context.SP_startRecord()
		
		# yylee: cleanup ept resources before recply
		runtime.mmedia.unload()

		'''
		com = "/usr/local/bin/recply -1 1 0 /usr/local/lgvp/arec.3gp 0 0 0 0 %d "%path
		self.amr = os.popen(com, "w")
		'''
		self.amr = 9999
		self.pid = self.amr
		return self.pid

	def amr_record_start(self, use_hs_mic=False):
		#status.supervision_not_allowed = 1
		#tmp_file = '/usr/local/lgvp/arec.mp4'
		tmp_file = '/usr/local/lgvp/arec.amr'
		runtime.SP_context.SP_startRecord()
		runtime.mmedia.unload()
		runtime.mmedia.recorder_recordaudio(tmp_file, use_hs_mic)
		'''
		try:
			self.amr.write("R\n")
			self.amr.flush()
			self.amr_record = self.amr
		except:
			pass
		'''

	def amr_end(self):
		# KA: [20070730] media 사용중인 경우를 고려
		# recording STOP
		if self.amr != None:
			runtime.mmedia.unload()
			'''
			try:
				self.amr.write("E\n")
				self.amr.flush()
				self.amr.close()
			except:
				pass
			'''
			self.amr = None
			self.pid = None
			self.amr_record = None
			
			spkOnHook = runtime.SP_context.SPK_OnHook()
			if spkOnHook.next():
				spkOnHook.next()
				spkOnHook.next()
			runtime.SP_context.SP_stopRecord()

#			state = runtime.dspg.get_state()
#			if self.dspg_state and state != runtime.dspg.ST_V_HS_OFFHK_LPLAY and state != runtime.dspg.ST_HS_OFFHK:
#				runtime.dspg.set_state(self.dspg_state)
#				self.dspg_state = None
#			time.sleep(0.1)
		else:
			print 'ka..........######### Already ARM END'
		
		#status.supervision_not_allowed = 0

	def video_play(self, filename, pos, loop=True):
		#status.supervision_not_allowed = 1
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()
		runtime.SP_context.SP_startPlayback()	

		if self.viewfinder == None:
			self.viewfinder = runtime.evas.rectangle()
			self.viewfinder.layer = 1
			self.viewfinder.color = (255, 255, 254, 255)
		
		self.viewfinder.geometry = (pos[1], pos[0], pos[3]-pos[1], pos[2]-pos[0])
		runtime.evas.use_transparency(True)
		self.viewfinder.show()
		
		if filename.lower().endswith(config.video_record_format):
			_loop = -1
			if not loop:
				_loop = 1
				
			# yylee: cleanup ept resources before recply
			runtime.mmedia.unload()
			
			com = "/usr/local/bin/recply %d 0 1 %s"%(_loop, filename) + " %d %d %d %d"%(pos[0], pos[1], pos[2], pos[3])
			self.videopid = os.popen(com, "w")
			self.pid = self.videopid
			#print 'ka...........video_play com=', com
			return self.pid
			
# KA: [20070724] audio_play 추가
	def audio_play(self, filename, pos, loop=True):
		#status.supervision_not_allowed = 1

# KA: [20080328] for testmode
		devices = runtime.SP_context.getCurrentDevice()
		if devices:
			pass
		else:
# KA: [20080328] for testmode ==
			spkOffHook = runtime.SP_context.SPK_OffHook()
			if spkOffHook.next():
				spkOffHook.next()

		runtime.SP_context.SP_startPlayback()		

		# yylee: cleanup ept resources before recply
		if runtime.mmedia != None:
			runtime.mmedia.unload()
		
# KA: [20070730] media 사용중인 경우를 고려
#		if filename.lower().endswith('.3gp') and not os.access('/var/run/vengine.id', os.R_OK):
		if not os.access('/var/run/vengine.id', os.R_OK):
			_loop = -1
			if not loop:
				_loop = 1
			
			com = "/usr/local/bin/recply %d 1 1 %s"%(_loop, filename) + " %d %d %d %d"%(pos[0], pos[1], pos[2], pos[3])
			self.amr = os.popen(com, "w")
			self.pid = self.amr
			#print 'ka...........audio_play com=', com
			return self.pid
		else:
			print 'ka..........######### Already PLAYING'
			
	def play_mp3(self, filename, pos, loop=True):
	
		runtime.SP_context.SP_stereoPlayback()

		# yylee: cleanup ept resources before recply
		if runtime.mmedia != None:
			runtime.mmedia.unload()
	
		if not os.access('/var/run/vengine.id', os.R_OK):
			_loop = -1
			if not loop:
				_loop = 1
			#print 'ka...##### play mp3'
			
			com = "/usr/local/bin/recply %d 1 1 %s"%(_loop, filename) + " %d %d %d %d"%(pos[0], pos[1], pos[2], pos[3])
			self.mp3 = os.popen(com, "w")
			self.pid = self.mp3
			return self.pid
		else:
			print 'ka..........######### Already PLAYING'

	def mp3_end(self):
		if self.mp3 != None:
			try:
				self.mp3.write("E\n")
				self.mp3.flush()
				self.mp3.close()
			except:
				pass
			self.mp3 = None
			self.pid = None
			self.amr_record = None
			
		runtime.SP_context.SP_stereoStopPlayback()	
	

	def video_record_ready(self, pos):
		#status.supervision_not_allowed = 1
		try:
			if config.video_record_format == '3gp':
				remove('/usr/local/lgvp/avrec.3gp')
			elif config.video_record_format == 'mp4':
				remove('/usr/local/lgvp/avrec.mp4')
			else:
				remove('/usr/local/lgvp/avrec.3gp')
		except:
			pass
#		self.dspg_state = runtime.dspg.get_state()
#		runtime.dspg.set_state(runtime.dspg.ST_MENU_REC)

		# yylee: cleanup ept resources before recply
		runtime.mmedia.unload()
		
		if self.viewfinder == None:
			self.viewfinder = runtime.evas.rectangle()
			self.viewfinder.layer = 1
			self.viewfinder.color = (255, 255, 254, 255)
			
		xpos = pos[1]
		ypos = pos[0]
		xres = pos[3]-pos[1]
		yres = pos[2]-pos[0]
		
		#self.viewfinder.geometry = (pos[1], pos[0], pos[3]-pos[1], pos[2]-pos[0])
		self.viewfinder.geometry = (xpos, ypos, xres, yres)
		runtime.evas.use_transparency(True)
		self.viewfinder.show()
		
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()
		runtime.SP_context.SP_startRecord()

		'''
		self.videopid = os.popen('/usr/local/bin/recply -1 0 0 /usr/local/lgvp/avrec.3gp %d %d %d %d 2 0 %d'%(pos[0], pos[1], pos[2], pos[3], setting.video_record_res), 'w')
		self.pid = self.videopid
		'''
		runtime.mmedia.recorder_preview(setting.video_record_res, xres, yres, xpos, ypos)
		self.videopid = 9999
		self.pid = self.videopid
		return self.pid

	def video_record_start(self):
		#status.supervision_not_allowed = 1
		print 'ka...############## Video_record_start'
		if self.videopid != None:
			#tmp_file = '/usr/local/lgvp/avrec.mp4'
			if config.video_record_format == '3gp':
				tmp_file = '/usr/local/lgvp/avrec.3gp'
			elif config.video_record_format == 'mp4':
				tmp_file = '/usr/local/lgvp/avrec.mp4'
			else:
				tmp_file = '/usr/local/lgvp/avrec.3gp'

			runtime.SP_context.SP_startRecord()
			
			runtime.mmedia.recorder_recordvideo(tmp_file)
			self.video_record_save = True
			self.videopid_record = self.videopid
			'''
			try:
				self.videopid.write("R\n")
				self.videopid.flush()
				self.video_record_save = True
				self.videopid_record = self.videopid
			except:
				pass
			'''

	def video_end(self, isthumb=True):
# KA: [20070730] media를 정리중인 경우를 고려
		if self.videopid != None and os.access('/var/run/vengine.id', os.R_OK):
			runtime.mmedia.unload()
			'''
			try:
				print 'ka....................video_end'
				self.videopid.write("E\n")
				self.videopid.flush()
				self.videopid.close()
			except:
				pass
			'''

#			import time
#			time.sleep(10)
			if self.video_record_save and isthumb:
				if config.video_record_format == '3gp':
					self.create_thumb('/usr/local/lgvp/avrec.3gp')
				elif config.video_record_format == 'mp4':
					self.create_thumb('/usr/local/lgvp/avrec.mp4')
				else:
					self.create_thumb('/usr/local/lgvp/avrec.3gp')
			self.video_record_save = False
			self.videopid = None
			self.pid = None
			self.videopid_record = None

			if self.viewfinder != None:
				self.viewfinder.hide()
				runtime.evas.use_transparency(False)
			
			spkOnHook = runtime.SP_context.SPK_OnHook()
			if spkOnHook.next():
				spkOnHook.next()
				spkOnHook.next()
			runtime.SP_context.SP_stopRecord()
#			state = runtime.dspg.get_state()
#			if self.dspg_state and state != runtime.dspg.ST_V_HS_OFFHK_LPLAY and state != runtime.dspg.ST_HS_OFFHK:
#				runtime.dspg.set_state(self.dspg_state)
#				self.dspg_state = None
#			time.sleep(0.3)
		else:
			if self.viewfinder != None:
				self.viewfinder.hide()
				runtime.evas.use_transparency(False)
			#print 'ka.....................pass Already Call VIDEO_END'
			
# KA: [20070730] media를 정리중인 경우를 고려 ==
		#status.supervision_not_allowed = 0

#################################
# answer delay 수정을 위해 변경된 부분. start
#################################

	def preview_start(self, pos=None):
# answer delay 06.05.29	
		if config.utils_debug:
			print 'check camera enabled'
			
		if self.viewfinder == None:
			self.viewfinder = runtime.evas.rectangle()
			self.viewfinder.geometry = (0,0,480,272)
			self.viewfinder.layer = 1
			self.viewfinder.color = (255, 255, 254, 255)

		self.position = pos
		self.camera_ok_timer = None
		self.preview_wait_EC = False
		self.camera_ok_timer = Timer(50, self.is_enable_camera)

	def is_enable_camera(self):
		if os.access('/proc/video/running', os.R_OK):
			if config.utils_debug: print 'can not use CAMERA!!!'
			self.camera_cnt = self.camera_cnt +1
			if self.camera_cnt > 15 :
				if config.utils_debug: print 'STOP trying to catch camera - 1)'
				return False
						#return False
			return True
		if os.access('/proc/audio_check', os.R_OK):
			if config.utils_debug: print 'can not use AUDIO!!!'
			self.camera_cnt = self.camera_cnt +1
			if self.camera_cnt > 15 :
				if config.utils_debug: print 'STOP trying to catch camera - 2)'
				return False
			return True

		self.run_camera(self.position)
		return False


###################################################################
	def run_camera(self, pos=None):
		self.camera_ok_timer = None
		self.camera_cnt = 0
		if config.utils_debug:
			print 'picture preview start'

		# yylee: cleanup ept resources before ci-capture
		runtime.mmedia.unload()
		
		import uiconfig

		if setting.photo_quality == 0: 
			cam_mode = config.STILL_CAPTURE_MODE_QVGA
			style = uiconfig.cam_cap_style_normal
		elif setting.photo_quality == 1: 
			cam_mode = config.STILL_CAPTURE_MODE_VGA
			style = uiconfig.cam_cap_style_wide
		elif setting.photo_quality == 2: 
			cam_mode = config.STILL_CAPTURE_MODE_VGA
			style = uiconfig.cam_cap_style_big
		elif setting.photo_quality == 3: 
			cam_mode = config.STILL_CAPTURE_MODE_QQVGA
			style = uiconfig.cam_cap_style_small
		elif setting.photo_quality == 4: 
			cam_mode = config.STILL_CAPTURE_MODE_CIF
			style = uiconfig.cam_cap_style_cif
		else:
			print "unknown photo quality", setting.photo_quality
			setting.photo_quality = 0
			style = cam_cap_style_normal

		#self.camera_pid = self.run("ci-capture", "ci-capture", style[0], style[1], style[4], style[5], '25000',style[2],style[3])
		#runtime.evas.set_clip(int(style[4]), int(style[5]), int(style[2]),int(style[3]))
		runtime.mmedia.still_preview(cam_mode, int(style[2]),int(style[3]), int(style[4]), int(style[5]))

		if self.viewfinder != None:
			runtime.evas.use_transparency(True)
			if setting.photo_quality == 2:
				self.viewfinder.geometry = (int(style[4]), int(style[5])+1, int(style[2]), int(style[3])-1)
			else:
				self.viewfinder.geometry = (int(style[4]), int(style[5]), int(style[2]), int(style[3]))
			self.viewfinder.show()

		# apply camera brghtness and white balance settings
		camera_brightness_set(setting.camera_brightness)
		camera_wb_set(setting.camera_white_balance)
		
		'''
		#xpos = 72
		#ypos = 40
		xpos = 0
		ypos = 0
		if pos:
			xpos = 320 - (176 + pos[0])
			ypos = pos[1]
		if setting.photo_quality == 0: # normal
			self.camera_pid = self.run("ci-capture", "ci-capture", "480", "272", str(xpos), str(ypos), '25000', '480', '248')
			#self.camera_pid = self.run("ci-capture", "ci-capture", "176", "144", str(xpos), str(ypos))
			runtime.evas.set_clip(xpos, ypos, 480, 272)
		else:
			self.camera_pid = self.run("ci-capture", "ci-capture", "320", "240", str(xpos), str(ypos))
			runtime.evas.set_clip(xpos+8, ypos+12, 160, 120)
		'''

	def check_stop_media(self):
		self.stop()
# eicho add 11.22
# kill process related 'playing video' from 'videos.PlayStage'
		curr_stage_name = runtime.manager.stage.get_name()
		if curr_stage_name =='videorecordstage' or curr_stage_name =='video preview' or curr_stage_name == 'videoplaystage':
			runtime.manager.stage.stop_play()
# end.

		loop_cnt =0
		#import time
		while loop_cnt < 3:
			time.sleep(0.1)	#sleep 100 msec.
			loop_cnt = loop_cnt + 1
			if os.access('/proc/video/running', os.R_OK):
				if config.utils_debug: print 'debug) check_stop_media - FAIL - using video '
				continue
			if os.access('/proc/audio_check', os.R_OK):
				if config.utils_debug: print 'debug) check_stop_media - FAIL - using audio '
				continue
			return True
		if config.utils_debug: print 'debug) check_stop_media - FAIL overcount'
		return False


	def is_using_media(self):
		if os.access('/proc/video/running', os.R_OK):
			if config.utils_debug: print 'debug) check_stop_media - FAIL - using video '
			# someone already use video device.
			return True
		if os.access('/proc/audio_check', os.R_OK):
			# someone already use audio device
			if config.utils_debug: print 'debug) check_stop_media - FAIL - using audio '
			return True
		if self.amr_chg != None:
			if config.utils_debug: print '### is_using_media!!! - self.amr_chg is not null ###'
			return True
		if runtime.manager.stage.get_name() == 'audio gallery' and runtime.manager.stage.player_pid != None:
			if config.utils_debug: print '### is_using_media!!! - runtime.manager.stage.player_pid is not null ###'
			return True
# eicho add 06.11.22
		curr_stage_name = runtime.manager.stage.get_name()
		if curr_stage_name == 'videoplaystage' and runtime.manager.stage.player_pid != None:
			if config.utils_debug: print '### stage videoplay - player_pid is not None! ###'
			return True

		elif curr_stage_name =='videorecordstage' or curr_stage_name =='video preview' :
			if config.utils_debug: print '### stage related to video media is on ###'
			return True
# end.
		return False

# answer delay end

	# kill camera_pid
	def preview_stop(self):

		# print "[yylee debug] stop camera preview...mmedia unload now"
		runtime.mmedia.unload()
		
		# answer delay
		self.camera_ok_timer = None
		self.camera_cnt = 0

		'''
		if not self.camera_pid:
			return
		if config.utils_debug:
			print 'picture preview stop'
		try:
			print 'ka.......KILL camera_pid=', self.camera_pid
# KA: [20070720] SIGKILL --> SIGTERM
			#os.kill(self.camera_pid, signal.SIGTERM)
			#runtime.evas.set_clip()
			if self.viewfinder != None:
				self.viewfinder.hide()
				runtime.evas.use_transparency(False)
			os.waitpid(self.camera_pid, 0)
		except:
			print 'Can not kill self.camera_pid=', self.camera_pid
		'''
		self.camera_pid = None
		#status.supervision_not_allowed = 0

	# camera pause and dump picture
	def preview_pause(self):
		#status.supervision_not_allowed = 1
		if config.utils_debug:
			print 'picture preview pause'

		runtime.mmedia.still_capture()
		runtime.mmedia.still_save_jpg()
		time.sleep(1)

		'''
		if not self.camera_pid:
			return
		print 'ka.....######## ci-capture PREVIEW_PAUSE camera_pid=', self.camera_pid
		try:
			#ret = os.kill(self.camera_pid, signal.SIGUSR1) # for png capture
			ret = os.kill(self.camera_pid, signal.SIGUSR2)   # for jpg capture
			time.sleep(1)
		except:
			print 'Can not kill self.camera_pid'
		'''

	def picture_capture(self, filename):
		#status.supervision_not_allowed = 1
		#tmpfile = '/tmp/ci-capture.png'
		tmpfile = '/tmp/ci-capture.jpg'
# KA: [20070713]  파일 복사 tmp --> taken
#		filename = '/usr/local/lgvp/'+filename

		from mmsutils import MMS_filemove
		MMS_filemove(tmpfile, filename)
		return filename

		'''
		for i in range(15):
			if os.access(tmpfile, os.R_OK):
				break
			time.sleep(0.3)
		pid = self.run("imlib2_conv", "imlib2_conv",
			tmpfile, filename)
		os.waitpid(pid, 0)
		remove_cmd('/tmp/*.png')
		remove_cmd('/tmp/*.yuv420')
		return filename
		pid = self.run("pic-capture", "pic-capture", "176", "144",
			config.image_taken_dir + filename,
			'/tmp/cap.yuv422', '1')
		os.waitpid(pid, 0)
		return filename
		'''
# KA: [20070713]  파일 복사 tmp --> taken ==


	def clip_enable(self):
		if self.viewfinder != None:
			runtime.evas.use_transparency(True)
			self.viewfinder.show()
		
	def clip_disable(self):
		if self.viewfinder != None:
			self.viewfinder.hide()
			runtime.evas.use_transparency(False)

		
	def create_thumb(self, filename):
		if not filename:
			return False
		for i in range(15):
			if os.access(filename, os.R_OK):
				break
			time.sleep(0.3)
		remove_cmd('*.yuv420')
		remove_cmd('*.png')
		path = os.path.split(filename)
		image_file = path[-1]
		dot = image_file.rfind('.')
		
		if dot < 0 or image_file[dot+1:].lower() != config.video_record_format:
			return False
		if dot >=0:
			image_file = image_file[:dot]
# KA: [20070719]
#		os.system('get_thumb ' + filename + ' ' + '/tmp/%s.yuv420'%image_file)
		if os.access('/var/run/vengine.id', os.R_OK):
			print 'ka.................wait 2 second'
			time.sleep(2)
		#else:
		#os.system('get_thumb ' + filename + ' ' + '/usr/local/lgvp/%s.png'%image_file)
		image_file = '/usr/local/lgvp/%s.png'%image_file
		runtime.mmedia.get_thumbnail( filename, image_file)
		runtime.mmedia.unload()
		print 'ka..............after get thumg'
		'''
		if os.access('/tmp/%s.yuv420'%image_file, os.R_OK):
			if os.stat('/tmp/%s.yuv420'%image_file)[6] != 0:
				print 'ka................pic-capture'
				pid = self.run("pic-capture", "pic-capture", "176", "144",
					'%s/%s.png'%(path[0],image_file), '/tmp/%s.yuv420'%image_file, '0')
				os.waitpid(pid, 0)
				return True
			else:
				return False
		else:
			return False
		'''
	def create_thumb_yuv(self, filename):
		if not filename:
			return False
		self.thumb_filename = filename
		for i in range(15):
			if os.access(filename, os.R_OK):
				break
			time.sleep(0.3)
		remove_cmd('*.yuv420')
		remove_cmd('*.png')

		path = os.path.split(filename)
		image_file = path[-1]
		dot = image_file.rfind('.')

		if dot < 0 or image_file[dot+1:].lower() != config.video_record_format:
			return False
		if dot >=0:
			image_file = image_file[:dot]

		image_file = '/usr/local/lgvp/%s.png'%image_file
		runtime.mmedia.get_thumbnail( filename, image_file)
		runtime.mmedia.unload()
		return True
		'''
		self.thumb_yuv = os.fork()
		if self.thumb_yuv == 0:
			try:
				command = ('get_thumb','get_thumb',) + (filename,) + ('/tmp/avrec.yuv420',)
				os.execlp("get_thumb","get_thumb", "%s"%filename, "/tmp/avrec.yuv420")

				return True
			except:
				self.thumb_yuv = None
				os._exit(1)
				return False
		else:
			#os.waitpid(0, os.WNOHANG)
			return True
		return False
		'''
		
	def create_thumb_png(self, filename):
		import mmsconfig
		path = os.path.split(filename)
		image_path = ''
		if path[0] == mmsconfig.mms_temp_message[:-1]:
			image_path = mmsconfig.mms_temp_message
		elif path[0] == config.video_recorded_dir[:-1]:
			image_path = config.video_recorded_thumnail_dir
		else:
			image_path = config.video_received_thumnail_dir
		image_file = path[-1]
		dot = image_file.rfind('.')
		if dot < 0 or image_file[dot+1:].lower() != '3gp':
			return 0
		if dot >=0:
			image_file = image_file[:dot]
		if os.access('/tmp/avrec.yuv420', os.R_OK):
			if os.stat('/tmp/avrec.yuv420')[6] == 0:
				return 0
			else:
				self.thumb_png = os.fork()
				if self.thumb_png == 0:
					try:
						os.execlp("pic-capture", "pic-capture", "176", "144",
								"%s%s.png"%(image_path,image_file), "/tmp/avrec.yuv420", "0")
						return 1
					except:
						os._exit(1)
						self.thumb_png = None
						if config.utils_debug:
							print 'create_png fork() fail - 0'
						return 0
				else:
					os.waitpid(0, os.WNOHANG)
					return 1
				return 0
		else:
			return 2

	def delete_thumb(self, isyuv=True):
		if self.thumb_yuv and isyuv:
			try:
				os.kill(self.thumb_yuv, signal.SIGKILL)
				os.waitpid(self.thumb_yuv, 0)
			except:
				pass
			self.thumb_yuv = None
		if self.thumb_png:
			try:
				os.kill(self.thumb_png, signal.SIGKILL)
				os.waitpid(self.thumb_png, 0)
			except:
				pass
			self.thumb_png = None

	def videocall_capture(self):
		#status.supervision_not_allowed = 1
		date = "photo"
		findex = setting.photo_serial
		while 1:
			filename = date + "%03d" % findex
			if not os.access(config.image_taken_dir + filename + '.jpg', os.R_OK):
				break
			findex = (findex + 1) % 1000
		setting.photo_serial = findex + 1
		time.sleep(0.5)
		fileSize = 0
		for i in range(300):
			if os.access('/tmp/cap.yuv420', os.R_OK):
				fileSize = os.stat('/tmp/cap.yuv420')[6]
				if fileSize != 0:
					break
		# KA:[20081111]QA8-7: video capture파일이 생성이 안된 경우:
		if fileSize == 0:
			return False
			
		# os.stat(filename)[6]
		CIFsize = 352 * 288 * 3 / 2 
		QCIFsize = 176 * 144 * 3 / 2
		if fileSize == CIFsize:
			size = "352 288"
		else:
			size = "176 144"
		
		# 352 288 / 176 144
		#command = "pic-capture" + ' ' + size+ ' '+ '/tmp/' + filename + '.png' + ' ' + '/tmp/cap.yuv420'+ ' ' +'0'
		command = "pic-capture" + ' ' + size+ ' '+ '/tmp/' + filename + '.jpg' + ' ' + '/tmp/cap.yuv420'+ ' ' +'0'
		os.system(command)
		
		from mmsutils import MMS_filemove
		try:
			MMS_filemove('/tmp/'+filename + '.jpg',  config.image_taken_dir + filename + '.jpg')
		except:
			#runtime.manager.change_stage(NotifyStage(_('Save failed'), uiconfig.baloon_record_icon))
			return False
			
		remove_cmd('/tmp/*.jpg')
		remove_cmd('/tmp/*.yuv420')
		return config.image_taken_dir + filename + '.jpg'
# KA: [20070725] video capture == 

	def play_message(self, play_error=False):
		#status.supervision_not_allowed = 1
		#import profile
		if profile.ip_mode == 1:
			if play_error == 'busy':
				import vdciapp
				vdciapp.vdcitone_play_tone(config.PLAY_BUSY_TONE)
				return
			elif play_error == 'cg':
				import vdciapp
				vdciapp.vdcitone_play_tone(config.PLAY_CG_TONE)
				return
			elif play_error == 'connecting':
				pass
			else:
				#play_message is skip for VoIP call
				return

		dspg = runtime.dspg
		message_dir = './audios/messages/'
		play_file = ''
		if play_error != 'connecting' and play_error:
			if setting.lang == 'English':
				play_file = 'M6_Eng.wav'
			else:
				play_file = 'M6_Spa.wav'
		else:
			if setting.lang == 'English':
				play_file = 'M3_Eng.wav'
			else: # spanish
				if runtime.vdciapp.caller:
					play_file = 'M3_Spa.wav'
				else:
					play_file = 'M3_Spa2.wav'

		play_file = message_dir + play_file
		if self.pid:
			self.stop_message()
		if status.modem_audio_state == status.HS:
			dspg.set_state(dspg.ST_V_HS_OFFHK_LPLAY)
		elif status.modem_audio_state == status.SPK:
			dspg.set_state(dspg.ST_V_SPK_OFFHK_LPLAY)
		if play_error != 'connecting' and play_error:
			def playover_signal_handler(sig, stack):
				if self.pid:
					pid, status = os.waitpid(self.pid, os.WNOHANG)
					if pid <= 0:
						# not us
						return
					signal.signal(signal.SIGCHLD, signal.SIG_DFL)
					self.stop_message(False)
			signal.signal(signal.SIGCHLD, playover_signal_handler)
			self.pid = self.run("playulaw", "playulaw", play_file)
		else:
			self.pid = self.run("playulaw", "playulaw", '--loop', play_file)
		return False	# for timer

	def stop_message(self, cleanup_child=True):
		import vdciapp
		if vdciapp.vdcitone_is_playing():
			vdciapp.vdcitone_stop_tone()
		if not self.pid:
			return

		if cleanup_child:
			self.amr_end()
			signal.signal(signal.SIGCHLD, signal.SIG_DFL)
			try:
				os.kill(self.pid, signal.SIGKILL)
				os.waitpid(self.pid, 0)
			except:# OSError:
				pass

		self.pid = None
		dspg = runtime.dspg

	def run(self, *command):
		if config.utils_debug:
			print 'command run', command
		pid = os.fork()
		if pid == 0:
			try:
				os.execlp(*command)
			except:
				os._exit(1)
		return pid


# ka...3800 ringback--> tone play 2007.05.11
	def start_ringback_tone(self, channel):
		import status
		self.current_tone_channel = status.get_current_channel()
		runtime.vdci_send_mesg(code1=config.MESG_CALL_WAITING_CODE1, \
					code2=config.MESG_CALL_WAITING_START, \
					chan1=int(channel), \
					mesg1='RINGBACK', \
					mesg2=config.MESG_CALL_WAITING_MESG2)

#	runtime.vdciapp.send_mesg(code1=config.MESG_CALL_WAITING_CODE1, \
#				code2=config.MESG_CALL_WAITING_START, \
#				chan1=self.current_tone_channel, \
#				mesg1='RINGBACK', \
#				mesg2=config.MESG_CALL_WAITING_MESG2)

		return True

		
	def stop_ringback_tone(self):
		if self.ringback_tone_timer != None :
			del(self.ringback_tone_timer)
		self.ringback_tone_timer = None
		
# 06.07.07 change cwi tone.
		'''
		if self.current_tone_channel == 0 :
			return
			
		runtime.vdci_send_mesg(code1=config.MESG_CALL_WAITING_CODE1, \
					code2=config.MESG_CALL_WAITING_STOP, \
					chan1=self.current_tone_channel)
		'''
		
		#self.current_tone_channel = 0


# answer dealy modification - 06.05.15
	def play_ringback_on_tup(self,  loop=True):
		if runtime.vdciapp == None:
			return False
		try :
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RINGBACK_TUP,  \
						code2=config.MESG_PLAY_START_TUP, \
						mesg1='RINGBACK', mesg2=99)
			return True
		except :
			print 'play_ringback_on_tup occurs exception!!!'
		return False

	def play_wav_on_tup(self, file):
		if runtime.vdciapp == None:
			return 0
		try :
			p_filename =  config.audio_root_dir  + file
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_WAV,  \
						code2=config.MESG_PLAY_START_TUP, \
						mesg1=p_filename)
			return 1
		except :
			print 'play_wav_on_tup occurs exception!!!'
		return 0

	def play_amr_on_tup(self, file):
		if runtime.vdciapp == None:
			return 0
		try :
			'''
			p_filename =  config.audio_root_dir  + file
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_AMR,  \
						code2=config.MESG_PLAY_START_TUP, \
						mesg1=p_filename)
			return 2
			'''

			p_filename = config.audio_root_dir + self.change_name_audiowav(file)

			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_WAV,  \
						code2=config.MESG_PLAY_START_TUP, \
						mesg1=p_filename)
			return 1

		except :
			print 'play_amr_on_tup occurs exception!!!'
		return 0

	def stop_on_tup(self):
		if runtime.vdciapp == None:
			if config.utils_debug: print 'Utils.stop_on_tup can not go on next step. vdciapp is null'
			return
		try :
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_WAV,  \
						code2=config.MESG_PLAY_STOP_TUP)

		except :
			print 'stop_on_tup occurs exception!!!'

	def stop_amr_on_tup(self):
		self.stop_on_tup()
		'''
		if runtime.vdciapp == None:
			if config.utils_debug: print 'Utils.stop_amr_on_tup can not go on next step. vdciapp is null'
			return
		try :
			runtime.vdciapp.send_mesg(code1=config.MESG_PLAY_RING_AMR,  \
						code2=config.MESG_PLAY_STOP_TUP)

		except :
			print 'stop_on_tup occurs exception!!!'
		'''


########### add codes for set AMR as ring (wav) ### 06.06.01
	def change_name_audiowav(self, file):
		if file.startswith(config.audio_recorded_dir):
			p_filename = file.replace(config.audio_recorded_dir, config.audio_amr2wav_recorded_dir)
		elif file.startswith(config.audio_polyphonic_dir):
			p_filename = file.replace(config.audio_polyphonic_dir, config.audio_amr2wav_polyphonic_dir)
		elif file.startswith(config.audio_other_dir):
			p_filename = file.replace(config.audio_other_dir, config.audio_amr2wav_other_dir)
		else:
			p_filename = file
		return p_filename.replace('.amr', '.wav')

	def chage_amr_wav(self, cmd):
		#print '### AMR2WAV : command => ', cmd
		self.amr_chg = os.popen(cmd, "w")
		self.pid = self.amr_chg

		return self.pid

	def set_ring_amr(self, file_name):
		#print '### set_ring_amr/file_name from sounds =', file_name

		import status
		if status.call_status == status.IncomingCall:
			print '### AMR2WAV : Can not start during incoming call'
			return ''

		if self.pid:
			#self.stop_change_amr(self.pid)
			self.stop(self.pid)
		fullfilename = self.change_name_audiowav(file_name)
		if file_name.lower().endswith('.amr'):
			command = "/usr/local/bin/amr2wav "+ config.audio_root_dir + file_name + " " + config.audio_root_dir + fullfilename
			return self.chage_amr_wav(command)

		self.pid = os.fork()
		if self.pid == 0:
			try:
				os.execlp(*command)
			except:
				os._exit(1)

		return self.pid

################## 06.07.25
	def set_as_user_ring(self, file_name):
		import status
		if status.call_status == status.IncomingCall:
			print '### AMR2WAV : Can not start during incoming call'
			return False

		try: 
			file_name = unicode(file_name, 'utf-8').encode('euc-kr')
		except:
			pass 

		if file_name.lower().endswith('.amr'):
			fullfilename = self.change_name_audiowav(file_name)
			command = "/usr/local/bin/amr2wav "+ config.audio_root_dir + file_name + " " + config.audio_root_dir + fullfilename
			if config.utils_debug:
				print '# set_as_user_ring) COMMAND: ', command
			os.system(command)
		return True
	
	def set_as_ring_cmd(self, file_name):
		#import time
		#print '### start set_as_ring_cmd: ', time.asctime()
		
		import status
		if status.call_status == status.IncomingCall:
			print '### AMR2WAV : Can not start during incoming call'
			return ''
   
		try:   
			file_name = unicode(file_name, 'utf-8').encode('euc-kr')   
		except:   
			pass 
			
		fullfilename = self.change_name_audiowav(file_name)
		if file_name.lower().endswith('.amr'):
			command = "/usr/local/bin/amr2wav "+ config.audio_root_dir + file_name + " " + config.audio_root_dir + fullfilename
			os.system(command)
			setting.external_ring = file_name
			
		#print '### end set_as_ring_cmd: ', time.asctime()
		
		
	def change_amr_end(self):
		if self.amr_chg != None:
			try:
				self.amr_chg.write("E\n")
				self.amr.flush()
				self.amr.close()
			except:
				print '### change_amr_end : except writing flush'

			self.amr_chg = None
			self.pid = None
			# eicho change sleep time to 500 msec. 06.07.25
			# time.sleep(0.1)
			time.sleep(0.5)


	def stop_change_amr(self, pid=''):
		if not self.pid:
			return
		if pid != '' and self.pid != pid:
			return
		if pid == None:
			return
		if self.amr_chg != None:
			self.change_amr_end()
		else:
			try:
				os.kill(self.pid, signal.SIGKILL)
				if config.utils_debug:
					print 'now call waitpid', self.pid
				os.waitpid(self.pid, 0)
			except:
				if config.utils_debug:
					print 'fail to kill!!!'

			if not config.dual_audio_volume:
				if status.phone_status != status.VoiceConnected:
					setting.set_volume(setting.audio_volume)
		self.pid = None

# KA: [20070816] play DTMF
	def dtmf_ready(self):
#		self.dspg_state = runtime.dspg.get_state()
#		runtime.dspg.set_state(runtime.dspg.ST_MENU_REC)
		if self.dtmf_play_pid:
			return
		self.dtmf_play_pid = os.popen('/usr/local/bin/play_dtmf', 'w')
#		self.pid = self.dtmf_play_pid
		return self.dtmf_play_pid

	def dtmf_play(self, key):
		print 'ka...############## dtmf_play key=', key
		if not self.dtmf_play_pid:
			self.dtmf_play_pid = os.popen('/usr/local/bin/play_dtmf', 'w')
		
		if self.dtmf_play_pid != None:
			#try:
			self.dtmf_play_pid.write(key)
			self.dtmf_play_pid.flush()
				#self.video_record_save = True
				#self.videopid_record = self.videopid
			#except:
			#	pass

	def dtmf_stop(self):
		if self.dtmf_play_pid != None:
			try:
				self.dtmf_play_pid.write("E\n")
				self.dtmf_play_pid.flush()
				self.dtmf_play_pid.close()
			except:
				print '### change_DTMF_PLAY_end : except writing flush'

			self.dtmf_play_pid = None
			self.pid = None
# KA: [20070816] play DTMF ==

# end.

player = MelodyPlayer()

#시스템 시간을 바꿈
#시간변경시 'date' 실행권한 에러 발생함. 에러발생이후 indicator bar의 시간이 깜빡이지 않음
def set_time(year, mon, day, hour, min):
	date_command = 'date %02d%02d%02d%02d%04d' % (mon, day, hour, min, year)
	if config.utils_debug:
		print date_command
	os.system(date_command)

# SRS WOW-enable
def enable_srswow():
	os.system('echo 1 > /proc/sys/srswow/enableWowHD')
	setting.srswow_enable = 1

# SRS WOW-disable
def disable_srswow():
	os.system('echo 0 > /proc/sys/srswow/enableWowHD')
	setting.srswow_enable = 0

def is_srswow_enabled():
	enable_file = '/proc/sys/srswow/enableWowHD'
	if not os.access(enable_file, os.R_OK):
		return False
	enable = open(enable_file).read()
	if enable == '':
		return False
	else:
		if int(enable) > 0:
			return True
		return False
	
def get_srswow_preset():
	preset_file = '/proc/sys/srswow/WowHD_preset'
	if not os.access(preset_file, os.R_OK):
		return 0
	preset = open(preset_file).read()
	if preset == '':
		return 0
	else:
		preset_val = int(preset)
		return preset_val

def set_srswow_preset(preset):
	if preset > 5 or preset <0:
		print "[utils.set_srswow_preset] invalid preset value", preset
		return
	preset_file = '/proc/sys/srswow/WowHD_preset'
	cmd = "echo %d > %s"%(preset, preset_file)
	os.system(cmd)
	return

def usb_mount_ready():
	os.system('echo 1 > /proc/sys/lvp3870/usb_uart_switch')
	os.system('sync')
	os.system('mount -t usbfs usbfs /proc/bus/usb/')
	os.system('sync')
	os.system('sync')
	time.sleep(1)

def usb_mount(dev='/dev/sda1'):
	os.system('mount -t vfat %s /mnt -o iocharset=cp949'%dev)
	os.system('sync')
	os.system('sync')
	time.sleep(1)
	os.system('cd /mnt')

	
def usb_umount():
	os.system('cd /')
	os.system('umount /mnt')
	os.system('umount /proc/bus/usb')
	os.system('sync')
	os.system('echo 0 > /proc/sys/lvp3870/usb_uart_switch')
	
#lcdoff
def lcd_off():
	if config.utils_debug:
		print '*******************LCD OFF'
	os.system('lcdoff 1')
	status.lcdOn = False

#lcdon
def lcd_on():
	if config.utils_debug:
		print '*******************LCD ON'
	os.system('lcdoff 0')
	if runtime.manager != None:
		runtime.manager.handle_lighting()
		if not runtime.manager.in_night_mode:
			runtime.manager.set_brightness(setting.brightness-1)
	status.lcdOn = True

def check_lcd_on():
	return status.lcdOn

#system reset
def system_reset(reboot=True):
	setting.reset()
	from phonedb import phonedb
	phonedb.reset()
	from speeddb import speeddb
	speeddb.reset()
	from groupdb import groupdb
	groupdb.reset()
	
	# shchun : remove first boot mark.
	try:
		os.system('rm -f /usr/etc/first_boot_done')
		os.system('rm -f /usr/local/lgvp/mdown.cfg') # download setting
		os.system('rm -f /usr/local/lgvp/cpeid.cfg')
		os.system('cp -f /usr/etc/snmp/snmpd.ini /usr/etc/snmp/snmpd.conf')
		os.system('cp -f /usr/etc/trapcontrol.ini /usr/etc/trapcontrol.conf')
		os.system('sync')
	except:
		pass
		
	import calldb
	calldb.delete_db('all')
	
	remove_dir(get_image_dir('wallpaper'))
	remove_dir(get_image_dir('picture'))
	#remove_dir(config.image_snapshot_dir)
	remove_dir(get_audio_dir('recorded'))
	remove_dir(get_audio_dir('poly'))
	remove_dir(get_audio_dir('other'))
	# record fils
	remove_dir(get_image_dir('taken'))
	remove_dir(config.video_recorded_dir)
	remove_dir(config.audio_dir_recorded)
	
	remove_dir(config.video_recorded_thumnail_dir)
	remove_dir(config.video_received_thumnail_dir)
	# eicho add 06.11.23 same as BT, remove amr2wav directory
	remove_dir(config.audio_amr2wav_recorded_dir)
	remove_dir(config.audio_amr2wav_polyphonic_dir)
	remove_dir(config.audio_amr2wav_other_dir)
	# for web
	#remove_dir(config.image_web_dir)
	#remove_dir(config.audio_web_dir)
	#remove_dir(config.video_web_dir)
	# down files by web
	remove_dir(config.audio_dir_download)
	remove_dir(config.image_received_dir)
	remove_dir(config.video_received_dir)
	
	## remove T9 added word
	#remove_t9_word_list()
	#remove_dir(get_email_dir('emailetc'))

	#sms/mms
	#remove_dir(config.vm_MMSC_dir)
	os.system('rm -rf /usr/local/lgvp/store')

	# for dect
	status.DECT_RESET_TEST = True
	print 'status.DECT_RESET_TEST :::: TRUE'
	runtime.dectCallManager.sendFactoryReset()
	

	if runtime.vdciapp and runtime.vdciapp.subscriber_success:
		runtime.vdciapp.req_desubscriber()
		time.sleep(1)
	
	if runtime.vdciapp and status.get_register_mode() == status.Registered:
		runtime.vdciapp.req_deregister()
		time.sleep(1)
		
	# profile reset, 리셋시 default 값이 정의되어야 함
	from profile import profile, lan_profile, wifi_profile, dns_profile, wifi_profile_general
	from vdcisetting import vdci_setting
	lan_profile.reset()
	#wifi_profile.reset()
	# shchun: wifi_profile_general 
	wifi_profile_general.reset()
	dns_profile.reset()
	vdci_setting.reset()
	profile.reset() # profile저장시 vdcisetting을 변경하므로 마지막에 수행함
	#roxia_trace('wlstop')
	#os.popen('wlstop')
	#if runtime.vdciapp:
	#	runtime.vdciapp.kill_vdciapp()
	#	runtime.vdciapp = None


	if reboot:
#MMW 2008.06.25 when reboot is called, reset vega and DCP related GPIO pin				
		vega_reset_together()
#end of MMW	
#MMW	2008.07.07	when reboot send disassoc to AP and then unload the driver
		os.system('wlstop')
#end of MMW
		os.system('reboot')
		import sys
		sys.exit()
	else:
		pass
	

#file, dir의 name을 바꿈
def rename(old_name, new_name):
	if config.utils_debug:
		print 'rename: ', old_name, new_name
	try:
		os.rename(old_name, new_name)
		return True
	except:
		return False

#file을 지움
def remove(name):
	if config.utils_debug:
		print 'remove: ', name
	try:
		os.remove(name)
		return True
	except:
		return False

def remove_cmd(name):
	try:
		cmd = 'rm %s' % name
		os.system(cmd)
	except:
		pass

#dir을 만듬
def make_dir(dir_name):
	if os.path.exists(dir_name):
		return

	dir = ''
	for c in os.path.normpath(dir_name).split('/'):
		dir += c + '/'
		if not os.path.exists(dir):
			os.mkdir(dir)

#dir_name안의 일반적인 파일들만 지움 (디렉토리를 지우는 것은 아니다)
def remove_dir(dir_name):
	if config.utils_debug:
		print 'remove dirs', dir_name
	try:
		if os.path.exists(dir_name):
			for f in os.listdir(dir_name):
				name = dir_name + f
				stat = os.stat(name)
				if stat[0] & 0100000:
					if config.utils_debug:
						print 'remove this file:', name
					try:
						os.remove(name)
					except:
						pass
	except OSError:
		pass

#전체적인 message를 지운다.
#def remove_messages(type = 'all'):#, isemail=True):
def remove_messages(type = 'all', isreset=True):
	if type == 'sms':
		from smsmanager import smsmgr
		smsmgr.remove_all()
	elif type == 'mms':
		from mmsmanager import mmsmgr
		mmsmgr.MMS_Remove_Allmsg()
	elif type == 'ipemail':
		from ipemailmanager import ipemailmgr
		ipemailmgr.remove_all()
	elif type == 'all':
		from smsmanager import smsmgr
		from mmsmanager import mmsmgr
		from ipemailmanager import ipemailmgr
		if isreset:
			smsmgr.remove_all()
			mmsmgr.MMS_Remove_Allmsg()
			ipemailmgr.remove_all()
		else:
			from profile import profile
			if profile.get_profile() == 0:
				smsmgr.remove_all()
				mmsmgr.MMS_Remove_Allmsg()
			else:
				ipemailmgr.remove_all()

	else:
		if config.utils_debug:
			print 'Unknown type [%s]' % type
		#assert False

#해당 파일 이름 name의 확장자를 얻어낸다(.은 빼고)
def get_ext(name):
	last_dot = name.rfind('.')
	return name[last_dot+1:]

#해당 디렉토리의 경로로 이미지의 타입을 얻어낸다
def image_type(name):
	if name.startswith(config.image_taken_dir) or name.startswith(config.lgvp+config.image_taken_dir):
		return 'taken'
	elif name.startswith(config.image_picture_dir) or  name.startswith(config.lgvp+config.image_picture_dir):
		return 'picture'
	elif name.startswith(config.image_wallpaper_dir) or name.startswith(config.lgvp+config.image_wallpaper_dir):
		return 'wallpaper'
	elif name.startswith(config.image_bg_dir) or name.startswith(config.lgvp+config.image_bg_dir):
		return 'vdc'
	elif name.startswith(config.image_received_dir) or name.startswith(config.lgvp+config.image_received_dir):
		return 'received'
	elif name.startswith(config.image_avatas_dir) or name.startswith(config.lgvp+config.image_avatas_dir):
		return 'avatas'

def get_email_dir(type):
	_email_paths = {'emailetc':config.ip_email_attach_etc_path}
	return _email_paths[type]

#해당 이미지 타입으로 디렉토리를 얻어낸다
def get_image_dir(type):
	_image_paths = {'taken': config.image_taken_dir,
					'picture': config.image_picture_dir,
					'wallpaper': config.image_wallpaper_dir,
					'vdc': config.image_bg_dir,
					'received': config.image_received_dir,
					'avatas': config.image_avatas_dir,
					'privacy': config.image_privacy_dir,
					'sdmmc': config.sdmmc_conv_dir,
					'usb': config.usb_dir}
	return _image_paths[type]
	
def get_image_dir_by_index(type):
	_image_paths = {1: config.image_avatas_dir,
		       2: config.image_bg_dir,
		       3: config.image_taken_dir,
		       4: config.image_received_dir}
	return _image_paths[type]



	

#해당 오디오 타입으로 디렉토리를 얻어낸다
def get_audio_dir(type):
	_audio_paths = {'ring': config.audio_def_dir,
		       'recorded': config.audio_recorded_dir,
		       'poly': config.audio_polyphonic_dir,
		       'other': config.audio_other_dir}
	return _audio_paths[type]

# KA: [20080412] ring 관련
def get_ring_dir_list():
	return [_('None'), _('Basic bell'), _('Sweet bell'), _('Merry bell'), _('Classic bell'), _('Effect bell'),  _('Download bell'), _('Recorded bell')]

def get_image_dir_list():
	import uiconfig
	return [_('None'), _('Avatas'), _('Basic Images'), _('My album'), _('Receive Images')]

# 실제 폰북에 저장된 image name값을 받은 경우 
def get_image_dir_index(value='', dir_index=None):
	if config.mmi_debug: print 'ka..............value =%s index=%s'%(value, dir_index)
	if value!= '' and not os.access(value, os.R_OK):
		if config.mmi_debug: 
			print '@@@@ file is not available'
		return 0, [_('None'), ], 0
	if dir_index in (0, 1, 2, 3, 4):
		if dir_index == 0:
			return [_('None'), ]
		elif dir_index == 1:
			path = config.image_avatas_dir
		elif dir_index == 2:
			path = config.image_bg_dir
		elif dir_index == 3:
			path = config.image_taken_dir
		elif dir_index == 4:
			path = config.image_received_dir
		list = []
		list = os.listdir(path)
		list.sort()
		return list

	if value == 'None' or value.endswith('no_photo.png'):
		value = ''
	if value:
		# full name을 주는 경우 (photos/bg/ or (photos/taken/ or photos/received)
		if value.startswith('photos') or value.startswith('/usr/local/lgvp/photos'):
			path =value.split('photos/')[1]
		# 시작 Dir만 주는 경우 (Basic Bell)
		else:
			path = value
		print path
		if path.startswith('avatas'):
			index = 1
			path = config.image_avatas_dir
		elif path.startswith('bg'):
			index = 2
			path = config.image_bg_dir
		elif path.startswith('taken'):
			index = 3
			path = config.image_taken_dir
		elif path.startswith('downloadimages') or path.startswith('received'):
			index = 4
			path = config.image_received_dir
		#print '[utils] get_ring_dir_index=', index, path
		list = []
		list = os.listdir(path)
		list.sort()

		utf8_list = []
		for i in list:
			try:
				i = unicode(i, 'euc-kr').encode('utf-8')
			except:
				pass
			utf8_list.append(i)
		# KA: [20080424] file index
		file =value.split(path)[1]
		file_index = list.index(file)
		return index, utf8_list, file_index
	else:
		return 0, [_('None'), ], 0

def camera_wb_set(wb):
	#cmd = "vc gencmd camera_control set_white_balance %d"%(wb)
	cmd = "/usr/local/bin/camera_control.sh 6 %d"%(wb)
	os.system(cmd)

def camera_brightness_set(brightness):
	#cmd = "vc gencmd camera_control set_brightness %d"%(brightness)
	cmd = "/usr/local/bin/camera_control.sh 0 %d"%(brightness)
	os.system(cmd)

def get_ring_dir(type):
	_audio_paths = {'Basic bell': config.audio_dir_basic,
		       'Sweet bell': config.audio_dir_sweet,
		       'Merry bell': config.audio_dir_merry,
		       'Classic bell': config.audio_dir_classic, 
		       'Effect bell': config.audio_dir_effect,
		       'Download bell': config.audio_dir_download}
	return _audio_paths[type]
	
def get_ring_dir_by_index(type):
	_audio_paths = {1: config.audio_dir_basic,
		       2: config.audio_dir_sweet,
		       3: config.audio_dir_merry,
		       4: config.audio_dir_classic, 
		       5: config.audio_dir_effect,
		       6: config.audio_dir_download,
		       7: config.audio_dir_recorded}
	return _audio_paths[type]


# 실제 폰북에 저장된 ring name값을 받은 경우 
def get_ring_dir_index(value):
	#value = unicode(value, 'utf-8').encode('utf-8')
	if value == 'None':
		value = ''
	if config.mmi_debug: print '## value =', value
	if value!= '' and not os.access(value, os.R_OK):
		if config.mmi_debug: 
			print '@@@@ file is not available'
		return 0, [_('None'), ], 0
	if value:
		if value.startswith('audios/audios/recorded') or value.startswith('/usr/local/lgvp/audios/audios/recorded'):
			value =value.split('audios/audios/')[1]
			index = 7
			path = config.audio_dir_recorded
		else:
			# full name을 주는 경우 (audios/ring/Basic Bell/XX.mid)
			if value.startswith('audios') or value.startswith('/usr/local/lgvp/audios'):
				value =value.split('audios/ring/')[1]
				path = value
			# 시작 Dir만 주는 경우 (Basic Bell)
			else:
				path = value
			# -----BasicBell/sting.mid
			
			if path.startswith('Basic'):
				index = 1
				path = config.audio_dir_basic
			elif path.startswith('Sweet'):
				index = 2
				path = config.audio_dir_sweet
			elif path.startswith('Merry'):
				index = 3
				path = config.audio_dir_merry
			elif path.startswith('Classic'):
				index = 4
				path = config.audio_dir_classic
			elif path.startswith('Effect'):
				index = 5
				path = config.audio_dir_effect
			elif path.startswith('download'):
				index = 6
				path = config.audio_dir_download

		#print '[utils] get_ring_dir_index=', index, path
		#print 'ka........path=', path
		list = []
		_list = os.listdir(path)

		for item in _list:
			dot = item.rfind('.')
			if dot >= 0:
				item = item[:dot]
				item = unicode(item, 'euc-kr').encode('utf-8')
			list.append(item)
		list.sort()
		
		file = value.split('/')[1]
		try:
			file = unicode(file, 'euc-kr').encode('utf-8')
			dot = file.rfind('.')
			if dot >= 0:
				file = file[:dot]
		except:
			pass
		
		#print 'ka..............file=', file
		#print 'ka..............list=', list

		try:
			file_index = list.index(file)
		except:
			file_index = 0
		
		return index, list, file_index
	else:
		return 0, [_('None'), ], 0


def get_ring_list(dir_index):
	if dir_index:
		if dir_index == 1:
			path = config.audio_dir_basic
		elif dir_index == 2:
			path = config.audio_dir_sweet
		elif dir_index == 3:
			path = config.audio_dir_merry
		elif dir_index == 4:
			path = config.audio_dir_classic
		elif dir_index == 5:
			path = config.audio_dir_effect
		elif dir_index == 6:
			path = config.audio_dir_download
		elif dir_index == 7:
			path = config.audio_dir_recorded
		#print 'ka.........path = ', path
		list = []
		list = os.listdir(path)
		list.sort()
		return list
	else:
		return [_('None'), ]


def get_melody_fullname(dir, name):
	list = os.listdir(dir)
	
	try:
		name = unicode(name, 'utf-8').encode('euc-kr')
	except:
		pass
	
	for fname in list:
		dot = fname.rfind('.')
		if dot >= 0:
			if fname[:dot] == name:
				return fname
	return None
		
def get_audio_gallery_list(type):
	dirname = audio_paths[type]
	
	return dirname, get_file_lists(dirname)

def get_image_gallery_list(type):
	dirname = get_image_dir(type)
	return dirname, get_file_lists(dirname)

def get_ext_image_gallery_list(type):
	dirname = get_image_dir(type)
	return dirname, get_ext_img_file_lists(dirname)

def get_jpg_image_gallery_list(type):
	dirname = get_image_dir(type)
	return dirname, get_ext_file_lists(dirname, '.jpg')

def get_video_dir(type):
	_video_paths = {'recorded': config.video_recorded_dir, 'received':config.video_received_dir}
	_video_thumb_paths = {'recorded': config.video_recorded_thumnail_dir, 'received':config.video_received_thumnail_dir}
	return _video_paths[type], _video_thumb_paths[type]

#해당 디렉토리의 경로로 오디오의 타입을 얻어낸다
def audio_type(name):
	if name.startswith(config.audio_def_dir):
		return 'ring'
	elif name.startswith(config.audio_recorded_dir):
		return 'recorded'
	elif name.startswith(config.audio_polyphonic_dir):
		return 'poly'
	elif name.startswith(config.audio_other_dir):
		return 'other'
	# KA: [20080125] KT ANN
	elif name.startswith(config.mp3_dir):
		return 'mp3'

#절대경로로 되어 있는 이미지 파일네임을 디렉토리와 파일명으로 분리한다
def split_image_name(name):
	itype = image_type(name)
	idir = get_image_dir(itype)
	return idir, name[len(idir):]
#Roxia Begin smyook 06.05.09
def cut_text(text, width, font, with_punc=False):
	#roxia_trace('>> cut_text orging:', text)

	if text and text != '':
		if text[0] == '\x03':
			text = text[1:]
		if text[-1:] == '\x03':
			text = text[:-1]

	new_text = ''
	t = runtime.evas.text(text=text, font=font)
	w = t.geometry[2]
	if w > width:
		while text:
			# KA: [20070921] this conversion is required for Korean text
			#text = text[:-1]
			#text = (unicode(text, 'utf-8')[:-1]).encode('utf-8')
			# shchun 2007.10.29 when interdomain call 'text' can be unicode string. this cause python exception.
			if type(text) == type('abc'):
				text = unicode(text, 'utf-8')[:-1]
			else:
				text = text[:-1]
			text = text.encode('utf-8')
			# end of shchun
			if with_punc:
				t.text = text + '...'
			else:
				t.text = text

			if t.geometry[2] <= width:
				if with_punc:
					new_text = text + '...'
				else:
					new_text = text
				break

	else:
		new_text = text
	t.free()

	return (new_text, font)

#Roxia End smyook
def get_real_lang_str(str_textid):
	return runtime.evas.pre_parse(str_textid)


def cut_text_with_punc(text, width, font):
	#List Item scroll, string의 앞이나 뒤에 붙은 0x03(^C) 문자를 제거한다
	if text and text != '':
		if text[0] == '\x03':
			text = text[1:]
		if text[-1:] == '\x03':
			text = text[:-1]

	new_text = ''
	t = runtime.evas.text(text=text, font=font)
	w = t.geometry[2]
	if w > width:
		while text:
			# KA: [20070921] this conversion is required for Korean text
			#text = text[:-1]
			#text = (unicode(text, 'utf-8')[:-1]).encode('utf-8')
			if type(text) == type('abc'):
				text = unicode(text, 'utf-8')[:-1]
			else:
				text = text[:-1]
			text = text.encode('utf-8')

			t.text = text + '...'
			if t.geometry[2] <= width:
				new_text = text + '...'
				break
	else:
		new_text = text
	t.free()

	return (new_text, font)


#text를 그려주는 사각 영역의 크기에 따라 fontsize를 조정해 주거나 길면 ...으로 표시해 준다
def resize_text(text, width, font, nocut = False):
	if text.startswith('\x03') or nocut == True:
		#번역이 될 문장이다. 뒷부분을 자르는 경우 문제가 됨.
		t = runtime.evas.text(text=text, font=font)
		name, fontsize = font
		while t.geometry[2] > width:
			fontsize -= 1
			t.font = name, fontsize
			# RHC / [20061012_1]
			if fontsize == 1:
				break
			# RHC / [20061012_1]--
		t.free()
		return text, (name, fontsize)
	new_text = ''
	t = runtime.evas.text(text=text, font=font)
	w = t.geometry[2]
	if w > width:
		while text:
			# KA: [20070905] hangul lvp-2000 한글 긴문자열 조정시 '...' 이 표시 안되는 문제 해결
			#text = (unicode(text, 'utf-8')[:-1]).encode('utf-8')
			if type(text) == type('abc'):
				text = unicode(text, 'utf-8')[:-1]
			else:
				text = text[:-1]
			text = text.encode('utf-8')
			
			t.text = text + '...'
			if t.geometry[2] <= width:
				new_text = text + '...'
				break
	else:
		new_text = text
	t.free()
	return (new_text, font)

def baloon_resize_text2(text, width, font):
	t = runtime.evas.text(text=text, font=font)
	name, fontsize = font
	if t.horiz_advance_get() > width:
		fontsize -= 1
		t.font = name, fontsize
		if t.horiz_advance_get() > width:
			n = 0
			text1 = text
			while text1:
				n -= 1
				text1 = (unicode(text, 'utf-8')[:n]).encode('utf-8')
				text2 = (unicode(text, 'utf-8')[n:]).encode('utf-8')
				t.text = text1
				if t.horiz_advance_get() <= width:
					t.free()
					return text1, text2, (name, fontsize)
		else:
			t.free()
			return text, None, (name, fontsize)
	t.free()
	return text, None, font

def baloon_resize_text(text, width, font):
	t = runtime.evas.text(text=text, font=font)
	name, fontsize = font
	if t.horiz_advance_get() > width:
		fontsize -= 1
		t.font = name, fontsize
		if t.horiz_advance_get() > width:
			n = 0
			text1 = text
			while text1:
				n -= 1
				text1 = ''
				text2 = ''
				for tt in text.split(' ')[:n]:
					text1 += tt + ' '
				# text1 = (unicode(text1, 'utf-8')[:-1]).encode('utf-8')
				text1 = text1[:-1]
				for tt in text.split(' ')[n:]:
					text2 += tt + ' '
				# text2 = (unicode(text2, 'utf-8')[:-1]).encode('utf-8')	
				text2 = text2[:-1]
				t.text = text1
				if t.horiz_advance_get() <= width:
					t.free()
					return text1, text2, (name, fontsize)
		else:
			t.free()
			return text, None, (name, fontsize)
	t.free()
	return text, None, font

#해당 파일 사이즈를 Kb단위로 환산한다
def get_size_kb(filename):
	try:
		return (os.stat(filename)[6] + 1023)/1024
	except:
		return 0

#최소한의 메모리 사이즈인 4500보다 많은 메모리를 가지고 있는지 조사한다
def check_free_storage(mode = '', filesize = 0):
#Roxia Begin smyook 06.02.13
	if mode == 'filetosdmmc2':
#Roxia End smyook
		result = os.statvfs('/usr/mmchd')
	else:
		result = os.statvfs('/usr')
	# result[0] : block size
	# result[3] : blocks
	free_size = (result[0] * result[3]) / 1024
	if mode != '':
		if free_size - filesize > config.min_free_storage:
			return True
		else:
			return False
	if config.utils_debug:
		print 'mtd4, free size:', free_size
	if free_size > config.min_free_storage:
		return True
	else:
		return False

#비디오 콜 관련 ?
def check_videocall():
	# 0310 - TIM Mobile phone 과의 연동
	status.check_mobile_call = False

	if setting.enable_video_key != 1 or not status.dial_number:
		return False

	dial = status.dial_number
	if setting.phone_extension:
		if dial.startswith(setting.phone_extension):
			dial = dial[len(setting.phone_extension):]
			if dial[0] == 'P':
				dial = dial[1:]
	if dial.startswith(config.FAC_HIDE_ID_CODE):
		dial = dial[3:]

	status.ppp_call_number = config.sac1 #KEON-0414
	return True

def check_special_nas_number(number):
	if number == config.special_cid_number:
		return True
	return False	#Presently, foramt of special NAS number doesn't become known yet.

def get_special_nas_number(number):
	return config.sac2	#Presently, foramt of special NAS number doesn't become known yet.


#sms data를 read시 사용
class Parser:
	def __init__(self, data):
		self.parse_pos = 0
		self.raw_data = data

	def get_byte(self):
		b = ord(self.raw_data[self.parse_pos])
		self.parse_pos += 1
		return b

	def get_short(self):
		return self.get_byte() * 256 + self.get_byte()

	def get_data(self, size):
		data = self.raw_data[self.parse_pos:self.parse_pos+size]
		self.parse_pos += size
		return data
	def get_remaining(self):
		return self.raw_data[self.parse_pos:]

	def parsing_done(self):
		return self.parse_pos >= len(self.raw_data)

#sms를 통해서 받은 이미지 또는 사운드의 갯수를 얻는다
def next_file_index(path, prefix, suffix):
	count = 0
	while True:
		candi = path + prefix + '%d' % count + suffix
		if not os.path.exists(candi):
			break

		count += 1

	return count

def is_dtmf(key):
	if len(key) == 2 and key[0] == 'D':
		return True
	return False

#파일을 삭제한다
def remove_file(f):
	os.unlink(f)

#t9_word_list를 지원다
def remove_t9_word_list():
	if not os.access(config.t9_word_list, os.R_OK):	#t9_word_list를 읽을 수 있는 권한을 가지고 있는가
		return
	remove_file(config.t9_word_list)

#해당 파일의 최근 수정된 시간을 알려준다
def get_file_mtime(filename):
	return os.stat(filename)[8]

def print_hex(data):
	if not data:
		print 'empty data'
		return
	for i, c in enumerate(data):
		print "[%02X]" % (ord(c),),
		if i%16 == 15:
			print
	print

def log_time(mesg,init=False):
	if profile.ip_mode != 0:	# not PSTN
		return
	try:
		if init:
			os.unlink( '/tmp/vdc_time' )
	except:
		pass
	timestamp = ntptime.ntime()
	hour, min, sec = time.localtime(timestamp)[3:6]
	msec = str(timestamp)
	if setting.lang == 'Italian':
		msec = msec[msec.find(',')+1:]
	else:
		msec = msec[msec.find('.')+1:]
	date = "%02d:%02d:%02d.%s" % (hour, min, sec, msec)
	mesg = date+" "+mesg+'\n'
# answer delay
	try:
		fd = open( "/tmp/vdc_time", "a", 0 )
		fd.write( mesg )
	except:
		pass
	fd.close()

#automata_list중에 숫자가 아닌 인자로 들어온 값을 가지고 있는 index를 찾는다
def get_automata_idx(name, casemode=None):
	# KA: [20070831] hangul lvp-2000
	# vpark 2006.08.28 automata	
	if name == None:	
		return get_def_automata_idx()
	# KA: [20070831] hangul lvp-2000 ==
#ka...hangul Add 2007.01.25
	if setting.lang == 'Korean':
		for i, a in enumerate(config.automata_list_hangul):
			n,c = a
			if n == name and (not c or c == casemode):
				return i
	else:
		for i, a in enumerate(config.automata_list):
			n,c = a
			if n == name and (not c or c == casemode):
				return i
	#assert False
def get_automata_idx_no_hangul(name, casemode):
	if name == None:	
		return get_def_automata_idx()

	for i, a in enumerate(config.automata_list_mult_num_symbol):
		n,c = a
		if n == name and (not c or c == casemode):
			return i
#('t9', 'lower'), ('t9', 'first capital'), ('t9', 'upper'),
#('multitap', 'lower'), ('multitap', 'first capital'), ('multitap', 'upper'),
#('123', 0)
def get_def_automata_idx():	#('t9', 'first capital'), ('t9', 'upper'),('multitap', 'first capital'), ('multitap', 'upper')중에 edit write mode 시작시 입력방식
	return (0,1,2,3,4,5)[setting.writing_mode]
	
def get_def_automata_no_hangul():		#현 입력 방식에 대한 값을 리턴한다
	automata_idx = get_def_automata_idx()
	name,casemode = config.automata_list_mult_num_symbol[automata_idx]

	return name, casemode

def get_def_automata():		#현 입력 방식에 대한 값을 리턴한다
	automata_idx = get_def_automata_idx()
#ka...hangul Add 2007.01.25
#	if setting.lang == 'Korean':
	name,casemode = config.automata_list_hangul[automata_idx]
#	else:
#		name,casemode = config.automata_list[automata_idx]
	return name, casemode

class InterruptException(Exception):
	pass

def check_interrupt():
	while 1:
		key = runtime.evas.get_key()
		if not key:
			return
		if config.utils_debug:
			print "**********check interrupt key", key
		if key in (config.OffHook, config.Green):
			if config.utils_debug:
				print 'Raising interrupt', key
			status.interrupt_key = key
			raise InterruptException, key

#sms 수신 이미지에 대한 임시path+filename을 얻는다
last_temp_sbm = 0
def get_last_temp_sbm_filename():
	global last_temp_sbm
	filename = '/tmp/%08d.sbm' % last_temp_sbm
	last_temp_sbm += 1
	return filename

#sms 수신 사운드에 대한 임시path+filename을 얻는다
last_temp_imy = 0
def get_last_temp_imy_filename():
	global last_temp_imy
	filename = '/tmp/%08d.imy' % last_temp_imy
	last_temp_imy += 1
	return filename

#image를 가로 88 세로 72의 사이즈로 변화시킴
#크기가 88, 72보다 작거나 같으면 변화되지 않음
def image_resize(old, new):
	os.system('image-resize ' + old + ' ' + new + ' 88 72')

#file copy
def file_copy(src_file, dest_file):
	cmd = 'cp "%s" "%s"' % (src_file, dest_file)
	os.system(cmd)

# LG hw 디버깅 정보 요청사항
def print_hw_debug(message):
	# eicho change file name 'testmode' to 'testmode1'
	"""
	if not os.access('/usr/etc/testmode1', os.R_OK):

		return
	print message
	"""
	if is_test_mode():
		print message


# cid 와 함께 받은 date, time 을 받아서 call_time 을 만들어준다.
def make_call_time():
	recv_date = status.received_date
	recv_time = status.received_time
	date = time.localtime(ntptime.ntime())
	year, mon, day = date[0], date[1], date[2]
	hour, min, sec = date[3], date[4], date[5]
	if recv_date:
		mon = int(recv_date[:2])
		day = int(recv_date[2:])
	if recv_time:
		hour = int(recv_time[:2])
		min = int(recv_time[2:])
		sec = 0
	call_time = time.mktime((year, mon, day, hour, min, sec, 0, 0, 0))
	status.received_date = None
	status.received_time = None
	return call_time

#폰 재 부팅
def restart_lgvp():
	os._exit(1)

#adapter (문자열): ex)'eth', 'ppp' -> 뒤의 숫자는 붙이지 않는다
#return; adapter에 해당하는 ip와 mac address들을 리턴한다
#           ex)    [['00:00:00:00:00:00', 111,111,111,111], ['22:22:22:22:22:22', 333,333,333,333].......]
#							eth0									eth1
#				mac address			IP				mac address			IP
def get_address(adapter):
	bundle = [[]]
	ret = []

	index = -1
	try:
		os.system('ifconfig -a > /tmp/ifconfig.tmp')
		fp = open('/tmp/ifconfig.tmp')
		for data in fp:
			data = data.strip()
			if data:
				if index == -1:
					index = 0
				data = data.split()
				bundle[index].extend(data)
			else:
				if index != -1:
					bundle.append([])
					index += 1

		if not len(bundle[-1]):
			bundle.pop(-1)

		for data in bundle:
			if data[0][:-1] == adapter or data[0] == adapter:
				ret.append([])
				try:
					nfind = data.index('HWaddr')
					ret[len(ret)-1].append(data[nfind+1])
				except ValueError:
					ret[len(ret)-1].append(None)

				try:
					nfind = data.index('inet')
					ret[len(ret)-1].append((data[nfind+1].split(':'))[1])
				except ValueError:
					ret[len(ret)-1].append(None)

		return ret
	except:
		#print 'ioerror'
		pass



def show_softkey(show=True):
	if show:
		runtime.evas.soft.show()
		runtime.lb.show()
		runtime.rb.show()
		runtime.menu3.show()
		runtime.menu4.show()
	else:
		runtime.evas.soft.hide()
		runtime.lb.hide()
		runtime.rb.hide()
		runtime.menu3.hide()
		runtime.menu4.hide()

def image_isvalid(filename):
	if filename == '':
		return 0
		
	return runtime.mmedia.check_image_isvalid(filename)
	
def get_img_size(imageFile):
	if imageFile.lower().endswith('.jpg') or imageFile.lower().endswith('.jpeg'):
		tmp_image = runtime.evas.image(file=imageFile)
		tmp_w, tmp_h = tmp_image.size_get()
		tmp_image.free()
	elif imageFile.lower().endswith('.png'):
		tmp_image = runtime.evas.image(file=imageFile)
		tmp_w, tmp_h = tmp_image.size_get()
		tmp_image.free()
		'''
		dim = [ord(x) for x in open(imageFile).read(24)[16:]]
		tmp_w = dim[3] + 256 * (dim[2] + 256 * (dim[1] + 256 * dim[0]))
		tmp_h = dim[7] + 256 * (dim[6] + 256 * (dim[5] + 256 * dim[4]))
		'''
	elif imageFile.lower().endswith('.gif'):
		dim = [ord(x) for x in open(imageFile).read(24)]
		tmp_w = dim[6] + 256 * dim[7]
		tmp_h = dim[8] + 256 * dim[9]
	elif imageFile.lower().endswith('.bmp'):
		dim = [ord(x) for x in open(imageFile).read(26)]
		if dim[14] == 12: #dim[14] = 12 (Old BMP image file format, Used OS/2)
			tmp_w = dim[18] + 256 * dim[19]
			tmp_h = dim[20] + 256 * dim[21]
		else: #dim[14] > 12 (Microsoft Windows BMP image file)
			tmp_w = dim[18] + 256 * dim[19]
			tmp_h = dim[22] + 256 * dim[23]
	else:
		tmp_w = 320
		tmp_h = 240
	return [tmp_w, tmp_h]

def is_test_mode():
	if os.path.exists('/usr/etc/testmode1') or os.path.exists('/usr/etc/testmode2'):
		return True
	else:
		return False



#MMW	//2006.02.06
#		time.localtime(ntptime.ntime())
def file_time_adaptation(filename):

#	print filename

	atime = os.stat(filename)[stat.ST_ATIME]
	mtime = os.stat(filename)[stat.ST_MTIME]
#	print 'atime', atime

	atime = atime +  ntptime.timediff()
	mtime = mtime + ntptime.timediff()
#	print 'atime+', atime
#	print 'mtime+', mtime

	os.utime(filename, (atime, mtime))
	time.sleep(0.10)
	atime = os.stat(filename)[stat.ST_ATIME]
	mtime = os.stat(filename)[stat.ST_MTIME]
#	print 'atime++', atime
#	print 'mtime++', mtime

#end of MMW

# KA: [20070809] hangul
#start hyshim 2006.11.29 : euc-kr -> unicode
def f_unicode_encoding(message):
	result = ''
#	if setting.lang == 'Korean':
#		result = unicode(message,'euc-kr')
#	else:
#		result = message
	result = unicode(message,'euc-kr')
	return result
#end
#start hyshim 2007.01.09 : utf-8 -> euc-kr
def f_utf8tokr_encoding(message):
	resurlt = ''

	result = unicode(message,'utf-8').encoding('euc-kr')
	return result
#end


# KA: [20080310] private IP
def check_private_range():
	from profile import profile
	if profile.get_profile() == 1:
		network_info = get_address('eth')
	else:
		network_info = get_address('wlan')

	if network_info:
		
		ip = network_info[0][1]
	else:
		return False
		
	if not ip:
		return False

	hex_ip = ''.join(["%02X" % int(i) for i in ip.split('.')])
	hex_ip = int(hex_ip, 16)

	if (hex_ip >= 0xA000000 and hex_ip <= 0xAFFFFFF ) or \
		(hex_ip >= 0xAC100000 and hex_ip <= 0xAC1FFFFF) or \
		(hex_ip >= 0xC0A80000 and hex_ip <= 0xC0A8FFFF):
		return True
	else:
		return False
	#A클래스 	10.0.0.0~10.255.255.255
	#B클래스 	172.16.0.0~172.31.255.255
	#C클래스 	192.168.0.0~192.168.255.255
# KA: [20080310] private IP ==

def checkUrlPolicy(number):
	#if setting.urlPolicy == config.LOCAL_TEST_URI:
	#	return [config.LOCAL_URI, number]
	if config.local_test_flag:
		return [config.LOCAL_TEST_URI, number]
	elif setting.urlPolicy == config.KT_TEL_URI:
		return [config.KT_URI, number]
	elif setting.urlPolicy == config.STANDARD_SIP_URI:		
		if number[0] == '+':
			return [config.STANDARD_GLOBAL, number[1:]]
		elif number[:2] == '00':
			return [config.STANDARD_LOCAL, number]
		elif number[0] == '0':
			number = setting.nationalCode + number[1:]
			return [config.STANDARD_GLOBAL, number]
		elif number[0] == '1' or number[0] == '*' or number[0] == '#':
			return [config.STANDARD_LOCAL, number]
		else:
			number = setting.nationalCode + setting.prefix[1:] + number
			return [config.STANDARD_GLOBAL, number]
	else:
		return [config.KT_URI, number]

def getGifAnimationInfo():
	myCardGifInfoList = []
	frameFileList = []
	firstDelay = True
	
	infoFileHandler = open('/usr/local/lgvp/images/myCard/myCard.info')
	for line in infoFileHandler:
		tokenList = line.split(' ')
		print 'tokenList = ', tokenList
		if '*' in tokenList:
			gifFileName = tokenList[1]
			myCardGifInfoList.append(gifFileName)
			numberOfFrame = tokenList[2]
			myCardGifInfoList.append(numberOfFrame)
		elif 'delay' in tokenList:
			if firstDelay:
				#delayTime = int(float(tokenList[tokenList.index('delay')+1][:-2])*1000)
				delayTimeString = tokenList[tokenList.index('delay')+1][:-2]
				delayTimeList = delayTimeString.split('.')
				delayTime = int(delayTimeList[0])*1000 + int(delayTimeList[1][0])*100 + int(delayTimeList[1][1])*10
				myCardGifInfoList.append(delayTime)
				firstDelay = False

	for index in range(int(numberOfFrame)):
		if index < 10:
			framFileName = './myCard/' + gifFileName + '.00' + str(index)
		elif index >= 10:
			framFileName = './myCard/' + gifFileName + '.0' + str(index)
		frameFileList.append(framFileName)

	myCardGifInfoList.append(frameFileList)
	
	return myCardGifInfoList

# release dynamic ip....
def releaseDhcp():
	from profile import profile
	cmd = ''
	if profile.get_profile() == 1:
		cmd = 'stop_dhclient eth0 &' 
	else:
		cmd = 'stop_dhclient wlan0 &'

	os.system(cmd)

def get_free_flash_memory():
	df=os.popen('df -k | grep /dev/stl0/6').readlines()
	mem_info = df[0].split()
	return int(mem_info[3])

# Function: conv_telnum(number)
# Regular expression for telephone style number format
#  ^0(?:01|02|03|04|05|06|07|08|09|10|11|12|14|15|16|17|18|19)-(?:d{3}|d{4})-d{4}$
#  ^0(?:2|31|32|33|34|41|42|43|51|52|53|54|55|61|62|63|64|70|60|80|505)-(?:d{3}|d{4})-d{4}$

def conv_telnum(number):
	if not number:
		return ''
		
	#import re

	num = number
	sym = ''
	tel1 = ''
	tel2 = ''
	tel = ''

	while num[0] in ('*', '#', '+'):		# check symbol (delete symbol)
		sym = sym + num[:1]
		num = num[1:]
		#if num == '': return ''
		if num == '': break

	### Make tel1 ###
	''' ======================================================
	# check international/mobile number ('00?' or '11?' except '000' and '013')
	exp = re.compile(r"^0(?:01|02|03|04|05|06|07|08|09|10|11|12|14|15|16|17|18|19)")
		
	tel = exp.search(num)
	if tel == None:					# have no international/mobile number
		# check local number
		exp = re.compile(r"^0(?:2|31|32|33|34|41|42|43|51|52|53|54|55|61|62|63|64|70|60|80|505)")

		tel = exp.search(num)
		if tel == None:				# have no local number
			pass
		else:
			tel1 = tel.group()			# make local number
			num = exp.split(num)[1]		# make rest number
	else:
		tel1 = tel.group()				# make international/mobile number
		num = exp.split(num)[1]		# make rest number
	''' 
	# this routine is another version without regular expression, more efficient?
	length = len(num)
	if length >= 2:
		if num[:2] == '02':
			tel1 = num[:2]
			num = num[2:]
	if length >= 3:
		if num[:3] in (
			'001', '002', '003', '004', '005', '006', '007', '008', '009',
			'010', '011', '012', '014', '015', '016', '017', '018', '019',
			'031', '032', '033', '034', '041', '042', '043', '051', '052',
			'053', '054', '055', '061', '062', '063', '064', '070', '080'):
			tel1 = num[:3]
			num = num[3:]
	if length >= 4:
		if num[:4] == '0505':
			tel1 = num[:4]
			num = num[4:]
	''' ======================================================
	'''

	### Make tel2 ###
	if len(num) < 4:			tel2 = num					# 000
	elif num[3] in ('*', '#', '+'):	tel2 = num					# special case like *123*
	elif len(num) < 8:			tel2 = num[:3] + '-' + num[3:]	# 000-0000
	else:					tel2 = num[:4] + '-' + num[4:]	# 0000-0000

	### Make tel1+tel2 ###
	if tel1 == '':	tel = tel2
	elif tel2 == '':	tel = tel1
	else:		tel = tel1 + '-' + tel2

	if sym != '':	tel = sym + tel		# check symbol (add symbol)

	return tel
''' 
# This is for conv_telnum test
if __name__ == '__main__':
	tel_list = [ '0', '02', '021', '070', '07012', '0134567890', '001823112345678',
		'070123', '0701234', '070123456', '0701234567', '07012345678', '070123456789',
		'*07', '*070', '*0701', '*0701234', '*0701234567890',
		'#07', '#070', '#0701', '#0701234', '+0701234567890',
		'*123#', '*137*', '*12356#', '*13766*',
		]

	for i in range(len(tel_list)):
		if len(tel_list[i]) < 8:
			print tel_list[i] + '\t\t -> ' + conv_telnum(tel_list[i])
		else:
			print tel_list[i] + '\t -> ' + conv_telnum(tel_list[i])

	print conv_telnum('0134567890')			# 0134-567890 (000 and 013 is not international/mobile)
	print conv_telnum('001823112345678')	# 001-8231-12345678 (country code is not implemented)
'''

def check_emergency(number):
	if not number:
		return False

	num = number

	length = len(num)
	if length == 3:
		if num[0] == '1': return True
	elif length == 5:
		if num[:2] == '02' and num[2] == '1': return True
	elif length == 6:
		if num[:3] in (
			'001', '002', '003', '004', '005', '006', '007', '008', '009',
			'010', '011', '012', '014', '015', '016', '017', '018', '019',
			'031', '032', '033', '034', '041', '042', '043', '051', '052',
			'053', '054', '055', '061', '062', '063', '064', '070', '080') and num[3] == '1': return True

	return False
'''
# This is for check_emergency test
if __name__ == '__main__':
	tel_list = [ '', '0', '02', '02100', '021000', '0210000', '02100000', '070100', '013100',
		'03119', '031199', '0311999', '03119999', '031199999' ]

	for i in range(len(tel_list)):
		if check_emergency(tel_list[i]):
			print tel_list[i] + ' is emergency call <------------------'
		else:
			print tel_list[i] + ' is not emergency call'
'''


#MMW	2008.0622	network error message to dect
def send_VP_net_status_to_DCT(status):
	#D101
	import dectHandler
	from dectConfig import MessageCode
	from dectHandler import DectCallManager

	debugLogN('\tSET_DECT_MSG: %s'%status)
	
	if runtime.dectHandler == None:
		runtime.dectHandler = dectHandler.DectHandler()
	if runtime.dectCallManager == None:
		runtime.dectCallManager = dectHandler.DectCallManager(1)

#	dectStatus = runtime.dectCallManager.getDectStatus()
#	if dectStatus == DectCallManager.CONNECTED:
#		runtime.dectCallManager.serverStopCall()
#	print 'send VP net status to DCT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
	if runtime.dectCallManager.isSubcribedDect():	
		time.sleep(0.5)
		runtime.dectCallManager.unregisterstatusReport()
		if status == 'D101' :	# 709 WATING_FOR_READY_STATUS
#			print 'D101'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WATING_FOR_READY_STATUS)
		elif status == 'M101' :	# 701 LAN_CABLE_NOT_CONNECTED
#			print 'M101'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.LAN_CABLE_NOT_CONNECTED)
		elif status == 'M102' :	# 706 PPPOE_IP_ALLOC_AND_TEST
#			print 'M102'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.PPPOE_IP_ALLOC_AND_TEST)
		elif status == 'M201' :	# 702 NAS_CONNECTION_FAIL
#			print 'M201'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.NAS_CONNECTION_FAIL)
		elif status == 'M202' :	# 703 PPPOE_ID_AUTH_FAIL
#			print 'M202'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.PPPOE_ID_AUTH_FAIL)
		elif status == 'M301' :	# 705 DHCP_IP_ALLOC_FAIL		-> same with W104
#			print 'M301'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.DHCP_IP_ALLOC_FAIL)
		elif status == 'M302' :	# 707 IP_TEST_FAIL
#			print 'M302'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.IP_TEST_FAIL)
		elif status == 'M901' :	# 704 ETC_NETWORK_ERROR
#			print 'M901'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.ETC_NETWORK_ERROR)
		elif status == 'W100' :	# 714 WIRELESS_CONNECTING
#			print 'W100'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_CONNECTING)
		elif status == 'W101' :	# 711 WIRELESS_ASSOC_FAIL
#			print 'W101'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_ASSOC_FAIL)
		elif status == 'W102' :	# 712 WIRELESS_SEC_FAIL
#			print 'W102'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_SEC_FAIL)
		elif status == 'W104' :	# 705 DHCP_IP_ALLOC_FAIL		
#			print 'W104'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.DHCP_IP_ALLOC_FAIL)
		elif status == 'W105' :	# 707 IP_TEST_FAIL
#			print 'W105'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.IP_TEST_FAIL)
		elif status == 'W106' :	# 710 WIRELESS_ICMP_FAIL
#			print 'W106'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_ICMP_FAIL)
		elif status == 'W107' :	# 710 WIRELESS_ICMP_FAIL
#			print 'W107'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_ICMP_FAIL)
		elif status == 'W109' :	# 713 WIRELESS_DISCONNECTED
#			print 'W109'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_DISCONNECTED)
		elif status == 'W110' :	# DCT message not available so, send regstatus = 3 -> 0801 KT want to change to 714 WIRELESS_CONNECTING
#			print 'W110!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
			runtime.dectCallManager.sendNetworkStatusReportToDect(MessageCode.LGN_Define.WIRELESS_CONNECTING)
		else :
			print status
		time.sleep(0.5)


	if runtime.manager != None :
		# registration fail
		runtime.manager.set_registerinfo('1')	
def vega_reset_together() :
	print 'reboot is called so, reset vega and broadcom_idle and broadcom_sip_reg pin to default!!!!!!'
	try :
		# registration fail
		os.system('dect_stop')
		runtime.manager.set_registerinfo('1')	
		# broadcom is not ready
		runtime.manager.set_bootinfo('1')
#		time.sleep(1)		
		#vega reset
		os.system('dect_vega_reset')
	except : 
		print 'vega_reset_together fail'
				
#end of MMW	

def check_ipconflict(ipaddr):
	# shchun: from ip1535...
	try:
		import profile
		cur_prof = profile.profile.get_profile()
		cmd = ''

		
		if cur_prof == 1: # Lan profile
			#cmd = 'arping -D -c 1 -I %s %s 2> /dev/null | grep Received | cut -b10 > /tmp/arping.info'%('eth0', self.ipconflict_getcurip('eth0'))
			cmd = 'arping -D -c 1 -I %s %s 2> /dev/null | grep Received | cut -b10 > /tmp/arping.info'%(runtime.manager.get_eth0name(),ipaddr)

		elif cur_prof == 2: # Wifi profile
			cmd = 'arping -D -c 1 -I %s %s 2> /dev/null | grep Received | cut -b10 > /tmp/arping.info'%('wlan0', ipaddr)
		print 'CMD', cmd
		os.system(cmd)
		res = open('/tmp/arping.info').read()

		ival = int(res)
		if ival == 0:
			# Not conflicted
			return False
		else:
			# Confilcted
			return True
	except:
		print 'EXCEPT : check_ipconflict()'
		return False
		
# input decimal and returns list of binary
def dectobin(dec): 
	# shchun: from ip1535...
	bin = [] 
	while dec >= 1: 
		dec, remainder = divmod(dec, 2) 
		bin.insert(0,remainder) 
	while len(bin) < 8:
		bin.insert(0,0)
	return bin
	
# validate inmask is good netmask.
def isValidNetmask(inmask):
	# shchun: from ip1535...
	masks= inmask.split('.')
	if len(masks) != 4:
		return False

	binlist=[]
	for item in masks:
		ival = int(item)
		if ival<0 or ival>255:
			return False
		binlist += dectobin(ival)
	
	chg = 0
	prev = 1
	for i in range(len(binlist)):
		if prev != binlist[i]:
			chg+= 1
		prev=binlist[i]
	#print 'BINLIST', chg,  binlist
	
	if chg <= 1:
		return True
	return False

def isPrivateIP(ip):
	# shchun : from KA's code
	hex_ip = ''.join(["%02X" % int(i) for i in ip.split('.')])
	hex_ip = int(hex_ip, 16)

	if (hex_ip >= 0xA000000 and hex_ip <= 0xAFFFFFF ) or \
		(hex_ip >= 0xAC100000 and hex_ip <= 0xAC1FFFFF) or \
		(hex_ip >= 0xC0A80000 and hex_ip <= 0xC0A8FFFF):
		return True
	else:
		return False
	#A클래스 	10.0.0.0~10.255.255.255
	#B클래스 	172.16.0.0~172.31.255.255
	#C클래스 	192.168.0.0~192.168.255.255

def getHexIP(ip):
        hex_ip = ''.join(["%02X" % int(i) for i in ip.split('.')])
        hex_ip = int(hex_ip, 16)

        return hex_ip
        
def isGatewayInSubnet(ip, gw, mask):
	# shchun : to check if the gateway exists in same subnet
	hex_ip = getHexIP(ip)
	hex_gw = getHexIP(gw)
	hex_mask = getHexIP(mask)

	print "ip+mask: %X"%(hex_ip & hex_mask)
	print "gw+mask: %X"%(hex_gw & hex_mask)

	if (hex_ip & hex_mask) != (hex_gw & hex_mask):
		return False
	return True

def isIPaddrEqBroadcast(ipad, netma):


	
	iplist = ipad.split('.')
	netlist = netma.split('.')

	brdlist = []
	brdcast = ''
	try:
		for z in range(len(iplist)):
			brdlist.append(int(iplist[z]) | (~int(netlist[z]) + 256))

		for z in range(len(brdlist) - 1):
			brdcast += str(brdlist[z]) + '.'
		else:
			brdcast += str(brdlist[len(brdlist)- 1])
	except:
		pass

		debugLogC( 'isIPaddrEqBroadcast: IP/Netmask/Broadcast:', ipad, netma, brdcast)
	if ipad == brdcast:
		return True

	return False