Пример #1
0
 def draw(self, context):
   if not self.data: 
     return
   size = self.allocation
   surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, size.width, size.height)
   data_dic = {'current': self.data}
   CairoPlot.dot_line_plot(surface, data_dic, size.width, size.height-10, h_labels = self.y_axis, axis = True, grid = True)
   context.set_source_surface(surface, 0, 0)
   context.paint()
Пример #2
0
def graph(filename, data, h_labels):
    data = {"objects in memory": data}
    h_labels = h_labels
    CairoPlot.dot_line_plot(filename,
                            data,
                            800,
                            300,
                            border=20,
                            h_labels=h_labels,
                            axis=True,
                            grid=True,
                            dots=True)
Пример #3
0
    def plotProductSeverityDistribution(self, dist, product):
        severity_list = ['enhancement', 'trivial', 'minor', 'normal',
                         'major', 'critical', 'blocker']
        values_list = []

        for severity in severity_list:
            values_list.append(dist[severity])

        maxbugs = "%d bugs" % max(values_list)
        vlabels = ['zarro boogs', maxbugs]

        CairoPlot.bar_plot(str(product), values_list, 500, 400,
                           border=20, grid=True,
                           h_labels=severity_list, v_labels=vlabels)
Пример #4
0
def main() :
    #h_pixals = 1600
    h_pixals = 1360
    # 500 horizontal pixals: 120 for names, 380 for bars.
    #     380 gives 10 nice bars..  I need 16 bars, so 60/bar = 960
    #     120 for names of 7 chars.  I have at least 38 chars. assume 42.
    #          120 * 6 = 720
    #     960 + 640 = 1600 horizontal pixals.
    h_legend = []
    allstarts = []
    allends = []
    colors = []
    tasknames = []
    pieces = []
    bars = {}
    starttimes = {}
    bar_color = (1.0, 0.7, 0.0)

    f = parse_commandline()

    for inputline in f :
        for line in csv.reader([inputline], escapechar='\\'):
            name = "__".join(line[0:3])
            start = int(line[3])
            end = int(line[4])
            #if time.gmtime(end)[3:5] == (6,13) :
            #    print name
            bars.setdefault(name, []).append((start,end))
            allstarts.append(start)
            allends.append(end)
            starttimes.setdefault(start, []).append(name)

    first = min(allstarts)
    last = max(allends)
    v_tickmarks = calc_vticks(first, last)
    v_pixals = (len(bars.keys()) + 1) * 70
    # 350 vertical pixals.  70 for each task + 70 for headers.
    # v_tickmarks = scale_vlines(first, last)
    for start in sorted(starttimes.keys()) :
        for name in starttimes[start] :
            # one task name.
            tasknames.append(name)
            # need 1 color per name
            colors.append(bar_color)
            times = bars[name]
            #print 'debug', name
            pieces.append(scaled_times(times, first))

    CairoPlot.gantt_chart('visual_schedule', pieces, h_pixals, v_pixals, 
                          tasknames, v_tickmarks, colors)
Пример #5
0
def main():
     data = {"john" : [50, 20, 0, 10, 30], "mary" : [0, 10, 30, 50, 100], "philip" : [20, 30, 40, 20, 10]}
     h_labels = ["jan/2008", "feb/2008", "mar/2008", "apr/2008", "may/2008"]
     v_labels = ["jan/2008", "feb/2008", "mar/2008", "apr/2008", "may/2008"]
     CairoPlot.dot_line_plot('dotline1', data, 250, 150, axis = True, grid = True)
     CairoPlot.dot_line_plot('dotline1_dots', data, 400, 300, h_labels = h_labels, v_labels = v_labels, axis = True, grid = True, dots = True)

     data2 = {"cpu":[32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
                     37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
                     55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 100],
              "mem":[55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32, 62, 60, 55,
                     32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
                     37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 100]}
     h_labs = ["0:00", "3:00", "6:00", "9:00", "12:00", "15:00", "18:00", "21:00"]
     v_labs = ["","25%","50%","75%"]
     CairoPlot.dot_line_plot('dl1', data, 600, 500, axis = True, grid = True, dots = True)
     CairoPlot.dot_line_plot('dl1_dots',
                             data2,
                             1000,
                             500,
                             background = (204,204,204),
                             border = 0,
                             axis = True,
                             grid = True,
                             dots = True,
                             h_labels = h_labs,
                             v_labels = v_labs)
Пример #6
0
 def draw(self, context):
     if not self.data:
         return
     size = self.allocation
     surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size.width,
                                  size.height)
     data_dic = {'current': self.data}
     CairoPlot.dot_line_plot(surface,
                             data_dic,
                             size.width,
                             size.height - 10,
                             h_labels=self.y_axis,
                             axis=True,
                             grid=True)
     context.set_source_surface(surface, 0, 0)
     context.paint()
Пример #7
0
    def __generate_charts(self, results):

        for test, test_data in results.items():
            mem_data = list()
            time_data = list()

            h_labels = list()

            for key, value in test_data.items():
                # print key, value
                time_data.append(value[0])
                mem_data.append(value[1])
                h_labels.append(key.replace("test_", "").replace("_", " ").capitalize())

            # data = [[3,4], [4,8], [5,3], [9,1]]
            # v_labels = ["line1", "line2", "line3", "line4", "line5", "line6"]
            # h_labels = ["group1", "group2", "group3", "group4"]

            CairoPlot.bar_plot("charts/time_%s.png" % key, time_data, 900, 300, border=20, grid=True, h_labels=h_labels)
            CairoPlot.bar_plot("charts/mem_%s.png" % key, mem_data, 900, 300, border=20, grid=True, h_labels=h_labels)
Пример #8
0
    def plotProductSeverityDistribution(self, dist, product):
        severity_list = [
            'enhancement', 'trivial', 'minor', 'normal', 'major', 'critical',
            'blocker'
        ]
        values_list = []

        for severity in severity_list:
            values_list.append(dist[severity])

        maxbugs = "%d bugs" % max(values_list)
        vlabels = ['zarro boogs', maxbugs]

        CairoPlot.bar_plot(str(product),
                           values_list,
                           500,
                           400,
                           border=20,
                           grid=True,
                           h_labels=severity_list,
                           v_labels=vlabels)
Пример #9
0
import CairoPlot
CairoPlot.dot_line_plot('output/results/graph_cars', [ 2, 2, 7, 8, 1, 4, 2, 13, 0, 3, 10, 2, 1, 8, 0, 0, 2, 0, 5, 0, 3, 7, 7, 3, 3, 2, 14, 1, 5, 8, 3, 1, 13, 6, 6, 10, 5, 14, 9, 5, 15, 4, 3, 9, 5, 27, 5, 12, 12, 17], 400, 300, h_labels = [ "01/Mar 15:57", "01/Mar 16:14", "01/Mar 16:35", "01/Mar 19:20", "01/Mar 19:33", "02/Mar 08:09", "02/Mar 08:20", "02/Mar 08:37", "02/Mar 08:48", "02/Mar 08:58", "02/Mar 09:10", "02/Mar 09:27", "02/Mar 09:39", "02/Mar 09:52", "02/Mar 10:04", "02/Mar 10:29", "02/Mar 10:45", "02/Mar 11:02", "02/Mar 11:14", "02/Mar 11:26", "02/Mar 11:38", "02/Mar 11:51", "02/Mar 11:51", "02/Mar 12:05", "02/Mar 12:20", "02/Mar 12:40", "02/Mar 12:56", "02/Mar 13:07", "02/Mar 13:20", "02/Mar 13:33", "02/Mar 13:49", "02/Mar 16:08", "02/Mar 16:19", "03/Mar 13:31", "03/Mar 13:33", "03/Mar 13:38", "03/Mar 13:43", "03/Mar 13:50", "03/Mar 13:59", "03/Mar 14:06", "03/Mar 14:12", "03/Mar 14:22", "03/Mar 14:29", "03/Mar 14:34", "03/Mar 14:40", "03/Mar 14:48", "03/Mar 14:53", "03/Mar 14:57", "03/Mar 14:57", "03/Mar 15:36"], axis = True, grid = True)
Пример #10
0
    def crear_grafica(self, grafica=None):

        if not grafica:
            grafica = self.grafica

        self.grafica = grafica
        pasar = False

        #self.cargar_colores()

        if self.colores and type(self.colores[-1]) == float:
            c1 = self.colores[-3]
            c2 = self.colores[-2]
            c3 = self.colores[-1]

            self.colores.remove(self.colores[-1])
            self.colores.remove(self.colores[-1])
            self.colores.remove(self.colores[-1])

            self.colores.insert(-1, (c1, c2, c3))

        for x in self.valores.keys():
            for i in self.valores[x]:
                if i >= 1:
                    pasar = True
                    break

        if not pasar and self.valores.keys():
            self.valores[sorted(self.valores.keys())[0]] = [1]

        if grafica == 'Gráfica de barras horizontales':
            y_labels = sorted(self.valores.keys())
            y_labels.sort()

            if self.valores:
                if len(self.valores[sorted(self.valores.keys())[0]]) == 1:
                    valores = self.transformar_a_barras()

                else:
                    valores = self.valores

                CairoPlot.horizontal_bar_plot(
                    self.direccion,
                    valores,
                    self.tamanyo_x,
                    self.tamanyo_y,
                    background=self.fondo,
                    border=self.borde,
                    display_values=self.display_values,
                    grid=self.cuadricula,
                    rounded_corners=self.rounded_corners,
                    stack=False,
                    three_dimension=True,
                    series_labels=None,
                    x_labels=[],
                    y_labels=y_labels,
                    x_bounds=None,
                    y_bounds=None,
                    colors=self.colores)

        elif grafica == 'Gráfica de barras verticales':
            x_labels = sorted(self.valores.keys()) #self.l_valores
            y_labels = []
            x_labels.sort()

            if self.valores:
                if len(self.valores[sorted(self.valores.keys())[0]]) == 1:
                    valores = self.transformar_a_barras()

                else:
                    valores = self.valores

                CairoPlot.vertical_bar_plot(
                    self.direccion,
                    valores,
                    self.tamanyo_x,
                    self.tamanyo_y,
                    background=self.fondo,
                    border=self.borde,
                    display_values=self.display_values,
                    grid=self.cuadricula,
                    rounded_corners=self.rounded_corners,
                    stack=False,
                    three_dimension=True,
                    series_labels=None,
                    x_labels=x_labels,
                    y_labels=y_labels,
                    x_bounds=None,
                    y_bounds=None,
                    colors=self.colores)

        elif grafica == 'Gráfica de torta':
            CairoPlot.pie_plot(
                self.direccion,
                self.valores,
                self.tamanyo_x,
                self.tamanyo_y,
                background=self.fondo,
                gradient=True,
                shadow=False,
                colors=self.colores)

        elif grafica == 'Gráfica de puntos':
            CairoPlot.dot_line_plot(
                self.direccion,
                self.valores,
                self.tamanyo_x,
                self.tamanyo_y,
                background=self.fondo,
                border=self.borde,
                axis=self.axis,
                dots=False,
                grid=self.cuadricula,
                series_legend=self.grupos,
                x_labels=self.x_labels,
                y_labels=self.y_labels,
                x_bounds=None,
                y_bounds=None,
                x_title=self.titulo_x,
                y_title=self.titulo_y,
                series_colors=self.colores)

        elif grafica == 'Gráfica de anillo':
            CairoPlot.donut_plot(
                self.direccion,
                self.valores,
                self.tamanyo_x,
                self.tamanyo_y,
                background=self.fondo,
                gradient=True,
                shadow=False,
                colors=self.colores,
                inner_radius=self.inner_radius)

        elif grafica == 'Gráfica de ecuaciones':
            valores, rectas = self.transformar_a_ecuaciones()

            CairoPlot.dot_ecuations_plot(self.direccion, valores, rectas=rectas, width=self.tamanyo_x, height=self.tamanyo_y)

        self.area.set_plot(self.direccion)

        self.emit('save-changes')
Пример #11
0
def parse_command(message, str_cmd):
    global keypad_target_dev
    global is_cctv_active
    global CHAT_ID
    global CCTV_URL

    # split message
    cmd = str_cmd.strip().split(' ')
    
    # Bot check command
    if cmd[0] == 'hello' or cmd[0] == 'hi' or cmd[0] == '하이' or cmd[0] == '안녕':
        send_chat(message, msg_welcome())
        return

    # Send chat message
    if cmd[0] == 'chat' or cmd[0] == '챗':
        if len(cmd) > 1:
            str_msg = 'Bot msg: '
            for index in range(1, len(cmd)):
                str_msg += cmd[index] + ' '
            str_msg.strip()
            send_chat(message, str_msg)

    # Ping test
    elif cmd[0] == 'help' or cmd[0] == '도움말':
        send_chat(message, msg_help_text())
        return

    # Ping test
    elif cmd[0] == 'ping' or cmd[0] == '핑':
        # extract parameter
        # send a data1 data2 data3 data4 : a=device number, data1 ~ data4: data to send to remote
        if len(cmd) < 2:
            send_chat(message, msg_devnum_error())
            return
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        else:
            send_chat(message, msg_devnum_error())
            return
        device = t_dev.get_device_at(devnum)
        if device is None:
            send_chat(message, msg_device_not_found() + ' ' + str(devnum))
            return
        t_ser.send(device.cat1, device.cat2, device.devid, 0x01, 0, 0, 0, 0)
        return

    # Set language
    elif cmd[0] == 'lang' or cmd[0] == 'language' or cmd[0] == '언어':
        if len(cmd) < 2:
            send_chat(message, msg_current_lang() +': '+config.get_language())
            return
        if cmd[1] == 'en' or cmd[1] == 'english' or cmd[1] == '영어':
            config.set_language('en')
            set_proto_lang('en')
            set_msg_lang('en')
            send_chat(message, msg_lang_changed())
            return
        elif cmd[1] == 'kr' or cmd[1] == 'korean' or cmd[1] == '한글' or cmd[1] == '한국어':
            config.set_language('kr')
            set_proto_lang('kr')
            set_msg_lang('kr')
            send_chat(message, msg_lang_changed())
            return
        send_chat(message, msg_invalid_param())
        return

    # Control MPD (need MPC)
    elif cmd[0] == 'mpc' or cmd[0] == 'music' or cmd[0] == '음악' or cmd[0] == '뮤직':
        # show queued songs
        if len(cmd) < 2:
            results = subprocess.check_output('mpc playlist', shell=True)
            a_res = results.split('\n')
            disp_str = ''
            index = 1
            for item in a_res:
                if item != '':
                    disp_str += str(index) + '. ' + item + '\n'
                    index += 1
            send_chat(message, '[] '+msg_current_queue()+': \n' + disp_str)
            return

        # play
        elif cmd[1] == 'play' or cmd[1] == '재생' or cmd[1] == '플레이':
            # play
            if len(cmd) < 3:
                results = subprocess.check_output('mpc play', shell=True)
                send_chat(message, results)
                return
            # check parameter: playlist number
            if cmd[2].isdigit() == False:
                send_chat(message, msg_invalid_playlist())
                return
            # push playlist into current queue
            tmpcheck = subprocess.check_output('mpc play '+cmd[2], shell=True)
            send_chat(message, tmpcheck)
            return

        # stop
        elif cmd[1] == 'stop' or cmd[1] == '정지':
            tmpcheck = subprocess.check_output('mpc stop', shell=True)
            send_chat(message, tmpcheck)
            return

        # playlist handler
        elif cmd[1] == 'playlist' or cmd[1] == '재생목록':
            # show playlists
            if len(cmd) < 3:
                results = subprocess.check_output('mpc lsplaylists', shell=True)
                a_res = results.split('\n')
                disp_str = ''
                index = 1
                for item in a_res:
                    if item != '':
                        disp_str += str(index) + '. ' + item + '\n'
                        index += 1
                send_chat(message, '[*] Playlists: \n' + disp_str)
                return
            # check parameter: playlist number
            if cmd[2].isdigit() == False:
                send_chat(message, msg_invalid_playlist())
                return
            # push playlist into current queue
            playlist_num = int(cmd[2])
            results = subprocess.check_output('mpc lsplaylists', shell=True)
            a_res = results.split('\n')
            disp_str = ''
            index = 1
            selected = 0
            for item in a_res:
                if item != '':
                    if playlist_num == index:
                        disp_str = item
                        selected = index
                    index += 1
            if selected > 0:
                tmpcheck = subprocess.check_output('mpc current', shell=True)
                if tmpcheck == '' or tmpcheck is None or len(tmpcheck) < 3:
                    # current status: stopped - clear all
                    subprocess.check_output('mpc clear', shell=True)
                else:
                    # current status: stopped - clear except current playing
                    subprocess.check_output('mpc crop', shell=True)
                results = subprocess.check_output('mpc load '+disp_str, shell=True)
                send_chat(message, 'Playlist '+msg_changed_to()+' \n' + disp_str)
            else:
                send_chat(message, msg_invalid_playlist())
            return

        # control panel
        if cmd[1] == 'ctrl' or cmd[1] == 'control' or cmd[1] == '리모콘' or cmd[1] == '컨트롤':
            if len(cmd) > 2 and (cmd[2] == 'off' or cmd[2] == '닫기' or cmd[2]=='오프'):
                markup = types.ReplyKeyboardHide(selective=False)
                bot.send_message(CHAT_ID, 'Music '+msg_control_panel_closed(), reply_markup=markup)
            else:
                markup = types.ReplyKeyboardMarkup(row_width=3)
                markup.add('[prev]', '[play]', '[next]', '[pause]', '[stop]', '[exit]', '[random]', '[repeat]', '[consume]')
                bot.send_message(CHAT_ID, 'Music '+msg_control_panel()+': ', reply_markup=markup)
            return

    # Keypad: control panel
    if cmd[0] == 'keypad' or cmd[0] == 'control' or cmd[0] == '키패드' or cmd[0] == '컨트롤':
        # close keypad
        if len(cmd) > 1 and (cmd[1] == 'off' or cmd[1] == 'close' or cmd[1] == '닫기' or cmd[1]=='오프'):
            markup = types.ReplyKeyboardHide(selective=False)
            bot.send_message(CHAT_ID, msg_keypad()+' '+msg_control_panel_closed(), reply_markup=markup)
        # show current target device
        elif len(cmd) == 2 and (cmd[1] == 'dev' or cmd[1] == 'set' or cmd[1] == '장치' or cmd[1]=='설정'):
            send_chat(message, msg_k+' = '+str(keypad_target_dev))
        # set target device
        elif len(cmd) > 2 and (cmd[1] == 'dev' or cmd[1] == 'set' or cmd[1] == '장치' or cmd[1]=='설정'):
            if cmd[2].isdigit():
                devnum = -1
                devnum = int(cmd[2])
                device = t_dev.get_device_at(devnum)
                if device is None:
                    send_chat(message, msg_wrong_device())
                    return;
                keypad_target_dev = devnum
                send_chat(message, msg_keypad_set_dev()+' : '+str(keypad_target_dev))
            else:
                send_chat(message, msg_wrong_device())
            return
        # open keypad
        else:
            markup = types.ReplyKeyboardMarkup(row_width=4)
            markup.add('[/]', '[*]', '[+]', '[-]', '[7]', '[8]', '[9]', '[Enter]', '[4]', '[5]', '[6]', '[.]', '[1]', '[2]', '[3]', '[0]')
            bot.send_message(CHAT_ID, msg_keypad()+': ', reply_markup=markup)
        return

    # cctv command
    elif cmd[0] == 'cctv' or cmd[0] == 'cam' or cmd[0] == '캠':
        if len(cmd) < 2:
            send_chat(message, msg_invalid_param())
            return
        if cmd[1] == 'on' or cmd[1] == '온':
            if is_cctv_active:
                send_chat(message, msg_cctv_already_on() + ' ' + CCTV_URL)
                return
            else:
                #if CCTV_URL == '':
                #    CCTV_URL = 'http://'
                #    CCTV_URL += subprocess.check_output('wget -q http://ip.kiduk.kr && more index.html', shell=True)
                #    CCTV_URL += ':' + CCTV_PORT
                os.system(CCTV_START_CMD)
                send_chat(message, msg_cctv_on() + ' ' + CCTV_URL)
                is_cctv_active = True
        elif cmd[1] == 'off' or cmd[1] == '오프':
            os.system(CCTV_STOP_CMD)
            send_chat(message, msg_cctv_off())
            is_cctv_active = False
        return

    # take a picture
    elif cmd[0] == 'pic' or cmd[0] == 'picture' or cmd[0] == '사진':
        # remove pictures in picture directory
        if len(cmd) > 1 and (cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거'):
            os.system('rm -f '+PICTURE_DIR+'image_*.jpg')
            send_chat(message, msg_remove_pictures())
            return

        # Stop cctv first
        if is_cctv_active:
            send_chat(message, msg_turnoff_cctv())
        os.system(CCTV_STOP_CMD)
        is_cctv_active = False
        time.sleep(1)  # Sleep for a while to avoid camera access error

        # Take a still shot
        now = time.localtime()
        pic_file_name = "image_%04d-%02d-%02d_%02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
        pic_file_name += '.jpg'
        os.system(PHOTO_CMD + ' ' + PICTURE_DIR + pic_file_name)

        # Send picture
        try:
            pic_file = open(PICTURE_DIR + pic_file_name, 'rb')
            ret_msg = send_photo(message, pic_file)  # message.chat.id
        except:
            send_chat(message, 'Cannot take a picture!!')
        return

    # Device command
    elif cmd[0] == 'dev' or cmd[0] == 'device' or cmd[0] == '장치':
        # Device - Show device list
        if len(cmd) < 2:
            count = 0
            msg = ''
            devices = t_dev.get_device_list()
            for device in devices:
                msg += str(count+1) + ". "
                msg += device.name
                msg += ", " + msg_location() + "="
                msg += device.loc
                msg += "\n" + msg_category() +"1=" + str(device.cat1)
                msg += ", " + msg_category() +"2=" + str(device.cat2)
                msg += ", ID=" + str(device.devid)
                msg += "\n\n"
                count = count + 1
            if count < 1:
                msg += msg_device_not_found()
            else:
                msg += msg_devdesc_command()
            send_chat(message, msg)
            return
        # Device - Show device details
        elif cmd[1] == 'desc' or cmd[1] == 'detail' or cmd[1] == '상세':
            if len(cmd) >= 3:
                msg = ''
                devnum = -1
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                device = t_dev.get_device_at(devnum)
                if device is not None:
                    msg += msg_device_number() + " = " + str(devnum) + "\n"
                    msg += device.name
                    msg += ", " + msg_location() + "="
                    msg += device.loc
                    msg += "\n" + msg_category() + "1=" + str(device.cat1)
                    msg += ", " + msg_category() + "2=" + str(device.cat2)
                    msg += ", ID=" + str(device.devid)
                    msg += "\n" + msg_update_time() + "=" + time.asctime(time.localtime(device.time))
                    msg += "\n\n"
                    msg += msg_control_signal() + "1="
                    msg += get_cmd_name(device.cmd1)
                    msg += ", " + msg_data_type() + "1="
                    msg += get_cmd_type_name(device.cmd1dtype)
                    msg += "\n"
                    msg += msg_control_signal() + "2="
                    msg += get_cmd_name(device.cmd2)
                    msg += ", " + msg_data_type() + "2="
                    msg += get_cmd_type_name(device.cmd2dtype)
                    msg += "\n"
                    msg += msg_control_signal() + "3="
                    msg += get_cmd_name(device.cmd3)
                    msg += ", " + msg_data_type() + "3="
                    msg += get_cmd_type_name(device.cmd3dtype)
                    msg += "\n"
                    msg += msg_control_signal() + "4="
                    msg += get_cmd_name(device.cmd4)
                    msg += ", " + msg_data_type() + "4="
                    msg += get_cmd_type_name(device.cmd4dtype)
                    msg += "\n\n" + msg_ctrlsignal_desc()
                else:
                    msg += msg_device_not_found()
                send_chat(message, msg)
            return

        # Device - Remove device
        elif cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) >= 3:
                msg = ''
                devnum = 0
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                else:
                    send_chat(message, msg_devnum_error())
                    return
                if t_dev.delete_device_at(devnum):
                    send_chat(message, msg_device_removed() % devnum)
                else:
                    send_chat(message, msg_device_remove_error() % devnum)
            return

        # Device - Remove all devices
        elif cmd[1] == 'removeall' or cmd[1] == 'delall' or cmd[1] == 'deleteall' or cmd[1] == '모두삭제' or cmd[1] == '모두제거':
            if t_dev.delete_devices_all():
                send_chat(message, msg_every_device_removed())
            else:
                send_chat(message, msg_every_device_remove_error())
            return

    # Get sensor value
    elif cmd[0] == 'sensor' or cmd[0] == 'data' or cmd[0] == 'print' or cmd[0] == '센서' or cmd[0] == '데이터' or cmd[0] == '출력':
        if len(cmd) < 2:
            return
        # Delete sensor records
        if cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거':
            # Delete specified device's records
            if len(cmd) == 3:
                devnum = 0
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                else:
                    send_chat(message, msg_devnum_error())
                    return
                # delete from DB
                if t_dev.delete_sensor_val(devnum, -1):
                    send_chat(message, msg_sensordata_removed() % devnum)
                else:
                    send_chat(message, msg_sensordata_remove_error() % devnum)

            # Delete records older than user specified time (specified device)
            # time must be hour unit: delete all older than x hours
            elif len(cmd) >= 4:
                # Get device number, time string
                devnum = -1
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                newtime = -1
                if cmd[3].isdigit():
                    tparam = int(cmd[3])
                    newtime = int(time.time() - tparam*60*60)
                # delete from DB
                if t_dev.delete_sensor_val(devnum, newtime):
                    send_chat(message, msg_sensordata_removed() % devnum)
                else:
                    send_chat(message, msg_sensordata_remove_error() % devnum)
            else:
                send_chat(message, msg_need_devnum())
            return

        # Delete sensor records all
        elif cmd[1] == 'removeall' or cmd[1] == 'delall' or cmd[1] == 'deleteall' or cmd[1] == '모두삭제' or cmd[1] == '모두제거':
            # Delete specified device's records
            newtime = -1
            if len(cmd) >= 3:
                # Delete records older than user specified time (specified device)
                # time must be hour unit: delete all older than x hours
                newtime = -1
                if cmd[2].isdigit():
                    tparam = int(cmd[2])
                    newtime = int(time.time() - tparam*60*60*1000)
            # delete from DB
            if t_dev.delete_sensor_all(newtime):
                send_chat(message, msg_every_sensordata_removed())
            else:
                send_chat(message, msg_every_sensordata_remove_error())

        # Show sensor records
        else:
            # extract parameter
            # sensor a b : a=device number, b=count
            count = 1
            if len(cmd) > 2:
                if cmd[2].isdigit():
                    count = int(cmd[2])
                if count > 100 or count < 1:
                    count = 100
            devnum = -1
            if cmd[1].isdigit():
                devnum = int(cmd[1])
            if devnum < 0:
                send_chat(message, msg_wrong_device())
                return
            infos = t_dev.get_sensor_val(devnum, count)
            if infos is None or len(infos) < 1:
                send_chat(message, msg_no_matching_result())
                return
            msg = ''
            i = 0
            for info in infos:
                itime = time.localtime(info.time)
                msg += "%d-%d %d:%d" % (itime.tm_mon, itime.tm_mday, itime.tm_hour, itime.tm_min)
                msg += " = %d, %d, %d, %d" % (info.data1, info.data2, info.data3, info.data4)
                msg += "\n"
                i = i + 1
            if i > 0:
                send_chat(message, msg)
            else:
                send_chat(message, msg_no_matching_result())
        return

    # Get sensor value and return with graph
    elif cmd[0] == 'graph' or cmd[0] == '그래프':
        if len(cmd) == 2 and (cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거'):
            os.system('rm -f '+GRAPH_DIR+'graph_*.png')
            send_chat(message, msg_remove_pictures())
            return

        # extract parameter
        # graph a b : a=device number, b=count
        if len(cmd) < 2:
            return
        count = 10
        if len(cmd) > 2:
            if cmd[2].isdigit():
                count = int(cmd[2])
            if count > 100 or count < 1:
                count = 100
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        if devnum < 0:
            send_chat(message, msg_wrong_device())
            return
        infos = t_dev.get_sensor_val(devnum, count)
        if infos is None or len(infos) < 1:
            send_chat(message, msg_no_matching_result())
            return
        # making data list
        i = 0
        datas = [[], [], [], []]
        h_labels = []
        prev_d, prev_h, prev_m = 0, 0, 0
        for info in infos:
            itime = time.localtime(info.time)
            if prev_d != itime.tm_mday or prev_h != itime.tm_hour or prev_m != itime.tm_min:
                timestr = "%d-%d %d:%d" % (itime.tm_mon, itime.tm_mday, itime.tm_hour, itime.tm_min)
            else:
                timestr = "%d:%d" % (itime.tm_hour, itime.tm_min)
            prev_d, prev_h, prev_m = itime.tm_mday, itime.tm_hour, itime.tm_min
            datas[0].append(info.data1)
            datas[1].append(info.data2)
            datas[2].append(info.data3)
            datas[3].append(info.data4)
            h_labels.append(timestr)
            i = i + 1
        # ready to burn graph
        if i > 0:
            # adjust image size
            width = 500
            height = 375
            if i > 25 and i <= 50:
                width = 1000
                height = 750
            elif i > 50:
                width = 1600
                height = 1200
            # burn graph
            cat1, cat2, devid = t_dev.get_ids_at(devnum)
            fname = 'graph_'+str(cat1)+'_'+str(cat2)+'_'+str(devid)+'.png'
            CairoPlot.dot_line_plot(GRAPH_DIR + fname,
                    datas, width, height,
                    h_labels = h_labels, v_labels = [],
                    axis = True, grid = True, dots = True)
            try:
                # Send graph
                pic_file = open(GRAPH_DIR + fname, 'rb')
                ret_msg = send_photo(message, pic_file)
            except:
                send_chat(message, msg_cannot_open_graph())
        else:
            send_chat(message, msg_no_matching_result())
        return

    # Sends data to remote
    elif cmd[0] == 'ctrl' or cmd[0] == 'control' or cmd[0] == 'send' or cmd[0] == '제어' or cmd[0] == '전송':
        # extract parameter
        # send a data1 data2 data3 data4 : a=device number, data1 ~ data4: data to send to remote
        if len(cmd) < 3:
            return
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        else:
            send_chat(message, msg_wrong_device())
            return;
        # get device info
        device = t_dev.get_device_at(devnum)
        if device is None:
            send_chat(message, msg_wrong_device())
            return;
        data1 = 0
        # we have to catch the exception: negative value
        if cmd[2][0] == '-' and cmd[2][1:].isdigit():
            data1 = int(Decimal(cmd[2]))
        elif cmd[2].isdigit():
            data1 = int(cmd[2])
        else:
            send_chat(message, msg_wrong_param1())
            return;
        data2 = 0
        if len(cmd) > 3 and cmd[3][0] == '-' and cmd[3][1:].isdigit():
            data2 = int(Decimal(cmd[3]))
        elif len(cmd) > 3 and cmd[3].isdigit():
            data2 = int(cmd[3])
        else:
            data2 = 0
        data3 = 0
        if len(cmd) > 4 and cmd[4][0] == '-' and cmd[4][1:].isdigit():
            data3 = int(Decimal(cmd[4]))
        elif len(cmd) > 4 and cmd[4].isdigit():
            data3 = int(cmd[4])
        else:
            data3 = 0
        data4 = 0
        if len(cmd) > 5 and cmd[5][0] == '-' and cmd[5][1:].isdigit():
            data4 = int(Decimal(cmd[5]))
        elif len(cmd) > 5 and cmd[5].isdigit():
            data4 = int(cmd[5])
        else:
            data4 = 0
        # send device control signal to remote
        t_ser.send_control_signal(device.cat1, device.cat2, device.devid, data1, data2, data3, data4)
        send_chat(message, msg_sent_signal() % devnum)
        return

    # Make notification setting
    elif cmd[0] == 'noti' or cmd[0] == 'notification' or cmd[0] == '알림':
        # Show current notifications
        if len(cmd) < 2:
            strmsg = ''
            notis = t_dev.get_noti_list()
            count = 0
            for noti in notis:
                strmsg += msg_noti() + ' ID = ' + str(noti.id) + '\n'
                #strmsg += noti[13] + '\n'
                strmsg += msg_category() + "1=" + str(noti.cat1)
                strmsg += ", " + msg_category() + "2=" + str(noti.cat2)
                strmsg += ", ID=" + str(noti.devid) + "\n" + "if "
                tmpcount = 0
                if noti.comp1 > 0:
                    strmsg += "Data1 "
                    strmsg += get_comp_operator(noti.comp1) + " "
                    strmsg += str(noti.data1) + "\n"
                    tmpcount += 1
                if noti.comp2 > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data2 "
                    strmsg += get_comp_operator(noti.comp2) + " "
                    strmsg += str(noti.data2) + "\n"
                    tmpcount += 1
                if noti.comp3 > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data3 "
                    strmsg += get_comp_operator(noti.comp3) + " "
                    strmsg += str(noti.data3) + "\n"
                    tmpcount += 1
                if noti.comp4 > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data4 "
                    strmsg += get_comp_operator(noti.comp4) + " "
                    strmsg += str(noti.data4) + "\n"
                    tmpcount += 1
                count += 1
                strmsg += '\n'
            if count > 0:
                send_chat(message, strmsg)
            else:
                send_chat(message, msg_no_noti())
            # End of 'noti' command
            return

        # Delete notification
        elif cmd[1] == 'delete' or cmd[1] == 'del' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) < 3:
                send_chat(message, msg_type_noti_del_param())
                return
            else:
                if len(cmd) == 3 and cmd[2].isdigit():
                    # delete with noti-ID
                    noti_id = int(cmd[2])
                    if t_dev.delete_noti_with_id(noti_id):
                        send_chat(message, msg_noti_del_success())
                    else:
                        send_chat(message, msg_noti_del_fail())
                    return
                elif len(cmd) == 5 and cmd[2].isdigit() and cmd[3].isdigit() and cmd[4].isdigit():
                    # delete with device parameters
                    cat1 = int(cmd[2])
                    cat2 = int(cmd[3])
                    devid = int(cmd[4])
                    if t_dev.delete_noti_with_param(cat1, cat2, devid):
                        send_chat(message, msg_noti_del_success())
                    else:
                        send_chat(message, msg_noti_del_fail())
                    return
                else:
                    send_chat(message, msg_noti_del_fail())
                    return

        # Add notification
        elif cmd[1] == 'add' or cmd[1] == '추가':
            if len(cmd) < 4:
                send_chat(message, msg_add_noti_param())
                return
            devnum = -1
            if cmd[2].isdigit():
                devnum = int(cmd[2])
            else:
                send_chat(message, msg_add_noti_param())
                return
            # search device info
            cat1, cat2, devid = t_dev.get_ids_at(devnum)
            if cat1 < 0 or cat2 < 0 or devid < 0:
                send_chat(message, msg_wrong_device())
                return
            noti = NotiInfo()
            noti.cat1 = cat1
            noti.cat2 = cat2
            noti.devid = devid
            datanum1, datanum2, datanum3, datanum4 = 0,0,0,0
            compcode1, compcode2, compcode3, compcode4 = 0,0,0,0
            targetnum1, targetnum2, targetnum3, targetnum4 = 0,0,0,0
            pcount = 0
            # parse data1
            datanum, compcode, targetnum = parse_comp_str(cmd[3])
            if datanum < 1 or compcode < 1:
                # send_chat(message, msg_add_noti_param()+' (data1 error)')
                pass
            elif datanum == 1:
                compcode1 = compcode
                targetnum1 = targetnum
                pcount += 1
            elif datanum == 2:
                compcode2 = compcode
                targetnum2 = targetnum
                pcount += 1
            elif datanum == 3:
                compcode3 = compcode
                targetnum3 = targetnum
                pcount += 1
            elif datanum == 4:
                compcode4 = compcode
                targetnum4 = targetnum
                pcount += 1
            # parse data2
            if len(cmd) > 4:
                datanum, compcode, targetnum = parse_comp_str(cmd[4])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data2 error)')
                    pass
                elif datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            # parse data3
            if len(cmd) > 5:
                datanum, compcode, targetnum = parse_comp_str(cmd[5])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data4 error)')
                    pass
                elif datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            # parse data4
            if len(cmd) > 6:
                datanum, compcode, targetnum = parse_comp_str(cmd[6])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data4 error)')
                    pass
                if datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            if pcount < 1:
                send_chat(message, msg_invalid_noti_cmd())
                return
            # assign parsed parameters
            noti.comp1 = compcode1
            noti.comp2 = compcode2
            noti.comp3 = compcode3
            noti.comp4 = compcode4
            noti.data1 = targetnum1
            noti.data2 = targetnum2
            noti.data3 = targetnum3
            noti.data4 = targetnum4
            noti.time = int(time.time())
            cur = time.localtime()
            noti.name = 'Noti' + str(cur.tm_mon) + str(cur.tm_mday) + str(cur.tm_hour) + str(cur.tm_min) + str(cur.tm_sec)
            # push to DB and cached list
            if t_dev.add_noti(noti):
                send_chat(message, msg_add_noti_success())
            else:
                send_chat(message, msg_add_noti_failed())
        # Invalid notification command
        else:
            send_chat(message, msg_invalid_noti_cmd())
        return

    # Make macro
    elif cmd[0] == 'macro' or cmd[0] == '매크로':
        # Show macro list
        if len(cmd) < 2:
            strmsg = ''
            macros = t_dev.get_macro_list()
            count = 0
            for macro in macros:
                if macro.interval > 0 or macro.nid < 0:  # filtering macro
                    continue
                strmsg += msg_macro() + ' ID = ' + str(macro.id) + '\n'
                strmsg += '-> If ' + msg_noti() + 'ID == ' + str(macro.nid) + ', Do : '
                strmsg += macro.cmd + '\n'
                count += 1
            if count > 0:
                send_chat(message, strmsg)
            else:
                strmsg += '\n'
                send_chat(message, msg_no_macro())
            # End of 'macro' command
            return

        # Delete macro
        elif cmd[1] == 'delete' or cmd[1] == 'del' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) < 3:
                send_chat(message, msg_type_macro_del_param())
                return
            else:
                if len(cmd) == 3 and cmd[2].isdigit():
                    # delete with macro-ID
                    macro_id = int(cmd[2])
                    if t_dev.delete_macro_with_id(macro_id):
                        send_chat(message, msg_macro_del_success())
                    else:
                        send_chat(message, msg_macro_del_fail())
                    return
                elif len(cmd) == 5 and cmd[2].isdigit() and cmd[3].isdigit() and cmd[4].isdigit():
                    # delete with device parameters
                    cat1 = int(cmd[2])
                    cat2 = int(cmd[3])
                    devid = int(cmd[4])
                    if t_dev.delete_macro_with_param(cat1, cat2, devid):
                        send_chat(message, msg_macro_del_success())
                    else:
                        send_chat(message, msg_macro_del_fail())
                    return
                else:
                    # cannot delete macro
                    send_chat(message, msg_macro_del_fail())
                    return

        # Add macro (noti-triggered)
        elif cmd[1] == 'add' or cmd[1] == '추가':
            if len(cmd) < 4:
                send_chat(message, msg_add_macro_param())
                return
            noti_num = -1
            if cmd[2].isdigit():
                noti_num = int(cmd[2])
            else:
                send_chat(message, msg_add_macro_param())
                return
            # search device info
            noti = t_dev.get_noti_with_id(noti_num)
            if noti is None:
                send_chat(message, msg_invalid_noti_id())
                return
            cat1 = noti.cat1
            cat2 = noti.cat2
            devid = noti.devid
            if cat1 < 0 or cat2 < 0 or devid < 0:
                send_chat(message, msg_wrong_device())
                return
            str_cmd = ""
            for index in range(3, len(cmd)):
                str_cmd += cmd[index] + ' '
            str_cmd.strip()
            o_macro = MacroInfo()
            o_macro.nid = noti_num  # noti id
            o_macro.cat1 = cat1     # cat1
            o_macro.cat2 = cat2     # cat2
            o_macro.devid = devid   # device ID
            o_macro.time = int(time.time())  # updated
            o_macro.cmd = str_cmd   # command
            o_macro.interval = 0    # interval (for timer)
            if t_dev.add_macro(o_macro):
                send_chat(message, msg_add_macro_success())
            else:
                send_chat(message, msg_add_macro_fail())
            return

    # Make timer
    elif cmd[0] == 'timer' or cmd[0] == '타이머':
        # Show timer list
        if len(cmd) < 2:
            strmsg = ''
            macros = t_dev.get_macro_list()
            count = 0
            for macro in macros:
                if macro.nid > -1:  # filter out noti-triggered macro
                    continue
                strmsg += msg_timer() + ' ID = ' + str(macro.id) + '\n'
                if macro.interval < 1:  # time based timer
                    strmsg += '-> At ' + str(macro.hour) + ':' + str(macro.minute) + ', Do : '
                else:    # interval based timer
                    strmsg += '-> Every ' + str(macro.interval) + ' min, Do : '
                strmsg += macro.cmd + '\n'
                count += 1
            if count > 0:
                send_chat(message, strmsg)
            else:
                strmsg += '\n'
                send_chat(message, msg_no_timer())
            # End of 'timer' command
            return

        # Delete timer
        elif cmd[1] == 'delete' or cmd[1] == 'del' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) < 3:
                send_chat(message, msg_type_timer_del_param())
                return
            else:
                if len(cmd) == 3 and cmd[2].isdigit():
                    # delete with timer-ID
                    timer_id = int(cmd[2])
                    if t_dev.delete_macro_with_id(timer_id):
                        send_chat(message, msg_timer_del_success())
                    else:
                        send_chat(message, msg_timer_del_fail())
                    return
                else:
                    # cannot delete timer
                    send_chat(message, msg_timer_del_fail())
                    return

        # Add timer
        elif cmd[1] == 'add' or cmd[1] == '추가':
            if len(cmd) < 4:
                send_chat(message, msg_add_timer_param())
                return
            interval = -1
            ihour = 0
            imin = 0
            # time interval timer
            if cmd[2].isdigit():
                interval = int(cmd[2])
            # reserved time
            else:
                if cmd[2].find(':') < 0:
                    send_chat(message, msg_add_timer_param())
                    return
                else:
                    tmpstr = cmd[2].split(':')
                    if len(tmpstr) != 2:
                        send_chat(message, msg_add_timer_param())
                        return
                    if tmpstr[0].isdigit() and tmpstr[1].isdigit():
                        ihour = int(tmpstr[0])
                        imin = int(tmpstr[1])
                    else:
                        send_chat(message, msg_add_timer_param())
                        return
            str_cmd = ""
            for index in range(3, len(cmd)):
                str_cmd += cmd[index] + ' '
            str_cmd.strip()
            o_macro = MacroInfo()
            o_macro.time = int(time.time())  # updated
            o_macro.cmd = str_cmd        # command
            o_macro.interval = interval  # interval (for timer)
            o_macro.hour = ihour         # reserved time - hour
            o_macro.minute = imin        # reserved time - min
            if t_dev.add_macro(o_macro):
                send_chat(message, msg_add_timer_success())
            else:
                send_chat(message, msg_add_timer_fail())
            return

    # End of echo_all(message)
    pass
Пример #12
0
# hist.py

import sys
import cairo
import CairoPlot


files = sys.argv
files.remove(sys.argv[0])

for f in files:
    try:
        inFile = open(f, "r")

        dat = {}

        for line in inFile:
            line = line.split()
            try:
                dat[line[1]] = int(line[0])
            except ValueError as (errno, strerror):
                print "Value error({0}): {1}".format(errno, strerror)

        inFile.close()

        f = f.split(".txt")[0].split("-")[-2].split("/")[-1] + "-piechart"
        CairoPlot.pie_plot(f, dat, 1000, 700)

    except IOError as (errno, strerror):
        print "I/O error({0}): " + f + " {1}".format(errno, strerror)
Пример #13
0
def parseCommand(message, str_cmd):
    global is_cctv_active
    global CHAT_ID
    global cctv_url

    # split message
    cmd = str_cmd.strip().split(' ')
    
    # Bot check command
    if cmd[0] == 'hello' or cmd[0] == 'hi' or cmd[0] == '하이' or cmd[0] == '안녕':
        send_chat(message, msg_welcome())
    # Ping test
    elif cmd[0] == 'help' or cmd[0] == '도움말':
        send_chat(message, msg_help_text())

    # Ping test
    elif cmd[0] == 'ping' or cmd[0] == '핑':
        # extract parameter
        # send a data1 data2 data3 data4 : a=device number, data1 ~ data4: data to send to remote
        if len(cmd) < 2:
            send_chat(message, msg_devnum_error())
            return
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        else:
            send_chat(message, msg_devnum_error())
            return
        device = t_dev.get_device_at(devnum)
        if len(device) < 1:
            send_chat(message, msg_device_not_found() + ' ' + str(devnum))
            return
        t_ser.send(device[1], device[2], device[3], 0x01, 0, 0, 0, 0)        

    # Set language
    elif cmd[0] == 'lang' or cmd[0] == 'language' or cmd[0] == '언어':
        if len(cmd) < 2:
            send_chat(message, msg_current_lang() +': '+config.get_language())
            return
        if cmd[1] == 'en' or cmd[1] == 'english' or cmd[1] == '영어':
            config.set_language('en')
            set_proto_lang('en')
            set_msg_lang('en')
            send_chat(message, msg_lang_changed())
            return
        elif cmd[1] == 'kr' or cmd[1] == 'korean' or cmd[1] == '한글' or cmd[1] == '한국어':
            config.set_language('kr')
            set_proto_lang('kr')
            set_msg_lang('kr')
            send_chat(message, msg_lang_changed())
            return
        send_chat(message, msg_invalid_param())

    # Deprecated!!! Do not use this
    # weather command
#    elif cmd[0] == 'weather' or cmd[0] == '날씨':
#        owm = pyowm.OWM(weather_api_key)
#        obs = owm.weather_at_place(weather_location)
#        w = obs.get_weather()
#        report_str = weather_location
#        report_str += "\n"
#        report_str += w.get_detailed_status()
#        report_str += ", "
#        report_str += str(w.get_temperature(unit='celsius')['temp'])
#        report_str += "'C, "
#        report_str += str(w.get_humidity())
#        report_str += "%"
#        send_chat(message, report_str)

    # cctv command
    elif cmd[0] == 'cctv' or cmd[0] == 'cam' or cmd[0] == '캠':
        if len(cmd) < 2:
            send_chat(message, msg_invalid_param())
            return
        if cmd[1] == 'on' or cmd[1] == '온':
            if is_cctv_active:
                send_chat(message, msg_cctv_already_on() + ' ' + cctv_url)
                return
            else:
                #if cctv_url == '':
                #    cctv_url = 'http://'
                #    cctv_url += subprocess.check_output('wget -q http://ip.kiduk.kr && more index.html', shell=True)
                #    cctv_url += ':' + cctv_port
                os.system(cctv_start_cmd)
                send_chat(message, msg_cctv_on() + ' ' + cctv_url)
                is_cctv_active = True
        elif cmd[1] == 'off' or cmd[1] == '오프':
            os.system(cctv_stop_cmd)
            send_chat(message, msg_cctv_off())
            is_cctv_active = False

    # take a picture
    elif cmd[0] == 'pic' or cmd[0] == 'picture' or cmd[0] == '사진':
        # Stop cctv first
        if is_cctv_active:
            send_chat(message, msg_turnoff_cctv())
        os.system(cctv_stop_cmd)
        is_cctv_active = False
        time.sleep(1)  # Sleep for a while to avoid camera access error

        # Take a still shot
        now = time.localtime()
        pic_file_name = "image_%04d-%02d-%02d_%02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
        pic_file_name += '.jpg'
        os.system(take_a_picture_cmd + picture_dir + pic_file_name)

        # Send picture
        try:
            pic_file = open(picture_dir + pic_file_name, 'rb')
            ret_msg = send_photo(message, pic_file)  # message.chat.id
        except:
            send_chat(message, 'Cannot take a picture!!')

    # Device command
    elif cmd[0] == 'dev' or cmd[0] == 'device' or cmd[0] == '장치':
        # Device - Show device list
        if len(cmd) < 2:
            count = 0
            msg = ''
            devices = t_dev.get_device_list()
            for device in devices:
                msg += str(count+1) + ". "
                msg += device[13]
                msg += ", " + msg_location() + "="
                msg += device[14]
                msg += "\n" + msg_category() +"1=" + str(device[1])
                msg += ", " + msg_category() +"2=" + str(device[2])
                msg += ", ID=" + str(device[3])
                msg += "\n\n"
                count = count + 1
            if count < 1:
                msg += msg_device_not_found()
            else:
                msg += msg_devdesc_command()
            send_chat(message, msg)
        # Device - Show device details
        elif cmd[1] == 'desc' or cmd[1] == 'detail' or cmd[1] == '상세':
            if len(cmd) >= 3:
                msg = ''
                devnum = -1
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                device = t_dev.get_device_at(devnum)
                if len(device) > 0:
                    msg += msg_device_number() + " = " + str(devnum) + "\n"
                    msg += device[13]
                    msg += ", " + msg_location() + "="
                    msg += device[14]
                    msg += "\n" + msg_category() + "1=" + str(device[1])
                    msg += ", " + msg_category() + "2=" + str(device[2])
                    msg += ", ID=" + str(device[3])
                    msg += "\n" + msg_update_time() + "=" + time.asctime(time.localtime(device[15]))
                    msg += "\n\n"
                    msg += msg_control_signal() + "1="
                    msg += get_cmd_name(device[5])
                    msg += ", " + msg_data_type() + "1="
                    msg += get_cmd_type_name(device[6])
                    msg += "\n"
                    msg += msg_control_signal() + "2="
                    msg += get_cmd_name(device[7])
                    msg += ", " + msg_data_type() + "2="
                    msg += get_cmd_type_name(device[8])
                    msg += "\n"
                    msg += msg_control_signal() + "3="
                    msg += get_cmd_name(device[9])
                    msg += ", " + msg_data_type() + "3="
                    msg += get_cmd_type_name(device[10])
                    msg += "\n"
                    msg += msg_control_signal() + "4="
                    msg += get_cmd_name(device[11])
                    msg += ", " + msg_data_type() + "4="
                    msg += get_cmd_type_name(device[12])
                    msg += "\n\n" + msg_ctrlsignal_desc()
                else:
                    msg += msg_device_not_found()
                send_chat(message, msg)

        # Device - Remove device
        elif cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) >= 3:
                msg = ''
                devnum = 0
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                else:
                    send_chat(message, msg_devnum_error())
                    return
                if t_dev.delete_device_at(devnum):
                    send_chat(message, msg_device_removed() % devnum)
                else:
                    send_chat(message, msg_device_remove_error() % devnum)

        # Device - Remove all devices
        elif cmd[1] == 'removeall' or cmd[1] == 'delall' or cmd[1] == 'deleteall' or cmd[1] == '모두삭제' or cmd[1] == '모두제거':
            if t_dev.delete_devices_all():
                send_chat(message, msg_every_device_removed())
            else:
                send_chat(message, msg_every_device_remove_error())

    # Get sensor value
    elif cmd[0] == 'sensor' or cmd[0] == 'data' or cmd[0] == 'print' or cmd[0] == '센서' or cmd[0] == '데이터' or cmd[0] == '출력':
        if len(cmd) < 2:
            return
        # Delete sensor records
        if cmd[1] == 'remove' or cmd[1] == 'del' or cmd[1] == 'delete' or cmd[1] == '삭제' or cmd[1] == '제거':
            # Delete specified device's records
            if len(cmd) == 3:
                devnum = 0
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                else:
                    send_chat(message, msg_devnum_error())
                    return
                # delete from DB
                if t_dev.delete_sensor_val(devnum, -1):
                    send_chat(message, msg_sensordata_removed() % devnum)
                else:
                    send_chat(message, msg_sensordata_remove_error() % devnum)

            # Delete records older than user specified time (specified device)
            # time must be hour unit: delete all older than x hours
            elif len(cmd) >= 4:
                # Get device number, time string
                devnum = -1
                if cmd[2].isdigit():
                    devnum = int(cmd[2])
                newtime = -1
                if cmd[3].isdigit():
                    tparam = int(cmd[3])
                    newtime = int(time.time() - tparam*60*60)
                # delete from DB
                if t_dev.delete_sensor_val(devnum, newtime):
                    send_chat(message, msg_sensordata_removed() % devnum)
                else:
                    send_chat(message, msg_sensordata_remove_error() % devnum)
            else:
                send_chat(message, msg_need_devnum())

        # Delete sensor records all
        elif cmd[1] == 'removeall' or cmd[1] == 'delall' or cmd[1] == 'deleteall' or cmd[1] == '모두삭제' or cmd[1] == '모두제거':
            # Delete specified device's records
            newtime = -1
            if len(cmd) >= 3:
                # Delete records older than user specified time (specified device)
                # time must be hour unit: delete all older than x hours
                newtime = -1
                if cmd[2].isdigit():
                    tparam = int(cmd[2])
                    newtime = int(time.time() - tparam*60*60*1000)
            # delete from DB
            if t_dev.delete_sensor_all(newtime):
                send_chat(message, msg_every_sensordata_removed())
            else:
                send_chat(message, msg_every_sensordata_remove_error())

        # Show sensor records
        else:
            # extract parameter
            # sensor a b : a=device number, b=count
            count = 1
            if len(cmd) > 2:
                if cmd[2].isdigit():
                    count = int(cmd[2])
                if count > 100 or count < 1:
                    count = 100
            devnum = -1
            if cmd[1].isdigit():
                devnum = int(cmd[1])
            is_avail, infos = t_dev.get_sensor_val(devnum, count)
            msg = ''
            i = 0
            for info in infos:
                itime = time.localtime(info[6])
                msg += "%d-%d %d:%d" % (itime.tm_mon, itime.tm_mday, itime.tm_hour, itime.tm_min)
                msg += " = %d, %d, %d, %d" % (info[0], info[1], info[2], info[3])
                msg += "\n"
                i = i + 1
            if i > 0:
                send_chat(message, msg)
            else:
                send_chat(message, msg_no_matching_result())

    # Get sensor value and return with graph
    elif cmd[0] == 'graph' or cmd[0] == '그래프':
        # extract parameter
        # graph a b : a=device number, b=count
        if len(cmd) < 2:
            return
        count = 10
        if len(cmd) > 2:
            if cmd[2].isdigit():
                count = int(cmd[2])
            if count > 100 or count < 1:
                count = 100
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        is_avail, infos = t_dev.get_sensor_val(devnum, count)
        # making data list
        i = 0
        datas = [[], [], [], []]
        h_labels = []
        prev_d, prev_h, prev_m = 0, 0, 0
        for info in infos:
            itime = time.localtime(info[6])
            if prev_d != itime.tm_mday or prev_h != itime.tm_hour or prev_m != itime.tm_min:
                timestr = "%d-%d %d:%d" % (itime.tm_mon, itime.tm_mday, itime.tm_hour, itime.tm_min)
            else:
                timestr = "%d:%d" % (itime.tm_hour, itime.tm_min)
            prev_d, prev_h, prev_m = itime.tm_mday, itime.tm_hour, itime.tm_min
            datas[0].append(info[0])
            datas[1].append(info[1])
            datas[2].append(info[2])
            datas[3].append(info[3])
            h_labels.append(timestr)
            i = i + 1
        # ready to burn graph
        if i > 0:
            # adjust image size
            width = 500
            height = 375
            if i > 25 and i <= 50:
                width = 1000
                height = 750
            elif i > 50:
                width = 1600
                height = 1200
            # burn graph
            cat1, cat2, devid = t_dev.get_ids_at(devnum)
            fname = 'graph_'+str(cat1)+'_'+str(cat2)+'_'+str(devid)+'.png'
            CairoPlot.dot_line_plot(graph_dir + fname,
                    datas, width, height,
                    h_labels = h_labels, v_labels = [],
                    axis = True, grid = True, dots = True)
            try:
                # Send graph
                pic_file = open(graph_dir + fname, 'rb')
                ret_msg = send_photo(message, pic_file)
            except:
                send_chat(message, msg_cannot_open_graph())
        else:
            send_chat(message, msg_no_matching_result())

    # Sends data to remote
    elif cmd[0] == 'ctrl' or cmd[0] == 'control' or cmd[0] == 'send' or cmd[0] == '제어' or cmd[0] == '전송':
        # extract parameter
        # send a data1 data2 data3 data4 : a=device number, data1 ~ data4: data to send to remote
        if len(cmd) < 3:
            return
        devnum = -1
        if cmd[1].isdigit():
            devnum = int(cmd[1])
        else:
            send_chat(message, msg_wrong_device())
            return;
        # get device info
        device = t_dev.get_device_at(devnum)
        if len(device) < 1:
            send_chat(message, msg_wrong_device())
            return;
        data1 = 0
        # we have to catch the exception: negative value
        if cmd[2][0] == '-' and cmd[2][1:].isdigit():
            data1 = int(Decimal(cmd[2]))
        elif cmd[2].isdigit():
            data1 = int(cmd[2])
        else:
            send_chat(message, msg_wrong_param1())
            return;
        data2 = 0
        if len(cmd) > 3 and cmd[3][0] == '-' and cmd[3][1:].isdigit():
            data2 = int(Decimal(cmd[3]))
        elif len(cmd) > 3 and cmd[3].isdigit():
            data2 = int(cmd[3])
        else:
            data2 = 0
        data3 = 0
        if len(cmd) > 4 and cmd[4][0] == '-' and cmd[4][1:].isdigit():
            data3 = int(Decimal(cmd[4]))
        elif len(cmd) > 4 and cmd[4].isdigit():
            data3 = int(cmd[4])
        else:
            data3 = 0
        data4 = 0
        if len(cmd) > 5 and cmd[5][0] == '-' and cmd[5][1:].isdigit():
            data4 = int(Decimal(cmd[5]))
        elif len(cmd) > 5 and cmd[5].isdigit():
            data4 = int(cmd[5])
        else:
            data4 = 0
        # send device control signal to remote
        t_ser.send_control_signal(device[1], device[2], device[3], data1, data2, data3, data4)
        send_chat(message, msg_sent_signal() % devnum)

    # Make notification setting
    elif cmd[0] == 'noti' or cmd[0] == 'notification' or cmd[0] == '알림':
        # Show current notifications
        if len(cmd) < 2:
            strmsg = ''
            notis = t_dev.get_noti_list()
            count = 0
            for noti in notis:
                strmsg += msg_noti() + ' ID = ' + str(noti[0]) + '\n'
                #strmsg += noti[13] + '\n'
                strmsg += msg_category() + "1=" + str(noti[1])
                strmsg += ", " + msg_category() + "2=" + str(noti[2])
                strmsg += ", ID=" + str(noti[3]) + "\n" + "if "
                tmpcount = 0
                if noti[4] > 0:
                    strmsg += "Data1 "
                    strmsg += get_comp_operator(noti[4]) + " "
                    strmsg += str(noti[8]) + "\n"
                    tmpcount += 1
                if noti[5] > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data2 "
                    strmsg += get_comp_operator(noti[5]) + " "
                    strmsg += str(noti[9]) + "\n"
                    tmpcount += 1
                if noti[6] > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data3 "
                    strmsg += get_comp_operator(noti[6]) + " "
                    strmsg += str(noti[10]) + "\n"
                    tmpcount += 1
                if noti[7] > 0:
                    if tmpcount > 0:
                        strmsg += "and "
                    strmsg += "Data4 "
                    strmsg += get_comp_operator(noti[7]) + " "
                    strmsg += str(noti[11]) + "\n"
                    tmpcount += 1
                count += 1
                strmsg += '\n'
            if count > 0:
                send_chat(message, strmsg)
            else:
                send_chat(message, msg_no_noti())
            # End of 'noti' command
            return

        # Delete notification
        elif cmd[1] == 'delete' or cmd[1] == 'del' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) < 3:
                send_chat(message, msg_type_noti_del_param())
                return
            else:
                if len(cmd) == 3 and cmd[2].isdigit():
                    # delete with noti-ID
                    noti_id = int(cmd[2])
                    if t_dev.delete_noti_with_id(noti_id):
                        send_chat(message, msg_noti_del_success())
                    else:
                        send_chat(message, msg_noti_del_fail())
                    return
                elif len(cmd) == 5 and cmd[2].isdigit() and cmd[3].isdigit() and cmd[4].isdigit():
                    # delete with device parameters
                    cat1 = int(cmd[2])
                    cat2 = int(cmd[3])
                    devid = int(cmd[4])
                    if t_dev.delete_noti_with_param(cat1, cat2, devid):
                        send_chat(message, msg_noti_del_success())
                    else:
                        send_chat(message, msg_noti_del_fail())
                    return
                else:
                    # delete with name
                    noti_name = ''
                    for index in range(2, len(cmd)):
                        noti_name += cmd[index]
                    if t_dev.delete_noti_with_name(noti_name):
                        send_chat(message, msg_noti_del_success())
                    else:
                        send_chat(message, msg_noti_del_fail())
                    return

        # Add notification
        elif cmd[1] == 'add' or cmd[1] == '추가':
            if len(cmd) < 4:
                send_chat(message, msg_add_noti_param())
                return
            devnum = -1
            if cmd[2].isdigit():
                devnum = int(cmd[2])
            else:
                send_chat(message, msg_add_noti_param())
                return
            # search device info
            cat1, cat2, devid = t_dev.get_ids_at(devnum)
            if cat1 < 0 or cat2 < 0 or devid < 0:
                send_chat(message, msg_wrong_device())
                return
            noti = []
            noti.append(-1)
            noti.append(cat1)
            noti.append(cat2)
            noti.append(devid)

            datanum1, datanum2, datanum3, datanum4 = 0,0,0,0
            compcode1, compcode2, compcode3, compcode4 = 0,0,0,0
            targetnum1, targetnum2, targetnum3, targetnum4 = 0,0,0,0
            pcount = 0
            # parse data1
            datanum, compcode, targetnum = parse_comp_str(cmd[3])
            if datanum < 1 or compcode < 1:
                # send_chat(message, msg_add_noti_param()+' (data1 error)')
                pass
            elif datanum == 1:
                compcode1 = compcode
                targetnum1 = targetnum
                pcount += 1
            elif datanum == 2:
                compcode2 = compcode
                targetnum2 = targetnum
                pcount += 1
            elif datanum == 3:
                compcode3 = compcode
                targetnum3 = targetnum
                pcount += 1
            elif datanum == 4:
                compcode4 = compcode
                targetnum4 = targetnum
                pcount += 1
            # parse data2
            if len(cmd) > 4:
                datanum, compcode, targetnum = parse_comp_str(cmd[4])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data2 error)')
                    pass
                elif datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            # parse data3
            if len(cmd) > 5:
                datanum, compcode, targetnum = parse_comp_str(cmd[5])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data4 error)')
                    pass
                elif datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            # parse data4
            if len(cmd) > 6:
                datanum, compcode, targetnum = parse_comp_str(cmd[6])
                if datanum < 1 or compcode < 1:
                    # send_chat(message, msg_add_noti_param()+' (data4 error)')
                    pass
                if datanum == 1:
                    compcode1 = compcode
                    targetnum1 = targetnum
                    pcount += 1
                elif datanum == 2:
                    compcode2 = compcode
                    targetnum2 = targetnum
                    pcount += 1
                elif datanum == 3:
                    compcode3 = compcode
                    targetnum3 = targetnum
                    pcount += 1
                elif datanum == 4:
                    compcode4 = compcode
                    targetnum4 = targetnum
                    pcount += 1
            if pcount < 1:
                send_chat(message, msg_invalid_noti_cmd())
                return
            # assign parsed parameters
            noti.append(compcode1)
            noti.append(compcode2)
            noti.append(compcode3)
            noti.append(compcode4)
            noti.append(targetnum1)
            noti.append(targetnum2)
            noti.append(targetnum3)
            noti.append(targetnum4)
            noti.append(int(time.time()))
            cur = time.localtime()
            noti.append('Noti' + str(cur.tm_mon) + str(cur.tm_mday) + str(cur.tm_hour) + str(cur.tm_min) + str(cur.tm_sec))
            # push to DB and cached list
            if t_dev.add_noti(noti):
                send_chat(message, msg_add_noti_success())
            else:
                send_chat(message, msg_add_noti_failed())
        # Invalid notification command
        else:
            send_chat(message, msg_invalid_noti_cmd())

    # Make macro
    elif cmd[0] == 'macro' or cmd[0] == '매크로':
        # Show macro list
        if len(cmd) < 2:
            strmsg = ''
            macros = t_dev.get_macro_list()
            count = 0
            for macro in macros:
                strmsg += msg_macro() + ' ID = ' + str(macro[0]) + '\n'
                strmsg += '-> If ' + msg_noti() + ' ID = ' + str(macro[1]) + ', Do : '
                strmsg += macro[6] + '\n'
                count += 1
            if count > 0:
                send_chat(message, strmsg)
            else:
                strmsg += '\n'
                send_chat(message, msg_no_macro())
            # End of 'macro' command
            return

        # Delete notification
        elif cmd[1] == 'delete' or cmd[1] == 'del' or cmd[1] == '삭제' or cmd[1] == '제거':
            if len(cmd) < 3:
                send_chat(message, msg_type_macro_del_param())
                return
            else:
                if len(cmd) == 3 and cmd[2].isdigit():
                    # delete with macro-ID
                    macro_id = int(cmd[2])
                    if t_dev.delete_macro_with_id(macro_id):
                        send_chat(message, msg_macro_del_success())
                    else:
                        send_chat(message, msg_macro_del_fail())
                    return
                elif len(cmd) == 5 and cmd[2].isdigit() and cmd[3].isdigit() and cmd[4].isdigit():
                    # delete with device parameters
                    cat1 = int(cmd[2])
                    cat2 = int(cmd[3])
                    devid = int(cmd[4])
                    if t_dev.delete_macro_with_param(cat1, cat2, devid):
                        send_chat(message, msg_macro_del_success())
                    else:
                        send_chat(message, msg_macro_del_fail())
                    return
                else:
                    # cannot delete macro
                    send_chat(message, msg_macro_del_fail())
                    return

        # Add notification
        elif cmd[1] == 'add' or cmd[1] == '추가':
            if len(cmd) < 4:
                send_chat(message, msg_add_macro_param())
                return
            noti_num = -1
            if cmd[2].isdigit():
                noti_num = int(cmd[2])
            else:
                send_chat(message, msg_add_macro_param())
                return
            # search device info
            noti = t_dev.get_noti_with_id(noti_num)
            if len(noti) < 1:
                send_chat(message, msg_invalid_noti_id())
                return
            cat1 = noti[1]
            cat2 = noti[2]
            devid = noti[3]
            if cat1 < 0 or cat2 < 0 or devid < 0:
                send_chat(message, msg_wrong_device())
                return
            str_cmd = ""
            for index in range(3, len(cmd)):
                str_cmd += cmd[index] + ' '
            str_cmd.strip()
            a_macro = []
            a_macro.append(-1)      # id
            a_macro.append(noti_num)# noti id
            a_macro.append(cat1)    # cat1
            a_macro.append(cat2)    # cat2
            a_macro.append(devid)  # device ID
            a_macro.append(time.time())  # updated
            a_macro.append(str_cmd) # command
            if t_dev.add_macro(a_macro):
                send_chat(message, msg_add_macro_success())
            else:
                send_chat(message, msg_add_macro_fail())

    # End of echo_all(message)
    pass
Пример #14
0
import CairoPlot
import cairo
import math

#Function Plot
#test1
data = lambda x: math.sin(0.1 * x) * math.cos(x)
CairoPlot.function_plot('function1',
                        data,
                        800,
                        300,
                        grid=True,
                        dots=True,
                        h_bounds=(0, 80),
                        step=0.9,
                        discrete=True)

#test2
CairoPlot.function_plot('function2',
                        data,
                        800,
                        300,
                        grid=True,
                        h_bounds=(0, 80),
                        step=0.9)

#test3
CairoPlot.function_plot('function3',
                        data,
                        800,
                        300,
Пример #15
0
chart_type = args[0]
variable_x = args[1]
variable_y = args[2]
file_name = args[3]

pipein = sys.stdin.read().splitlines()
lines = oosh.get_from_pipe(pipein)

if chart_type == 'pie':
    pie_data = {}
    for line in lines:
        name = line[variable_x]
        value = int(float(line[variable_y]))
        if value > 0:
            pie_data[name] = value
    CairoPlot.pie_plot(file_name, pie_data, 800, 600, shadow=True)

elif chart_type == 'bar':
    bar_data = {}
    data = []
    labels = []
    for line in lines:
        name = line[variable_x]
        value = float(line[variable_y])
        if value > 0:
            labels.append(name)
            data.append(value)
    CairoPlot.bar_plot (file_name, data, 800, 600, border=20, grid=True,
                        rounded_corners=True, h_labels=labels) 

Пример #16
0
def main():
     x_size = 2880
     y_size = 700
     
     parser = OptionParser()
     parser.add_option("-f", "--file", dest="filename",
                       help="input data file")
     parser.add_option("-o", "--output", dest="chartname",
                       help="output chart file")
     parser.add_option("-s", "--size", dest="size",
                       help="'xsize,ysize' ")
     parser.add_option("-t", "--type", dest="type",
                       help="'t1,t2,t3' draw type lines")
     (options, args) = parser.parse_args(sys.argv[1:])          
     if (options.filename == None or options.chartname == None):
          parser.print_help()
          sys.exit(1)
     # init x,y size
     if (options.size):
          size = options.size
          xy_pair = size.split(",")
          if len(xy_pair) == 2:
               x_size = string.atoi(xy_pair[0])
               y_size = string.atoi(xy_pair[1])
          else :
               parser.print_help()
               sys.exit(1)
               
     if (options.type):
          val_types = options.type.split(",")
     else:val_types = ["user", "system", "iowait", "nice"] #default
                 
     # ===========input file section=============
     ifile = open(options.filename)
     l = ifile.readline()
     items = l.split()
     if (len(items) == 0):
          print("%s's first line is not title!" % options.filename)
          sys.exit(1)

     empty_data = []
     for x in xrange(1440):
          empty_data.append(0)
     data_map = {}     
     for (num,ite) in enumerate(items):
          data_map[ite] = []

     maxn = 0.0
     while True:
          l = ifile.readline()
          if len(l) == 0:
               break
          line_datas = l.split()

          if (len(line_datas) != len(items) + 1):
               continue
          for (num, key) in enumerate(items):
               for val_t in val_types:
                    if (key.find(val_t) != -1):
                         val = float(line_datas[num+1])
                         data_map[key].append(val)
                         if (val > maxn): maxn = val
     print("max: %f" % maxn)
          # data_map["cpu:%user"].append(float(line_datas[2]) * 100)
          # data_map["net:eth0:out(MB/s)"].append((float(line_datas[24])/1.25))
          # data_map["net:eth0:in(MB/s)"].append((float(line_datas[23])/1.25))
          
     data = { "cpu":[32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
                     37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
                     55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 200, 150],
              "mem": [55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32, 62, 60, 55,
                      32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
                      37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 100]}
     use_data = {}
     for k in data_map.keys():
          for val_t in val_types:
               if (k.find(val_t) != -1):
                    use_data[k] = data_map[k]
                    print("draw key: %s" % k)
     #use_data["net:eth0:out(MB/s)"] = data_map["net:eth0:out(MB/s)"]
     #use_data["net:eth0:in(MB/s)"] = data_map["net:eth0:in(MB/s)"]
     # ==========output file section==========
     h_labs = ["0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00" , "11:00", "12:00", "13:00", "14:00",  "15:00","16:00" ,"17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"]
     v_labs = ["", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%"]
     CairoPlot.dot_line_plot(options.chartname, use_data, x_size, y_size, background = (204,204,204), border = 0,
                             axis = True, grid = True, dots = False, h_labels = h_labs)#, v_labels = v_labs)
Пример #17
0
import sys
sys.path.append("/home/the0project/Desktop/ProjectSimulator/cairo_plot")
sys.path.append("/home/the0project/Desktop/ProjectSimulator/python_db")
import CairoPlot
from db_model import *
import db_connect
import cairo

user = User.objects(email="*****@*****.**").get()
model = Model.objects(driver=user).get()
data = []
for s in model.speed:
    x = float(s.value)
    data.append(x)

CairoPlot.dot_line_plot('example.png',
                        data,
                        2000,
                        2000,
                        axis=True,
                        grid=True,
                        dots='true')
Пример #18
0
import CairoPlot
CairoPlot.dot_line_plot(
    'output/results/graph_cars', [
        2, 2, 7, 8, 1, 4, 2, 13, 0, 3, 10, 2, 1, 8, 0, 0, 2, 0, 5, 0, 3, 7, 7,
        3, 3, 2, 14, 1, 5, 8, 3, 1, 13, 6, 6, 10, 5, 14, 9, 5, 15, 4, 3, 9, 5,
        27, 5, 12, 12, 17
    ],
    400,
    300,
    h_labels=[
        "01/Mar 15:57", "01/Mar 16:14", "01/Mar 16:35", "01/Mar 19:20",
        "01/Mar 19:33", "02/Mar 08:09", "02/Mar 08:20", "02/Mar 08:37",
        "02/Mar 08:48", "02/Mar 08:58", "02/Mar 09:10", "02/Mar 09:27",
        "02/Mar 09:39", "02/Mar 09:52", "02/Mar 10:04", "02/Mar 10:29",
        "02/Mar 10:45", "02/Mar 11:02", "02/Mar 11:14", "02/Mar 11:26",
        "02/Mar 11:38", "02/Mar 11:51", "02/Mar 11:51", "02/Mar 12:05",
        "02/Mar 12:20", "02/Mar 12:40", "02/Mar 12:56", "02/Mar 13:07",
        "02/Mar 13:20", "02/Mar 13:33", "02/Mar 13:49", "02/Mar 16:08",
        "02/Mar 16:19", "03/Mar 13:31", "03/Mar 13:33", "03/Mar 13:38",
        "03/Mar 13:43", "03/Mar 13:50", "03/Mar 13:59", "03/Mar 14:06",
        "03/Mar 14:12", "03/Mar 14:22", "03/Mar 14:29", "03/Mar 14:34",
        "03/Mar 14:40", "03/Mar 14:48", "03/Mar 14:53", "03/Mar 14:57",
        "03/Mar 14:57", "03/Mar 15:36"
    ],
    axis=True,
    grid=True)
Пример #19
0
        a = [u"AAPL", u"SNE", u"MSFT"]

        if ticker in b:
            data[ticker]["%s-%s" % (date, hour)] = item[u'Price/Sales']
        elif ticker in a:
            data[ticker]["%s-%s" % (date, hour)] = item[u'Ask (Real-time)']
        else:
            x = item[u'Last Trade (Real-time) With Time']
            data[ticker]["%s-%s" % (date, hour)] = x.split('<')[1][2:]


    plottable = {}
    for ticker in data:
        dates = sorted(data[ticker])
        plottable[ticker] = []

        for date in dates:
            plottable[ticker].append(float(data[ticker][date]))

    for x in plottable:
        print x
        print plottable[x]
        print '-'*80

    CairoPlot.dot_line_plot("stocks.png",
                            plottable,
                            800,
                            600,
                            axis = True,
                            grid = True)
Пример #20
0
import sys

sys.path.append("/home/the0project/Desktop/ProjectSimulator/cairo_plot")
sys.path.append("/home/the0project/Desktop/ProjectSimulator/python_db")
import CairoPlot
from db_model import *
import db_connect
import cairo

user = User.objects(email="*****@*****.**").get()
model = Model.objects(driver=user).get()
data = []
for s in model.speed:
    x = float(s.value)
    data.append(x)

CairoPlot.dot_line_plot("example.png", data, 2000, 2000, axis=True, grid=True, dots="true")
Пример #21
0
def graph(filename, data, h_labels):
  data = {"objects in memory" : data}
  h_labels = h_labels
  CairoPlot.dot_line_plot(filename, data, 800, 300, 
                          border=20, h_labels=h_labels, 
                          axis=True, grid=True, dots=True)
Пример #22
0
        b = [u"JNJ"]
        a = [u"AAPL", u"SNE", u"MSFT"]

        if ticker in b:
            data[ticker]["%s-%s" % (date, hour)] = item[u'Price/Sales']
        elif ticker in a:
            data[ticker]["%s-%s" % (date, hour)] = item[u'Ask (Real-time)']
        else:
            x = item[u'Last Trade (Real-time) With Time']
            data[ticker]["%s-%s" % (date, hour)] = x.split('<')[1][2:]

    plottable = {}
    for ticker in data:
        dates = sorted(data[ticker])
        plottable[ticker] = []

        for date in dates:
            plottable[ticker].append(float(data[ticker][date]))

    for x in plottable:
        print x
        print plottable[x]
        print '-' * 80

    CairoPlot.dot_line_plot("stocks.png",
                            plottable,
                            800,
                            600,
                            axis=True,
                            grid=True)
Пример #23
0
import CairoPlot
import cairo
import math

#Function Plot
#test1
data = lambda x : math.sin(0.1*x)*math.cos(x)
CairoPlot.function_plot('function1', data, 800, 300, grid = True, dots = True, h_bounds=(0,80), step = 0.9, discrete = True)

#test2
CairoPlot.function_plot('function2', data, 800, 300, grid = True, h_bounds=(0,80), step = 0.9)

#test3
CairoPlot.function_plot('function3', data, 800, 300, grid = True, h_bounds=(0,80), step = 0.1)

#test4
data = lambda x : x**2
CairoPlot.function_plot('function4', data, 400, 300, grid = True, h_bounds=(-10,10), step = 0.1)

#Bar Plot
#test1
data = {'teste00' : [27], 'teste01' : [10], 'teste02' : [18], 'teste03' : [5], 'teste04' : [1], 'teste05' : [22], 'teste06' : [31], 'teste07' : [8]}
CairoPlot.bar_plot ('bar1', data, 400, 300, border = 20, grid = True, rounded_corners = False)

#test2
data = [3,1,10,2]
CairoPlot.bar_plot ('bar2.png', data, 300, 300, border = 20, grid = True, rounded_corners = True)

#test3
data = [[1.4, 3, 11], [8, 9, 21], [13, 10, 9], [2, 30, 8]]
h_labels = ["group1", "group2", "group3", "group4"]
Пример #24
0
   if name == "Unincorporated Gilpin County":
       name = "Uninc. Gilpin County"
   else:
       pass
   if name == "Unincorporated Jefferson County":
       name = "Uninc. Jefferson County" 
   else:
       pass
   
   series_labels = [name, "Region"]
   colors = ["light_blue", "Navy" ]
   data = [[other, reg_other], [wttw, reg_wttw], [bus, reg_bus], [man, reg_man], [perserv, reg_perserv], [ps, reg_ps], [pa, reg_pa], [retail, reg_retail], [uc, reg_uc], [exa, reg_exa]]
  
   #x_labels = [ "line1", "line2", "line3", "line4", "line5", "line6" ]
   #background = (1.0,0.0,1.0,1.0)
   y_labels = [ "Other", "Wholesale Trade", "Business Services", "Manufacturing", "Personal Services", "Professional Services", "Public Administration", "Retail Trade", "Utilities & Construction", "Extractive Activities" ]
 
   CairoPlot.horizontal_bar_plot (  '/home/michael/Documents/comm_prof/emp_by_ind/'+name+'.pdf', data, 380, 230, background = "white",border = 20,  display_values = True, grid = False, y_labels = y_labels, series_labels = series_labels, colors = colors, value_formatter = lambda x: makepercent_nodata(x))
 
#series_labels = series_labels
#value_formatter = lambda x: addcomma(x) 
   #'smb://cognet%2Fmtafel@kennedy/crs/Community%20Profiles_2010_2011/charts/hh_type'+name+'hh_type.png'
   # '/home/michael/Documents/comm_prof/hh_type/'
 
    
      #x_labels = x_labels
 # plt.savefig("/home/michael/Pictures/"+name+"_household.png")



Пример #25
0
import CairoPlot
import cairo

data = [1,3,3,2,4,5,6,7,12,7,3,1,2,3,4,6,7,8]

CairoPlot.dot_line_plot('example.png', data, 700, 700, axis=True, grid=True, dots='true')
Пример #26
0
def main():
    x_size = 2880
    y_size = 700

    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename", help="input data file")
    parser.add_option("-o",
                      "--output",
                      dest="chartname",
                      help="output chart file")
    parser.add_option("-s", "--size", dest="size", help="'xsize,ysize' ")
    parser.add_option("-t",
                      "--type",
                      dest="type",
                      help="'t1,t2,t3' draw type lines")
    (options, args) = parser.parse_args(sys.argv[1:])
    if (options.filename == None or options.chartname == None):
        parser.print_help()
        sys.exit(1)
    # init x,y size
    if (options.size):
        size = options.size
        xy_pair = size.split(",")
        if len(xy_pair) == 2:
            x_size = string.atoi(xy_pair[0])
            y_size = string.atoi(xy_pair[1])
        else:
            parser.print_help()
            sys.exit(1)

    if (options.type):
        val_types = options.type.split(",")
    else:
        val_types = ["user", "system", "iowait", "nice"]  #default

    # ===========input file section=============
    ifile = open(options.filename)
    l = ifile.readline()
    items = l.split()
    if (len(items) == 0):
        print("%s's first line is not title!" % options.filename)
        sys.exit(1)

    empty_data = []
    for x in xrange(1440):
        empty_data.append(0)
    data_map = {}
    for (num, ite) in enumerate(items):
        data_map[ite] = []

    maxn = 0.0
    while True:
        l = ifile.readline()
        if len(l) == 0:
            break
        line_datas = l.split()

        if (len(line_datas) != len(items) + 1):
            continue
        for (num, key) in enumerate(items):
            for val_t in val_types:
                if (key.find(val_t) != -1):
                    val = float(line_datas[num + 1])
                    data_map[key].append(val)
                    if (val > maxn): maxn = val
    print("max: %f" % maxn)
    # data_map["cpu:%user"].append(float(line_datas[2]) * 100)
    # data_map["net:eth0:out(MB/s)"].append((float(line_datas[24])/1.25))
    # data_map["net:eth0:in(MB/s)"].append((float(line_datas[23])/1.25))

    data = {
        "cpu": [
            32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34,
            37, 37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62,
            60, 55, 55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 200,
            150
        ],
        "mem": [
            55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32, 62, 60,
            55, 32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34,
            34, 37, 37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 100
        ]
    }
    use_data = {}
    for k in data_map.keys():
        for val_t in val_types:
            if (k.find(val_t) != -1):
                use_data[k] = data_map[k]
                print("draw key: %s" % k)
    #use_data["net:eth0:out(MB/s)"] = data_map["net:eth0:out(MB/s)"]
    #use_data["net:eth0:in(MB/s)"] = data_map["net:eth0:in(MB/s)"]
    # ==========output file section==========
    h_labs = [
        "0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00",
        "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00",
        "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"
    ]
    v_labs = [
        "", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%"
    ]
    CairoPlot.dot_line_plot(options.chartname,
                            use_data,
                            x_size,
                            y_size,
                            background=(204, 204, 204),
                            border=0,
                            axis=True,
                            grid=True,
                            dots=False,
                            h_labels=h_labs)  #, v_labels = v_labs)