Beispiel #1
0
def export_to_video(sketch_name, frame_rate, output, clean_after):
    """
    Export frames from sketch to a MP4 video
    """
    sketch_dir = SKETCH_DIR.child(sketch_name)

    if not sketch_dir.exists():
        cprint.err(f"There's no directory for the sketch {sketch_name}", interrupt=True)

    output = output or sketch_dir.child('output.mp4')
    cprint.info(f"Generating {output} from sketch sketch_name")
    query = sketch_dir + "/*.png"
    command = ' '.join([str(c) for c in [
        'ffmpeg', '-framerate', frame_rate, '-pattern_type', 'glob', '-i', query, '-c:v', 'libx264', '-r', frame_rate, '-pix_fmt', 'yuv420p', output
    ]])

    cprint.info(f"Command:\n\t$ {command}")

    convert = subprocess.Popen(
        shlex.split(command),
    )
    convert.wait()

    if clean_after:
        pngs = sketch_dir.listdir("*.png")
        cover = random.choice(pngs)
        cover.rename("cover.png")
        for png in pngs:
            png.remove()
Beispiel #2
0
async def interact(conn, svr, connector, method, args, verbose=False):
    try:
        await connector
    except Exception as e:
        print("Unable to connect to server: %s" % e)
        return -1

    cprint.info("\nConnected to: %s\n" % svr)

    if verbose:
        donate = await conn.RPC('server.donation_address')
        if donate:
            cprint.info("Donations: " + donate)

        motd = await conn.RPC('server.banner')
        cprint.info("\n---\n%s\n---" % motd)

    # XXX TODO do a simple REPL here

    if method:
        cprint.warn("\nMethod: %s" % method)

    # risky type cocerce here
    args = [(int(i) if i.isdigit() else i) for i in args]

    try:
        rv = await conn.RPC(method, *args)
        cprint.ok(json.dumps(rv, indent=1))
    except ElectrumErrorResponse as e:
        cprint.err(e)

    conn.close()
Beispiel #3
0
def log(
):  #https://stackoverflow.com/questions/33754670/calculate-logarithm-in-python
    import math
    while True:
        base = input(
            _("What base would you like to use? \nCurrently supported: 10 (base 10), e (natural)"
              ))
        if base == "10":
            cprint.info(_("Using base 10"))
            number = int(input(_("What is the number? ")))
            cprint.info(_("That equals:"))
            cprint.info(math.log10(number))
            logging.info(
                "User used base 10 logarithm with number %s, getting a result of %s"
                % (number, (math.log10(number))))
            break
        elif base.lower() == "e":
            cprint.info(_("Using natural logarithm"))
            number = int(input(_("What is the number? ")))
            cprint.info("That equals...")
            cprint.info(math.log(number))
            logging.info(
                "User used natural logarithm with number %s, getting a result of %s"
                % (number, (math.log(number))))
            break
        else:
            cprint.err(_("The logarithm you typed is not available."))
            cprint.ok(_("Try again."))
            logging.info(
                "User attempted to use a logarithm that is unavailable.")
Beispiel #4
0
 def __transfer_accident_data(self, tablename):
     """Функция следит за данными если время пришло усредняет их или если произошла авария """
     f = '%Y-%m-%d %H:%M:%S'
     self.__transfer_data(tablename)
     # если время вышло и была активна ошибка то переносим данные
     if (type(self.__accident_end_time) == type(datetime.datetime.now())
             and self.__accident_end_time < datetime.datetime.now()
             and self.__accident_temp == 1):
         self._try_to_connect_db()
         totalsec_start = self.__accident_start_time.strftime(f)
         totalsec_end = self.__accident_end_time.strftime(f)
         self._c.execute(
             '''INSERT  INTO  mvlab_''' + tablename + ''' (now_time, value)
              SELECT now_time, value FROM mvlab_temp_''' + tablename +
             ''' WHERE
              "now_time">= %s AND 
              "now_time"< %s  ;''', [totalsec_start, totalsec_end])
         try:
             self._conn.commit()
         except Exception as e:
             cprint.err('error переноса данных: %s' % e)
         self._c.execute(
             '''DELETE FROM mvlab_temp_''' + tablename + ''' WHERE
                          "now_time" >= %s AND 
                          "now_time" < %s  ;''',
             [totalsec_start, totalsec_end])
         try:
             self._conn.commit()
             self.__accident_temp = 0
             self.__accident_start_time = 0
             self.__accident_end_time = 0
             self._conn.close()
         except Exception as e:
             cprint.err('error переноса данных: %s' % e)
Beispiel #5
0
 def _try_to_connect_db(self):
     """Connected to DB"""
     try:
         self._conn = createConnection()
         self._c = self._conn.cursor()
     except:
         cprint.err('error connection to DB for ', interrupt=False)
Beispiel #6
0
def transcrypt_sketch(sketch_name, sketch_dir, pyp5js):
    """
    Command to generate the P5.js code for a python sketch

    Params:
    - sketch_name: name of the sketch (will create a {sketch_name}.py)

    Opitionals
    - sketch_dir: sketch's directory (defaults to ./{sketch_name})
    - pyp5hs: path to the pyp5js main file (defaults to local install)
    """
    SKETCH_DIR = Path(sketch_dir or f'./{sketch_name}')
    if not SKETCH_DIR.exists():
        cprint.warn(f"Couldn't find the sketch.")
        cprint.err(f"The directory {SKETCH_DIR} doesn't exist.",
                   interrupt=True)

    sketch = SKETCH_DIR.child(f"{sketch_name}.py")
    pyp5js = Path(pyp5js or PYP5_DIR)

    command = ' '.join([
        str(c)
        for c in ['transcrypt', '-xp', pyp5js, '-b', '-m', '-n', sketch]
    ])
    cprint.info(f"Command:\n\t {command}")

    transcrypt = subprocess.Popen(shlex.split(command))
    transcrypt.wait()
Beispiel #7
0
def monitor_sketch(sketch_name, sketch_dir):
    """
    Monitor for any change in any .py code under
    the sketch dir and, for every new change,
    runs the transcrypt to update the js files.

    :param sketch_name: name for new sketch
    :type sketch_name: string
    :param sketch_dir: directory name
    :type sketch_dir: string
    :return: file names
    :rtype: list of strings
    """

    sketch_files = Pyp5jsSketchFiles(sketch_dir, sketch_name)
    if not sketch_files.check_sketch_exists():
        cprint.err(f"Couldn't find {sketch_name}", interrupt=True)

    cprint(
        f"Monitoring for changes in {sketch_files.sketch_dir.absolute()}...")

    try:
        monitor_sketch_service(sketch_files)
    except KeyboardInterrupt:
        cprint.info("Exiting monitor...")
Beispiel #8
0
def read_json_data(json_filename):
    path = Path(DATA_DIR.child(f'{json_filename}.json'))

    if not path.exists():
        cprint.err(f"JSON file {path} does not exists.", True)

    with open(path) as fd:
        return json.load(fd)
Beispiel #9
0
 def bind_error_function(self, data, c) -> None:
     """Метод для опредления необходимо ли отслеживание аварии для переменной. Происходит расчет начала и конца временного периода аварии"""
     self.__accident_last = self.__accident
     if 'byte_bind' in c:
         self.__accident = int(
             self.transform_data_to_bit(offset=int(c['byte_bind']),
                                        bit=int(c['bit_bind']),
                                        data=data))
         if self.__accident == 0:
             try:
                 _conn = createConnection()
                 _c = _conn.cursor()
                 _c.execute(
                     f"""UPDATE mvlab_alarms SET status = 0, end_time = '{str(datetime.datetime.now())}' 
                  WHERE status=1 and text_alarm ='останов машин'""")
                 _conn.commit()
                 _conn.close()
             except:
                 cprint.err('Error update records alarm')
         # проверяем происходило ли событие до этого
         if self.__accident == 1 and self.__accident_last != self.__accident:
             self.__accident_temp = self.__accident
             if self.__accident_start_time == 0:
                 #  если событие происходит в первый раз то сохраняем с какого периода выбрать данные
                 if not self.write_to_db_alert:
                     self.write_to_db_alert = True
                     _conn = createConnection()
                     _c = _conn.cursor()
                     _c.execute(
                         f"""SELECT * FROM mvlab_alarms WHERE status=1 and text_alarm='останов машин'"""
                     )
                     records = _c.fetchall()
                     if len(records) <= 0:
                         _c.execute(
                             '''INSERT INTO mvlab_alarms''' \
                             """ (text_alarm, status,type_alarm,object_alarm) VALUES ('останов машин','""" + str(
                                 1) + """','alarm','""" + str(c['name']) + """');""")
                         _conn.commit()
                     _conn.close()
                 self.__accident_start_time = datetime.datetime.now(
                 ) - datetime.timedelta(minutes=self.deleay)
                 self.__accident_end_time = datetime.datetime.now(
                 ) + datetime.timedelta(minutes=self.deleay)
             if self.__accident_last != self.__accident:
                 self.__accident_end_time = datetime.datetime.now(
                 ) + datetime.timedelta(minutes=self.deleay)
         self.__transfer_accident_data(self.c['name'])
     else:
         if (self.__accident_end_time == 0 and not self.transfer_start
                 and self.__accident_start_time == 0
                 and self.__accident_temp == 0
                 and self.__last_update < datetime.datetime.now() -
                 datetime.timedelta(minutes=self.dleay_upd)):
             # self.__transfer_data(self.c['name'])
             x = threading.Thread(target=self.__transfer_data,
                                  args=(self.c['name'], ))
             x.start()
             self.transfer_start = True
Beispiel #10
0
def main():
    global pr
    global data_for_restart
    while True:
        list_connections = get_list_connections()
        statuses_connection = mp.Array('i', [0 for i in list_connections])
        count = 0
        for connection in list_connections:
            try:
                time.sleep(1)
                pr[connection['name']] = StartProcessOpcForConnectToPLC(
                    connection['ip'],
                    connection['rack'],
                    connection['slot'],
                    connection['DB'],
                    connection['start'],
                    connection['offset'],
                    values_list=connection['value_list'],
                    name_connect=connection['name'],
                    status=statuses_connection,
                    count=count)
                data_for_restart[connection['name']] = {
                    "ip": connection['ip'],
                    "rack": connection['rack'],
                    "slot": connection['slot'],
                    "DB": connection['DB'],
                    "start": connection['start'],
                    "offset": connection['offset'],
                    'values_list': connection['value_list'],
                    'count': count,
                    'name': connection['name']
                }
                count += 1
                pr[connection['name']].start()
            except:
                cprint.err('Not start process %s' % connection['name'])
        # start_socket()
        while True:
            for p in pr:
                restart_process_if_not_alive(p)
                print(pr[p].is_alive(), 'process', p)
            for a in statuses_connection:
                for index, (value1, value2) in enumerate(
                        zip(statuses_connection,
                            ses.query(Connections).order_by(Connections.id))):
                    value2.status = value1
                    ses.commit()
            time.sleep(1)
            if list_connections != get_list_connections():
                for i in pr:
                    pr[i].terminate()
                for i in ses.query(Connections).order_by(Connections.id):
                    i.status = None
                    ses.commit()
                pr = {}
                data_for_restart = {}
                break
Beispiel #11
0
def update_index_with_sketch(sketch_name, title, cover, pyp5js):
    """
    Updates index.html with new the new sketch
    """
    sketch_dir = SKETCH_DIR.child(sketch_name)

    if not sketch_dir.exists():
        cprint.err(f"There's no directory for the sketch {sketch_name}", interrupt=True)

    desc, desc_ptbr = '', ''
    while not desc:
        desc = input("Enter with sketch's description: ").strip()
    while not desc_ptbr:
        desc_ptbr = input("Entre com a descrição do sketch (PT-BR): ").strip()

    title = title or f'#{sketch_name}'
    if pyp5js:
        template = templates.get_template('new_pyp5js_entry_snippet.html')
    else:
        template = templates.get_template('new_entry_snippet.html')

    today = date.today()
    ctx = {
        'sketch_id': sketch_name,
        'title': title,
        'cover': cover,
        'sketch_date': f'{today:%m/%d/%Y}',
        'description': desc,
    }

    content = template.render(ctx)
    index_template = templates.get_template('index_base.html')
    new_index_content = index_template.render(new_sketch_content=content)

    with open(SKETCH_DIR.child('index.html'), 'w') as fd:
        fd.write(new_index_content)

    content = template.render(ctx)
    index_template = templates.get_template('index_base.html')
    base_index_content = index_template.render(new_sketch_content='{{ new_sketch_content }}\n\n' + content)

    with open(TEMPLATES_DIR.child('index_base.html'), 'w') as fd:
        fd.write(base_index_content)

    cprint.ok("\nTweet content:")
    tweet_template = templates.get_template('tweet_template.txt')
    ctx = {
        'eng_desc': desc,
        'pt_desc': desc_ptbr,
        'name': sketch_name,
        'pyp5js': pyp5js,
    }
    content = tweet_template.render(**ctx)
    cprint.ok(content)
def div(): #division
    n1, n2 = getNum()
    try:
        cprint.info(_("\nThat equals...\n%s" % (n1 / n2)))
        logging.info("User divvied %s by %s, getting a result of %s" % (n1, n2, (n1 / n2)))
    except ZeroDivisionError:
        cprint.err(_("Do not divide by zero!"))
        logging.error("User attempted to divide by zero.")
    except Exception as e:
        cprint.err(_("There was an unknown issue dividing your Numbers..."))
        logging.error("User had an issue divvying up %s by %s (%s)" % (n1,n2,e))
Beispiel #13
0
def get_data_from_plc():
    while True:
        time.sleep(2)
        try:
            data = PlcRemoteUse(PLC_init["address"], PLC_init["rack"], PLC_init["slot"], PLC_init["port"])
            data1 = data.get_dashboard_teldafax_value_power()
            data2 = data.get_status_machine()
            data = {"data1": data1, "data2": data2}
            globals()['result_query'] = data
            _conn = createConnection()
            _c = _conn.cursor()
            _c.execute('''CREATE TABLE IF NOT EXISTS mvlab_status_var \
                                (key serial primary key,now_time TIMESTAMP  WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, \
                                json_text TEXT, status int)''')
            _conn.commit()

            _c.execute('''CREATE TABLE IF NOT EXISTS mvlab_status_connections \
                                            (key serial primary key,now_time TIMESTAMP  WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, \
                                            json_text TEXT, status int)''')
            _conn.commit()
            _c.execute('SELECT * from mvlab_status_var limit 1')
            records = _c.fetchall()
            if len(records)==0:
                _c.execute('''INSERT INTO mvlab_status_var''' \
                    """ (json_text) VALUES  ('""" + str(json.dumps(data)) + """');""")
                _conn.commit()
                #_conn.commit()
            else:
                ts = time.time()
                timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
                _c.execute(f"UPDATE mvlab_status_var SET json_text='{str(json.dumps(data))}', now_time='{timestamp}'")
                _conn.commit()
            # return data
            ss = []
            count = 0
            for d in list_connections:
                ss.append({'connection_name': d['name'], "ip": d['ip'], 'key': count})
                count += 1
            data = json.dumps(ss).encode('utf-8')
            _c.execute('SELECT * from mvlab_status_var limit 1')
            records = _c.fetchall()
            if len(records) == 0:
                _c.execute('''INSERT INTO mvlab_status_connections''' \
                           """ (json_text) VALUES  ('""" + str(data) + """');""")
                _conn.commit()
            else:
                ts = time.time()
                timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
                _c.execute(f"UPDATE mvlab_status_var SET json_text='{data}', now_time='{timestamp}'")
                _conn.commit()
            _conn.close()
        except Exception as e:
            cprint.err(e)
            globals()['result_query'] = [{"error": 0}]
Beispiel #14
0
    def sketch_dir(self):
        sketch_dir = Path(self._sketch_dir)

        if not sketch_dir:
            return sketch_dir.child(f'{self.sketch_name}')

        if self.check_sketch_dir and not sketch_dir.exists():
            cprint.err(f"The directory {sketch_dir} does not exists.",
                       interrupt=True)

        return sketch_dir
Beispiel #15
0
def mod():  #modulo
    try:
        bigger = int(input(_("\nType the first number (greater): ")))
        smaller = int(input(_("Type the second number (smaller): ")))
    except (TypeError, ValueError):
        cprint.err(_("\nError!"))
        cprint.err(_("Invalid input (code 1)\n"))
        logging.error(
            "ERROR: attempted to modulo numbers %s and %s, but errored code 1."
            % (number1, number2))
    if (abs(bigger) < abs(smaller)):
        cprint.err(_("\nError!"))
        cprint.err(
            _("The second number entered is greater than the first number (code 2)\n"
              ))
        logging.error(
            "ERROR: attempted to modulo numbers %s and %s, but errored code 2."
            % (number1, number2))
    else:
        cprint.info(
            _("\nThat equals...\n%s" %
              (bigger - smaller * int(bigger / smaller))))
        logging.info(
            "User attempted to modulo numbers %s and %s, and got result %s" %
            (bigger, smaller, (bigger - smaller * int(bigger / smaller))))
        print()
Beispiel #16
0
def tempCalc():
    hi = int(
        input(
            _('''OPTIONS:
    1 - Farenheit to Celsius
    2 - Celsius to Farenheit
    3 - Farenheit to Kelvin
    4 - Celsius to Kelvin
    5 - Kelvin to Celsius
    6 - Kelvin to Farenheit
Type: ''')))
    if hi == 1:
        hello = float(input(_("Please enter the FAHRENHEIT temperature: ")))
        #howdy = float(input(_("Please enter the CELSIUS temperature: ")))
        yolo = hello - 32
        yolo = yolo * 5 / 9
        cprint.info(_("That equals...\n%s" % yolo))
        logging.info("User did F to C with F=%s, result=%s" % (hello, yolo))
    elif hi == 2:
        howdy = float(input(_("Please enter the CELSIUS temperature: ")))
        yolo = howdy * 9 / 5
        yolo = yolo + 32
        cprint.info(_("That equals...\n%s" % yolo))
        logging.info("User did C to F with C=%s, result=%s" % (howdy, yolo))
    elif hi == 3:
        salut = float(input(_("Please enter the FAHRENHEIT temperature: ")))
        #convert to celsius
        yolo = salut - 32
        yolo = yolo * 5 / 9
        #convert from celsius to kelvin
        yolo = yolo + 273.15
        cprint.info(_("That equals...\n%s" % yolo))
    elif hi == 4:
        howdy = float(input(_("Please enter the CELSIUS temperature: ")))
        yolo = howdy + 273.15  #convert to kelvin
        cprint.info(_("That equals...\n%s" % yolo))
    elif hi == 5:
        ciao = float(input(_("Please enter the KELVIN temperature: ")))
        yolo = ciao - 273.15  #do the opposite of celsius to kelvin
        cprint.info(_("That equals...\n%s" % yolo))
    elif hi == 6:
        ciao = float(input(_("Please enter the KELVIN temperature: ")))
        yolo = ciao - 273.15
        yolo = yolo * 9 / 5
        yolo = yolo + 32
        cprint.info(_("That equals...\n%s" % yolo))
    # TO FIGURE OUT THE FORMULA I JUST GOOGLED 5 ____ TO _____ AND LOOKED AT THE FORMULA IT SHOWS.
    else:
        cprint.err(_("Invalid response."))
        logging.error("User typed invalid temperature answer %s" % hi)
Beispiel #17
0
def configure_new_sketch(sketch_name):
    """
    Create dir and configure boilerplate
    """
    new_dir = SKETCH_DIR.child(sketch_name)
    new_sketch = new_dir.child(f'{sketch_name}.pyde')
    base_sketch = TEMPLATES_DIR.child('base_sketch.pyde')

    if new_dir.exists():
        cprint.err(f"There's already a sketch \"{sketch_name}\"", interrupt=True)

    os.mkdir(new_dir)
    os.mkdir(new_dir.child('results'))
    copyfile(base_sketch, new_sketch)
Beispiel #18
0
def add_to_bd_connections():
    try:
        _conn = createConnection()
        _c = _conn.cursor()
    except:
        cprint.err('error connection to DB for ', interrupt=False)
    _c.execute('''CREATE TABLE IF NOT EXISTS mvlab_connections \
                    (key serial primary key,now_time TIMESTAMP  WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, \
                    json_text TEXT)''')
    _conn.commit()
    res = json.dumps(list_connections)
    _c.execute("""INSERT INTO mvlab_connections (json_text) VALUES ('""" +
               str(res) + """');""")
    _conn.commit()
Beispiel #19
0
def restart_process_if_not_alive(p):
    if (not pr[p].is_alive()):
        cprint.err("restart process %s" % p)
        pr[p].terminate()
        pr[p] = StartProcessOpcForConnectToPLC(
            data_for_restart[p]['ip'],
            data_for_restart[p]['rack'],
            data_for_restart[p]['slot'],
            data_for_restart[p]['DB'],
            data_for_restart[p]['start'],
            data_for_restart[p]['offset'],
            values_list=data_for_restart[p]['values_list'],
            name_connect=data_for_restart[p]['name'],
            status=statuses_connection,
            count=data_for_restart[p]['count'])
Beispiel #20
0
    def sketch_py(self):
        py_file = self.sketch_dir.child(f'{self.sketch_name}.py')

        if self.check_sketch_dir and not py_file.exists():
            cwd_py_file = Path(os.getcwd()).child(f"{self.sketch_name}.py")
            if not cwd_py_file.exists():
                cprint.warn(f"Couldn't find the sketch.")
                cprint.err(
                    f"Neither the file {py_file} or {cwd_py_file} exist.",
                    interrupt=True)

            py_file = cwd_py_file
            self._sketch_dir = py_file.parent

        return py_file
Beispiel #21
0
def start_socket():
    cprint.err('run socket ')
    get_dat_from_plc_thread = threading.Thread(target=get_data_from_plc)
    get_dat_from_plc_thread.start()
    try:
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = '0.0.0.0'
        port = SOCKET_PORT
        conn.settimeout(1)
        conn.connect((host, port))
        conn.close()
        cprint.info("Socket isset")
    except:
        print("run socket server")
        my_thread = threading.Thread(target=listen_server_mvlab)
        my_thread.start()
Beispiel #22
0
def readMyMemory():
    cprint.info(
        _("This is the remember function.\nIt will read a number that was previously stored in a file."
          ))
    try:
        slot = str(int(input(_("What slot number did you use? "))))
        with open(slot, "r") as memory:
            theMem = memory.read()
            cprint.info(_("Number: %s" % theMem))
            logging.info("Retrieved number %s from memory slot %s" %
                         (theMem, slot))
    except Exception as e:
        logging.info(
            "There was an error retrieving the file from memory. (Err %s)" % e)
        cprint.err(
            _("There was an error reading the file. Did you save the number by using the save function? Did you accidentally rename the file?"
              ))
Beispiel #23
0
def _validate_sketch_path(sketch_name=None, sketch_dir=None):
    """
    Searches for the sketch .py file
    """
    sketch_dir = Path(sketch_dir or f'{sketch_name}')

    sketch = sketch_dir.child(f"{sketch_name}.py")
    if not sketch.exists():
        sketch_file = Path(os.getcwd()).child(f"{sketch_name}.py")
        if not sketch_file.exists():
            cprint.warn(f"Couldn't find the sketch.")
            cprint.err(f"Neither the file {sketch} or {sketch_file} exist.",
                       interrupt=True)

        sketch = sketch_file
        sketch_dir = sketch.parent

    return sketch
Beispiel #24
0
def transcrypt_sketch(sketch_name, sketch_dir):
    """
    Transcrypt the sketch python code to javascript.

    :param sketch_name: name for new sketch
    :type sketch_name: string
    :param sketch_dir: directory name
    :type sketch_dir: string
    :return: file names
    :rtype: list of strings
    """

    sketch_files = Pyp5jsSketchFiles(sketch_dir, sketch_name)
    if not sketch_files.check_sketch_exists():
        cprint.err(f"Couldn't find {sketch_name}", interrupt=True)

    compile_sketch_js(sketch_files)
    return sketch_files.index_html
Beispiel #25
0
def new_sketch(sketch_name, sketch_dir):
    """
    Creates a new sketch, on a folder/directory
    with the required assets and a index.html file,
    all based on a template
    
    :param sketch_name: name for new sketch
    :type sketch_name: string
    :param sketch_dir: directory name
    :type sketch_dir: string
    :return: file names
    :rtype: list of strings
    """

    SKETCH_DIR = Path(sketch_dir or f'{sketch_name}')

    if SKETCH_DIR.exists():
        cprint.warn(f"Cannot configure a new sketch.")
        cprint.err(f"The directory {SKETCH_DIR} already exists.",
                   interrupt=True)

    static_dir = SKETCH_DIR.child('static')
    templates_files = [(TEMPLATES_DIR.child('base_sketch.py'),
                        SKETCH_DIR.child(f'{sketch_name}.py')),
                       (PYP5_DIR.child('static',
                                       'p5.js'), static_dir.child('p5.js'))]

    index_template = templates.get_template('index.html')
    context = {
        "p5_js_url": "static/p5.js",
        "sketch_js_url": f"{TARGET_DIRNAME}/{sketch_name}.js",
        "sketch_name": sketch_name,
    }
    index_contet = index_template.render(context)

    os.mkdir(SKETCH_DIR)
    os.mkdir(static_dir)
    for src, dest in templates_files:
        shutil.copyfile(src, dest)

    with open(SKETCH_DIR.child("index.html"), "w") as fd:
        fd.write(index_contet)

    return templates_files[0][1]
Beispiel #26
0
def main():
    count = 0
    for connection in list_connections:
        try:
            time.sleep(3)
            if 'oee' in connection:
                oee = connection['oee']
            else:
                oee = None
            pr[connection['name']] = StartProcessOpcForConnectToPLC(
                connection['ip'],
                connection['rack'],
                connection['slot'],
                connection['DB'],
                connection['start'],
                connection['offset'],
                values_list=connection['value_list'],
                name_connect=connection['name'],
                status=statuses_connection,
                count=count,
                oee=oee)
            data_for_restart[connection['name']] = {
                "ip": connection['ip'],
                "rack": connection['rack'],
                "slot": connection['slot'],
                "DB": connection['DB'],
                "start": connection['start'],
                "offset": connection['offset'],
                'values_list': connection['value_list'],
                'count': count,
                'oee': oee
            }
            count += 1
            pr[connection['name']].start()
        except:
            cprint.err('Not start process %s' % connection['name'])
    start_socket()
    while True:
        for p in pr:
            restart_process_if_not_alive(p)
            print(pr[p].is_alive(), 'process', p)
        for a in statuses_connection:
            print(a)
        time.sleep(1)
Beispiel #27
0
def compile_sketch_js(sketch, target_name):
    sketch_dir = sketch.parent

    command = ' '.join([str(c) for c in [
        'transcrypt', '-xp', PYP5_DIR, '-b', '-m', '-n', sketch
    ]])

    cprint.info(f"Converting Python to P5.js...\nRunning command:\n\t {command}")

    proc = subprocess.Popen(shlex.split(command))
    proc.wait()

    __target = sketch_dir.child('__target__')
    if not __target.exists():
        cprint.err(f"Error with transcrypt: the {__target} directory wasn't created.", interrupt=True)

    target_dir = sketch_dir.child(target_name)
    if target_dir.exists():
        shutil.rmtree(target_dir)
    shutil.move(__target, target_dir)
Beispiel #28
0
    def report(self, filepath):
        if not self.can_report():
            cprint.info(f'not more then {self.interval} minutes')
            return

        logging.info("try to report from " + filepath)
        with open(filepath, 'rb') as fp:
            binary_data = fp.read()
            if not binary_data:
                cprint.err("read image err: " + filepath)
                return

            # not json, but form-data
            # data = {
            #   'images': [base64.encodebytes(binary_data).decode('utf-8')],
            #   "category": "测试",
            #   'street': self.street,
            #   'title': '告警'
            # }
            # encoded_data = json.dumps(data).encode('utf-8')
            # r = self.http.request(
            #   'POST',
            #   self.url,
            #   body=encoded_data,
            #   headers={'Content-Type': 'application/json'}
            # )

            r = self.http.request('POST',
                                  self.url,
                                  fields={
                                      'event[images][]':
                                      ('image.jpg', binary_data),
                                      'event[title]': self.title,
                                      'event[street]': self.street,
                                      'event[category]': self.category
                                  })
            result = r.data
            logging.info("result: " + result.decode("utf-8"))
            self.last_report_time = datetime.datetime.now().time()
Beispiel #29
0
def new_sketch(sketch_name, sketch_dir):
    """
    Creates a new sketch, on a folder/directory
    with the required assets and a index.html file,
    all based on a template

    :param sketch_name: name for new sketch
    :type sketch_name: string
    :param sketch_dir: directory name
    :type sketch_dir: string
    :return: file names
    :rtype: list of strings
    """

    sketch_files = Pyp5jsSketchFiles(sketch_dir,
                                     sketch_name,
                                     check_sketch_dir=False)
    if not sketch_files.can_create_sketch():
        cprint.warn(f"Cannot configure a new sketch.")
        cprint.err(f"The directory {sketch_files.sketch_dir} already exists.",
                   interrupt=True)

    pyp5js_files = Pyp5jsLibFiles()
    templates_files = [
        (pyp5js_files.base_sketch, sketch_files.sketch_py),
        (pyp5js_files.p5js, sketch_files.p5js),
        (pyp5js_files.p5_dom_js, sketch_files.p5_dom_js),
    ]

    os.makedirs(sketch_files.sketch_dir)
    os.mkdir(sketch_files.static_dir)
    for src, dest in templates_files:
        shutil.copyfile(src, dest)

    index_contet = get_index_content(sketch_name)
    with open(sketch_files.index_html, "w") as fd:
        fd.write(index_contet)

    return sketch_files.sketch_py, sketch_files.index_html
Beispiel #30
0
def configure_new_sketch(sketch_name, sketch_dir):
    """
    Create dir and configure boilerplate

    Params:
    - sketch_name: name of the sketch (will create a {sketch_name}.py)

    Opitionals
    - sketch_dir: directory to save the sketch (defaults to ./{sketch_name})
    """
    SKETCH_DIR = Path(sketch_dir or f'./{sketch_name}')
    if SKETCH_DIR.exists():
        cprint.warn(f"Cannot configure a new sketch.")
        cprint.err(f"The directory {SKETCH_DIR} already exists.",
                   interrupt=True)

    static_dir = SKETCH_DIR.child('static')
    templates_files = [(TEMPLATES_DIR.child('base_sketch.py'),
                        SKETCH_DIR.child(f'{sketch_name}.py')),
                       (PYP5_DIR.child('static',
                                       'p5.js'), static_dir.child('p5.js'))]

    os.mkdir(SKETCH_DIR)
    os.mkdir(static_dir)
    for src, dest in templates_files:
        copyfile(src, dest)

    index_template = templates.get_template('index.html')
    context = {
        "p5_js_url": "static/p5.js",
        "sketch_js_url": f"__target__/{sketch_name}.js",
    }
    index_contet = index_template.render(context)

    with open(SKETCH_DIR.child("index.html"), "w") as fd:
        fd.write(index_contet)