quarta-feira, 27 de setembro de 2017

pyserial

You can set timeout = None, then the read call will block until the requested number of bytes are there. If you want to wait until data arrives, just do a read(1) with timeout None. If you want to check data without blocking, do a read(1) with timeout zero, and check if it returns any data



#Modified code from main loop: 
s = serial.Serial(5)

#Modified code from thread reading the serial port
while 1:
  tdata = s.read()           # Wait forever for anything
  time.sleep(1)              # Sleep (or inWaiting() doesn't give the correct value)
  data_left = s.inWaiting()  # Get the number of characters ready to be read
  tdata += s.read(data_left) # Do the read and combine it with the first character

  ... #Rest of the code


you should set the baud rate in your serial.Serial(...) command, otherwise the camera might not recognize whatever command you're sending there. something along the lines of:
cam = serial.Serial("/dev/ttyUSB0", baudrate=9600)
Also, you may specify the timeout as a parameter, with the possible values:
timeout = None: wait forever
timeout = 0: non-blocking mode (return immediately on read)
timeout = x: set timeout to x seconds



#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/COM5"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

import serial

port = serial.Serial("/dev/ttyAMA0", baudrate=115200, timeout=3.0)

while True:
    port.write("\r\nSay something:")
    rcv = port.read(10)
    port.write("\r\nYou sent:" + repr(rcv))


import serial.tools.list_ports
list = serial.tools.list_ports.comports()
connected = []
for element in list:
    connected.append(element.device)
print("Connected COM ports: " + str(connected))

# deu pau por permissao denied
# sudo adduser MyUser dialout
# sudo chmod a+rw /dev/ttyUSB0


ser = serial.Serial(
    port='/dev/ttyUSB0',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
    timeout=0, \
    xonxoff=False, \
    dsrdtr=False, \
    rtscts=False)

print "esta aberto:", ser.is_open
ser.write("\r\nDiga algo:")
rcv = ser.readline()
ser.write("\r\nVoce mandou:" + repr(rcv))












domingo, 27 de agosto de 2017

Python OOP 01

Classe é a estrutura genérica de um objeto.
Atributos são as características do objeto.
Os métodos são as ações que o objeto faz.
Associação é, como o nome já diz, uma associação entre duas classes, uma interação entre eles. Classe humano utilizando da Classe carro.
Polimorfismo é quando uma ação se comporta diferente para cada classe. Classe carro e Classe aviao, ambas se deslocam mas por maneiras diferentes.
Encapsulamento é a forma de exposição dos atributos para quem irá acessá-lo.


sábado, 26 de agosto de 2017

pyinstaller

Cria executável do seu programa python com suas dependências.
pip install pyinstaller
pyinstaller programa.py

  File "/usr/local/lib/python2.7/dist-packages/PyInstaller/building/utils.py", line 466, in format_binaries_and_datas
    src_root_path_or_glob))
PyInstaller.compat.FileNotFoundError: Path or glob "/usr/include/python2.7/pyconfig.h" not found or matches no files.

apt-get install build-essential python-dev










quinta-feira, 24 de agosto de 2017

osgeo4w

Cada programa que usa gdal acaba instalando uma instância do programa pra si. O osgeo4w tenta criar uma unica instancia para todos os programas que utilizam da biblioteca.

http://www.gisinternals.com/release.php

Escolhi: release-1500-gdal-2-2-1-mapserver-7-0-6

Instalado python 2.7.13 - já vem com pip
instalado vcpython27 2014 - Visual C++ for Python 2.7
Instalado numpy via pip install numpy
Instalado gdal-202-1500-core.msi - python 2.7.13 no caso, tem compilação 1500
Instalado GDAL-2.2.1.win32-py27.msi

Adicionado paths:
Novo: 
Nome da variável: GDAL_DATA
Valor da variável: C:\Program Files (x86)\GDAL\gdal-data

Novo:
Nome da variável: GDAL_DRIVER_PATH
Valor da variável: C:\Program Files (x86)\GDAL\gdalplugins

Edit:
Nome da variável: Path
Valor da variavel: adicionar -->    C:\Program Files (x86)\GDAL\
Se colocar no final da linha, tem que ter um ; no inicio: ;C:\Program Files (x86)\GDAL\

Reiniciar a máquina

Testando, ir no prompt de comando e rodar gdalinfo
Aqui deu erro:

ERROR 1: Can't load requested DLL: c:\Program Files\GDAL\gdalplugins\ogr_MSSQLSpatial.dll

Solução: Pode apagar o arquivo ogr_MSSQLSpatial.dll
Mas eu criei uma pasta e coloquei a dll lá dentro, só por precaução, caso precise da dll mais pra frente. Outra opção é instalar o SQL Server Native Client




I find OSGEO4W a poor solution because it creates a whole parallel universe, almost like a virtual machine. I was able to install GDAL and use it in python following the steps outlined here (this is the link provided by @sys49152).
It sends you to gisinternals.com. Take the link to "stable releases" to get to:http://www.gisinternals.com/release.php
Now you have to choose between 32 and 64 bits and different Microsoft Visual C++ compiler versions. Note that this has to match your python version, not your OS. In my case I have a 64 bit windows, but a 32 bit python 2.7 (that shipped with ArcGIS).
To see what you have you can run python on the command line and a message like this:
C:\>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
So I need to use "release-1500"
I selected: MSVC 2013/win32 release-1500-gdal-1-11-3-mapserver-6-4-2
(the build version numbers will change over time)
I first downloaded and installed the "Generic installer for the GDAL core components": gdal-111-1500-core.msi
And added the path and other variables as described here.
Add to path: C:\Program Files (x86)\GDAL Create environmental variables: GDAL_DATA = C:\Program Files (x86)\GDAL\gdal-data GDAL_DRIVER_PATH = C:\Program Files (x86)\GDAL\gdalplugins
Then, I downloaded and installed the python module for python 2.7 GDAL-1.11.3.win32-py2.7.msi
And after that, in python I was able to do
from osgeo import gdal
ds = gdal.Open('file.tif')
etc.

sábado, 5 de agosto de 2017

EPSG Sad69 UTM 22S MC -51


UTM SAD69 22S --> EPSG:29192
WGS84                 --> EPSG:4326
SIRGAS 2000 / UTM zone 23S     ->  EPSG:31983
SIRGAS 2000 -> EPSG:4674

from osgeo import osr

src = osr.SpatialReference()
tgt = osr.SpatialReference()
src.ImportFromEPSG(31983)
tgt.ImportFromEPSG(4674)

transform = osr.CoordinateTransformation(src, tgt)
coords = transform.TransformPoint(580210.101, 7787362.590)
x,y = coords[0:2]

LG X Power

Problemas encontrado

Usando o programa beat! o wifi desconecta em standby e só volta a ligar quando liga-se a tela, e mesmo com a opção de deixar o wifi sempre ligado, ele acaba desligando.

Outro problema é que algumas vezes é necessário clicar duas vezes na tela pra ter resposta. No primeiro toque não pega.

Um outro problema é que vezes ou outra é necessário desmontar o cartão de memória pelo menu, e remontar para voltar a funcionar.

Queda frequente do wifi, desconecta, mas conecta em seguida.

Update: Quanto ao problema do wifi desconectando toda hora, vi em fóruns que o problema pode ser o ipv6, uso o mitrastar dsl-2401hn-t1c-nv que foi instalado pela vivo. O problema é que eles tiraram a opção para desligar o ipv6. Preciso testar com roteador pra ver.

domingo, 16 de julho de 2017

domingo, 9 de julho de 2017

boot cd no pendrive


dd bs=4M if=linuxmint-18.2-xfce-64bit.iso of=/dev/sdb

testar

qemu -hda /dev/sdb

sábado, 8 de julho de 2017

debian bug

Reading package lists... Done
Building dependency tree    
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 python3-pil : Depends: python3-olefile but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).


The following packages will be upgraded:
  python3-gi python3-pil python3-sip
3 upgraded, 1 newly installed, 20 to remove and 242 not upgraded.
8 not fully installed or removed.
Need to get 0 B/958 kB of archives.
After this operation, 65,2 MB disk space will be freed.
Do you want to continue? [Y/n]
Could not find platform independent libraries
Consider setting $PYTHONHOME to [:]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
LookupError: no codec search functions registered: can't find encoding

Current thread 0x00007fafa2631700 (most recent call first):
Aborted
E: Sub-process /usr/bin/apt-listchanges --apt || test $? -lt 10 returned an error code (1)
E: Failure running script /usr/bin/apt-listchanges --apt || test $? -lt 10






apt upgrade
Reading package lists... Done
Building dependency tree       
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 python3-gi-cairo : Depends: python3-gi (= 3.22.0-2+b1) but 3.22.0-2 is installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).




















sábado, 24 de junho de 2017

Permissão no linux

Resumo

d rwx rwx rwx
d: tipo de arquivo (diretório);
rwx: permissões do proprietário e/ou usuário;
rwx : permissões para usuários do mesmo grupo;
rwx: permissões para todos usuários.

Mas o que significa rwx?
r - read (permissão de leitura);
w - write (permissão de escrita);
x - execute (permissão de execução.

0 : --- (nenhuma permissão)
1 : --x (somente execução)
2 : -w- (somente escrita)
3 : -wx (escrita e execução)
4 : r-- (somente leitura)
5 : r-x (leitura e execução)
6 : rw- (leitura e escrita)
7 : rwx (leitura, escrita e execução)

chmod 666 -> dono tem permissão de ler e escrever, usuários do grupo e outros tmb
chmod 664 -> dono tem permissão de ler e escrever, usuários do grupo tmb, outros só leitura.


Fonte: https://www.vivaolinux.com.br/artigo/Entendendo-as-permissoes-de-arquivos-(chmod)



chown -R user:user Música/
chmod 766 Música/ -R

chmod 666 Música/ -R --> dá pau porque diretórios precisam de uma bandeira executável


sexta-feira, 16 de junho de 2017

Debian - locales pt_BR

locale -a
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory
C
C.UTF-8
POSIX


********************

locale-gen
Generating locales (this might take a while)...
  pt_BR.ISO-8859-1...cannot open locale definition file `pt_BR': No such file or directory
 done
  pt_BR.UTF-8...cannot open locale definition file `pt_BR': No such file or directory
 done
Generation complete.

********************

apt-get install --reinstall locales
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  gstreamer1.0-libav*
0 upgraded, 0 newly installed, 1 reinstalled, 1 to remove and 53 not upgraded.
Need to get 3290 kB of archives.
After this operation, 15.3 MB disk space will be freed.
Do you want to continue? [Y/n] 
Get:1 http://ftp.br.debian.org/debian testing/main amd64 locales all 2.24-11 [3290 kB]
Fetched 3290 kB in 1s (1921 kB/s)   
apt-listchanges: Can't set locale; make sure $LC_* and $LANG are correct!
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = "pt_BR:pt:en",
LC_ALL = (unset),
LANG = "pt_BR.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
Preconfiguring packages ...
(Reading database ... 372711 files and directories currently installed.)
Removing gstreamer1.0-libav:amd64 (1:1.10.4-dmo1) ...
(Reading database ... 372681 files and directories currently installed.)
Preparing to unpack .../locales_2.24-11_all.deb ...
Unpacking locales (2.24-11) over (2.24-11) ...
Processing triggers for man-db (2.7.6.1-2) ...
Setting up locales (2.24-11) ...
Generating locales (this might take a while)...
  pt_BR.ISO-8859-1... done
  pt_BR.UTF-8... done
Generation complete.

segunda-feira, 12 de junho de 2017

virtualbox e Debian Host - Pendrive não encontrado

Para funfar o pendrive no guest é preciso adicionar o seu user para o grupo do virtualbox:

usermod -a -G vboxusers seu_usuario

Tem que reiniciar a máquina pra surtir efeito, ou dar um jeito para atualizar as paradas.

sábado, 10 de junho de 2017

Opera 45 e H.264 codec no GNU/Linux Debian Stretch

Parou de funcionar o vídeo no opera, parece ser algum problema com o codec H.264
Vídeos no facebook, por exemplo, não funcionam.

Para testar se tem o suporte para o codec:
https://html5test.com

Pode-se tentar outras versões do libffmpeg.so e colocar na pasta:
/usr/lib/x86_64-linux-gnu/opera

Alguma versão deve funcionar.


Qual a diferença entre eles:
libavcodec-extra* libavcodec-extra57* libx265-95* (remove para instalar audacious)

e

libavcodec57 libavformat57


O flash no Opera diz que pode ser colocado em:
/home/usuario/.local/lib/opera/plugins/


Deu certo com os passos abaixo, se você não consegue reproduzir vídeos no facebook ou outro site:

wget https://repo.herecura.eu/herecura/x86_64/opera-ffmpeg-codecs-58.0.3029.110-1-x86_64.pkg.tar.xz

descompacte o arquivo e ele vai criar a pasta no diretorio que você especificiar: "usr/lib/opera/lib_extra/libffmpeg.so" temos que copiar o libffmpeg.so para a pasta do opera que está instalado no sistema.

copie o libffmpeg.so para a pasta do opera, tem que ser como root:
cp ~/usr/lib/opera/lib_extra/libffmpeg.so    /usr/lib/x86_64-linux-gnu/opera/usr/lib/x86_64-linux-gnu/opera



segunda-feira, 1 de maio de 2017

gvSIG com problema de java 32bits

gvSIG

Error: This Java instance does not support a 32-bit JVM.
Please install the desired version.


/opt/jdk1.8.0_131/bin/java

Descompactar o arquivo e abrir o gvSIG.sh, comentar as linhas

239 #export FORCE_JAVA_32BITS

240 #FORCE_JAVA_32BITS=""
241 #JAVA_HOME_OTHER_ARCHITECTURE=""

Adicionar o path do java


316 if [ "$JAVA_HOME_TO_USE" = "" ] ; then
           # Try to use the java in the system path
           if ! type java >/dev/null ; then
                # java not found in the system path
                if [ "$JAVA_HOME_OTHER_ARCHITECTURE" != "" ] ; then
                        JAVA_HOME="$JAVA_HOME_OTHER_ARCHITECTURE"
                        JAVA="$JAVA_HOME/bin/java"
                        JAVA="/opt/jdk1.8.0_131/bin/java"
                        logger_warn "java $PREFERED_ARCHITECTURE not found in the system path, using $JAVA_HOME_OTHER_ARCHITECTURE"
                else
                        logger_warn "java not found in the system"
                        exit 1
                fi
        else
if [ "$(getJavaArchitecture $(type -p java))" != "$PREFERED_ARCHITECTURE" ] ; then
                      logger_warn "java $PREFERED_ARCHITECTURE not found, using $(type -p java)"
                fi
                unset JAVA_HOME
                JAVA="java"
        fi
else
        JAVA_HOME="$JAVA_HOME_TO_USE"
        #JAVA="$JAVA_HOME/bin/java"
JAVA="/opt/jdk1.8.0_131/bin/java"
fi

Atom Editor + Octave + Script no Debian

Baixar o editor Atom (tem o arquivo .deb)
https://atom.io/

Instalar os pacotes: script e language-matlab 0.2.1
Basta ir em --> Settings --> Na coluna esquerda escolher + Install --> Procurar os pacotes script e language-matlab e instalar

Pode instalar temas também, no lugar de packages basta colocar Themes e procurar. Fica do lado onde você coloca a palavra para busca.

sábado, 22 de abril de 2017

Tomei multa 16/03/2017

Ao exceder o limite em 20%, uma penalidade de R $ 130,16 e 4 pontos na carteira.
Sacanagem, via de 60km/h multado por estar a 63km/h, faltou frear um pouco mais kkkkkk

sexta-feira, 21 de abril de 2017

Meu vivo

Com o chromium recebe-se a msg: Não foi possível realizar o login. Por favor tente novamente mais tarde.

Com o firefox dá certo. Por que será?

Com o firefox, na saraiva, não aparece certo o preço do produto. No chromium aparece.

confusão

Instalando o Java JDK 8 no Debian


 http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html

Fazer o download e descompactar em um diretório. Fiz em /opt
/opt/jdk1.8.0_131



Como root:
update-alternatives --install "/usr/bin/java" "java" "/opt/jdk1.8.0_131/bin/java" 100
update-alternatives --install "/usr/bin/javac" "javac" "/opt/jdk1.8.0_131/bin/javac" 100

Escolha qual java usar com o comando:
update-alternatives --config java

Escolha o jdk que fez o download manual

Para checar:

java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)