顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2020年2月17日 星期一

DMX512 protocol

DMX protocol…
# 1:break + 1:start + 512:channel

python:
import serial

class DMX512:
    def __init__(self, port):
        self.serial = serial.Serial(
        port=port,
        baudrate=250000,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_TWO,
        timeout=0
        )
        self.data=[0]*513   # 513 bytes = 1:start + 512:channel

    def setChannel(self, chan, intensity):
        self.data[chan] = intensity

    def setAll(self,col):
        for i in range(1, 513):
            self.data[i] = col

    def update(self):
        # break use or serial.send_break  or serial.break_condition
        self.serial.send_break(0.0001)  # 100us but not precise on different OSs
        # 513 bytes = 1:start + 512:channel
        self.serial.write(bytes(self.data))

dmx = DMX512( 'COM3' )
dmx.setAll(255)
dmx.update()

stm8s:
====BREAK====:
UART3_Init(
    (u32)45500,
    UART3_WORDLENGTH_9D,
    UART3_STOPBITS_1,
    UART3_PARITY_NO,
    UART3_MODE_TXRX_ENABLE
    );
UART3_SendData9( 0x0100 | 0x00 );

====TX/RX====:
UART3_Init(
    (u32)250000,
    UART3_WORDLENGTH_9D,
    UART3_STOPBITS_1,
    UART3_PARITY_NO,
    UART3_MODE_TXRX_ENABLE
    );
UART3_SendData9( 0x0100 | data ); /// 513 BYTES

====rx====:
u8 dmx_buffer[513];
u16 dmx_buffer_idx; 
BOOL DMX_FLAG = FALSE;
BOOL SC_FLAG = FALSE;

void UART3_RX_IRQHandler( void )
{
    BOOL BREAK_FLAG = FALSE; 
    u8 rx = 0; 

    /// DMX512 = 1:break + 1:start + 512:data
    if(UART3_GetITStatus(UART3_IT_RXNE )!= RESET)
    {
        BREAK_FLAG = UART3_ReceiveData9()>>8;
        rx = UART3_ReceiveData8();

        if(BREAK_FLAG == FALSE) /// 1:break
        {
            if(rx == 0x00)
            {
                SC_FLAG = TRUE;
                return ;           
            }
        }

        if((BREAK_FLAG == TRUE)&&(SC_FLAG == TRUE)) /// 1:start
        {
            SC_FLAG = FALSE;
            if(rx == 0x00)
            {
                DMX_FLAG = TRUE;
            dmx_buffer_idx = 1; /// fill buff start from idx=1
            return;
        }
        }

        if((BREAK_FLAG == TRUE)&&(DMX_FLAG == TRUE)) /// 512:data
        {
            if( dmx_buffer_idx < sizeof(dmx_buffer) )
            {
            dmx_buffer[dmx_buffer_idx] = rx;
                dmx_buffer_idx++;
            }
        }
    }
}

2019年7月18日 星期四

Bluepy Scanner disconnects exist connections

解決 blueby 每次 scan 就會中斷先前連線的問題

困擾了很久
試過各種寫法 thread / lock / wait / pause / sleep 都無效

結果很簡單,只要 scan 時增加 passive=True 就好了

            scanner = Scanner().withDelegate(ScanDelegate())
            devices = scanner.scan(1.0, passive=True)

2019年3月29日 星期五

python 處理 word 表格

# coding=utf-8
import docx
import glob
import os
import csv

#設置檔案路徑
path = '範例檔'
#設置輸出檔名
output = 'output.csv'

#開啟輸出的 CSV 檔案
with open(output, 'w', newline='') as csvfile:
  #建立 CSV 檔寫入器
  writer = csv.writer(csvfile)
  #header
  writer.writerow(['檔名','學校','班級','學生','國語','數學','社會','自然','藝術'])
 
for filename in glob.glob(os.path.join(path, '*.docx')):    #遍歷所有檔案
    #doc = docx.Document("範例檔\su_sn_11122.docx")
    doc = docx.Document(filename)
    for table in doc.tables:    #遍歷所有表格
        print("--------")
        _school = ''
        _class = ''
        _student = ''
        _score1 = ''
        _score2 = ''
        _score3 = ''
        _score4 = ''
        _score5 = ''
        done = False
        i = 0
        for row in table.rows:  #遍歷表格的所有 row
            #row_str = "\t".join([cell.text for cell in row.cells])  # 一行數據
            #print(row_str)
            j = 0
            for cell in row.cells:  #遍歷 row 中所有 cell
                #print( cell.text + "\t" )
                #print( str(i)+":"+str(j)+":"+table.cell( i, j ).text + "\t" )
                if cell.text == '學校':
                    _school = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '班級':
                    _class = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '學生':
                    _student = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '國語':
                    _score1 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '數學':
                    _score2 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '社會':
                    _score3 = table.cell( i+1, j ).text  #下面的 cell
                if cell.text == '自然':
                    _score4 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '藝術':
                    _score5 = table.cell( i+1, j ).text  #抓下面的 cell
                    done = True #這是最後一筆資料
                j = j + 1   #指向下一 cell
                if done:
                    break   #完成
            i = i + 1   #指向下一 row
            if done:
                break   #完成
        print( _school )
        print( _class )
        print( _student )
        print( _score1 )
        print( _score2 )
        print( _score3 )
        print( _score4 )
        print( _score5 )
        with open('output.csv', 'a', newline='') as csvfile:
            #建立 CSV 檔寫入器
            writer = csv.writer(csvfile)
            #內容
            writer.writerow([filename,_school,_class,_student,_score1,_score2,_score3,_score4,_score5])
        break #限制1檔1表

2019年3月15日 星期五

Modbus 傳輸資料型態轉換

Modbus 協議傳輸的資料一般只有基本的 U16 型態,但在實際應用上可能因裝置不同而有不同的應用,例如長整數、浮點數,但又因為硬體 CPU/MCU/OS 實際狀況而有位元順序的問題,底下是 python 轉換函式…

def Convert( theType, values  ):
    if( theType == 'FLOAT(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'UINT32(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'INT32(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'UINT16(AB)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[0],tobytes[1])
            set_value = struct.unpack('>H', packit)[0]
    elif( theType == 'UINT16(BA)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[1],tobytes[0])
            set_value = struct.unpack('>H', packit)[0]
    elif( theType == 'INT16(AB)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[0],tobytes[1])
            set_value = struct.unpack('>h', packit)[0]
    elif( theType == 'INT16(BA)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[1],tobytes[0])
            set_value = struct.unpack('>h', packit)[0]
    else:
        set_value = values[0]
    return set_value

#Modbus 讀值可能是 2byte 也可能是 4byte
values = [-4370,-8756]
Convert( 'FLOAT(ABCD)' ,values )
Convert( 'FLOAT(DCBA)' ,values )
Convert( 'FLOAT(BADC)'  ,values )
Convert( 'FLOAT(CDAB)'  ,values )
Convert( 'UINT32(ABCD)'  ,values )
Convert( 'UINT32(DCBA)'  ,values )
Convert( 'UINT32(BADC)'  ,values )
Convert( 'UINT32(CDAB)'  ,values )
Convert( 'INT32(ABCD)'  ,values )
Convert( 'INT32(DCBA)'  ,values )
Convert( 'INT32(BADC)'  ,values )
Convert( 'INT32(CDAB)'  ,values )
Convert( 'UINT16(AB)'  ,values )
Convert( 'INT16(AB)'  ,values )
Convert( 'INT16(BA)'  ,values )
Convert( 'UINT16(BA)'  ,values )

2018年1月16日 星期二

pysnmp startup

DOWNLOAD...
https://github.com/xfguo/pysnmp
http://snmplabs.com/pysnmp/
https://pypi.python.org/pypi/pysnmp/#downloads

INSTALL...
tar zxf package-X.X.X.tar.gz
cd package-X.X.X
python setup.py install
or...
pip install pysnmp
or...
easy_install pysnmp

EXAMPLE...
read…
http://www.nealc.com/blog/blog/2013/02/23/writing-an-snmp-agent-with-a-custom-mib-using-pysnmp/
readwrite…
http://www.cloud-rocket.com/2013/08/writing-custom-mib-for-pysnmp-agent/

1.create mib file MY-MIB
2.convert mib to py...
        build-pysnmp-mib -o MY-MIB.py MY-MIB
3.modify ip, get, trap functions
4.stop net-snmp
        service snmpd stop
        sudo update-rc.d snmpd disable
5.run example

        modify...
                ntfOrg = ntforg.NotificationOriginator(self._snmpContext)
        to...
                ntfOrg = ntforg.NotificationOriginator()
                ntfOrg.snmpContext = self._snmpContext

FIREWALL...
sudo iptables -A INPUT -p udp --dport 161 -j ACCEPT
or...
sudo ufw allow 161/udp

MIB BROWSER...
http://www.ireasoning.com/downloadmibbrowserfree.php

2017年12月21日 星期四

RaspberryPi BLE bluepy



install…
sudo apt-get install bluez
sudo hciconfig hci0 up

scan…
sudo hcitool lescan

or scan if no response...
sudo bluetoothctl
agent on
default-agent
scan on

other test...
using bluetoothctl

install bluepy…
https://github.com/IanHarvey/bluepy
sudo apt-get install python-pip libglib2.0-dev
sudo pip install bluepy

python test code…
from bluepy import btle
from bluepy.btle import Scanner, DefaultDelegate
import time
# Scan Delegate... 
class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

print 'Scanning...'
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(3.0)

address = None
for dev in devices:
    print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
    for (adtype, desc, value) in dev.getScanData():
        print "  %s = %s" % (desc, value)
        if desc == 'Complete Local Name' and value == 'YOUR_BLE_DEVICE_NAME':
            address = dev.addr

print "Connecting..."

#address = "YOUR_FIX_DEVICE_MAC"
dev = btle.Peripheral( address )

print "Services..."
for svc in dev.services:
    print str(svc)
    chs = svc.getCharacteristics()
    for ch in chs:
        print '  ' + str(ch)
# Notification Delegate
class MyDelegate(btle.DefaultDelegate):
    def __init__(self):
        btle.DefaultDelegate.__init__(self)
        # ... initialise here

    def handleNotification(self, cHandle, data):
        print 'handleNotification:' + str(data)
        # ... perhaps check cHandle
        # ... process 'data'


# Initialisation  -------

dev.setDelegate( MyDelegate() )

service_uuid = btle.UUID("49535343-fe7d-4ae5-8fa9-9fafd205e455") # YOUR SERVICE UUID
char_uuid = btle.UUID("49535343-1e4d-4bd9-ba61-23c647249616") # YOUR CHARACTERISTICS UUID

# Setup to turn notifications on, e.g.
svc = dev.getServiceByUUID( service_uuid )
ch = svc.getCharacteristics( char_uuid )[0]
# Here is how to write a value to Notification Characteristic... 
write_handle = ch.getHandle()
notify_handle = ch.getHandle() + 1
dev.writeCharacteristic( notify_handle, bytes("\x01"), withResponse=True)

time.sleep(1.0)

# Main loop --------
while True:
    if dev.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print "Waiting..."
    # Perhaps do something else here
    # Here is how to write a value to Characteristic
    dev.writeCharacteristic( write_handle, bytes("A"), False ) # YOUR DATA

2017年3月26日 星期日

python 透過 google smtp server 發信的方法

python code‧‧‧

import smtplib
    to = 'where@gmail.com'
    server = "smtp.gmail.com"
    #port = 465 # ssl
    port = 587 # tls
    gmail_user = 'youraccount@gmail.com'
    gmail_pwd = 'yourpassword or application password'
    #smtpserver = smtplib.SMTP_SSL(server, long(port)) # ssl
    smtpserver = smtplib.SMTP(server, long(port)) # tls
    smtpserver.ehlo()
    smtpserver.starttls() # tls
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:test \n'
    print header
    msg = header + '\n this is test \n\n'
    smtpserver.sendmail(gmail_user, to, msg)
    print 'done!'
    smtpserver.quit()

*如果你有使用兩階段驗證,必須先到 google 個人設定頁,增加應用程式密碼,smtp 才會驗證通過…
    https://myaccount.google.com/apppasswords

2017年3月1日 星期三

網頁後台使用 php 執行 python 操作 serial (uart) 權限的設定




uart0.php... (透過 shell_exec 執行 python 碼)
===============================================
$cmd = escapeshellcmd ( '/usr/bin/python uart0.py' );
$output = shell_exec ( $cmd );
echo $output;
===============================================

uart0.py... (console下執行沒問題,但透過 php 執行沒結果)
===============================================
import serial
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
serialport.write( "TEST" )
response = serialport.readlines(None)
print response
===============================================

解決… (需要設定裝置的權限 ttyAMA0 屬於 dialout 群組)
=1=暫時-reboot後無效==============================
sudo chmod 777 /dev/ttyAMA0
=2=============================================
sudo adduser youruser dialout
usermod -aG dialout youruser
===============================================


VirtualBox 空間減肥

@windows vm sdelete64 -z c: @macos VBoxManage  modifymedium  disk  "/Users/fellow/VirtualBox VMs/Win10/Win10.vdi"  --compact *.vdi...