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.