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

2018年7月1日 星期日

mqtt@RaspberryPi

broker / server / client library install...
# 安裝 broker 及 所需函式庫

sudo apt-get install mosquitto mosquitto-clients
sudo apt-get install python3-pip
sudo pip3 install paho-mqtt

fix python search path...
# poah 安裝路徑若 python 找不到要作修正

cd /usr/lib/python2.7/dist-packages
sudo ln -s /usr/local/lib/python3.5/dist-packages/paho


subscribe...
# Subscribe 訂閱訊息/接收訊息

import paho.mqtt.client as mqtt 
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("where/is/my/topic") 

def on_message(client, userdata, msg):
  print(msg.topic+" "+str(msg.payload)) 

client = mqtt.Client()
client.on_connect = on_connect    #call back function
client.on_message = on_message    #call back function
client.connect("localhost", 1883, 60)
client.loop_forever()

pubilsh...
# Publisher 發佈訊息

import paho.mqtt.publish as publish
# publish a message then disconnect.

host = "localhost"
topic = "where/is/my/topic"
payload = "hello"

# If broker asks user/password.
auth = {'username': "", 'password': ""}

# If broker asks client ID.
client_id = ""

publish.single(topic, payload, qos=1, hostname=host)
#publish.single(topic, payload, qos=1, host=host, auth=auth, client_id=client_id)




2018年5月9日 星期三

Raspberry pi VLAN



Raspberry pi 3 僅一個 RJ45 port,若要當二個實體 ip 用,需建立 VLAN 虛擬網卡

二張網卡在不同子網域 A&B,A是主要網卡,B是延伸的虛擬網卡
A:IP=192.168.254.31
B:IP=192.168.1.31
其中一個 ip 必須能與其它裝置建立 UDP 通訊,且此裝置無法進行進一步的網路設置

注意!! UDP 是透過 python socket 的 create_udp_socket() 來建立連線,界面 A 必須建立在 UDP 所要通訊的網址上,否則無法正常通訊 why? route issues?

一、建立二張網卡界面…
sudo nano /etc/network/interfaces

iface eth0 inet manual

# VLAN Interface
auto eth0.1
iface eth0.1 inet manual
    vlan-raw-device eth0

二、設定二張網卡 ip / router …
sudo nano /etc/dhcpcd.conf

#A-->B-->
#A
interface eth0
static ip_address=192.168.254.31/16
static routers=192.168.1.31
static domain_name_servers=xxx.xxx.xxx.xxx

#B
# Static IP configuration for VLan
interface eth0.1
static ip_address=192.168.1.31/16
static routers=192.168.1.72
static domain_name_servers=xxx.xxx.xxx.xxx



2017年12月21日 星期四

Modbus TCP Slaver using Python modbus-tk lib


https://github.com/ljean/modbus-tk/

install pip…
sudo apt-get install python-pip

install...
download modbus_tk-x.x.x.tar.gz
tar zxvf modbus_tk-x.x.x.tar.gz
python setup.py install

make sure your port is open...
sudo iptables -A INPUT -p tcp --dport 502 -j ACCEPT # for slaver
sudo iptables -A OUTPUT -p tcp --dport 502 -j ACCEPT  # for master

run example as root
a simple example...
import sys
import logging
import threading
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus as modbus
import modbus_tk.modbus_tcp as modbus_tcp
import time

logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
# CREATE server
server = modbus_tcp.TcpServer() #DEFAULT PORT=502
slaver = server.add_slave(1) #ID=1

def setup():
    slaver.add_block("coil", cst.COILS, 0, 16)
    slaver.set_values("coil", 0, 16*[0])
       
def loop():
    logger.info("running...")
    # START
    server.start()
    while True:
        values = slaver.get_values("coil", 0, 8)
        #print values[0]
        str = ''
        for i in range(0, 8):
            if values[i] == 1:
                str = str + '1'
            else:
                str = str + '0'
        print  str
        # DELAY
        time.sleep(1)
        
def destory():
    logger.info("destory")
    # STOP
    server.stop()
       
if __name__ == "__main__":
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destory()


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

2016年4月26日 星期二

Xilinx Virtual Download Cable using Raspberry Pi

based on this project below…( Thanks this great project )
https://github.com/tmbinc/xvcd

just replacement following function calls…

======== gipo.c ========
#include

#define GPIO_TDI 3       /// JTAG TDI pin
#define GPIO_TDO 12   /// JTAG TDO pin
#define GPIO_TCK 13   /// JTAG TCK pin
#define GPIO_TMS 14   /// JTAG TMS pin

void gpio_init(void)
{
if (wiringPiSetup() == -1)
return;
gpio_output(GPIO_TDI, 1);
gpio_output(GPIO_TMS, 1);
gpio_output(GPIO_TCK, 1);
gpio_output(GPIO_TDO, 0);
}

void gpio_close(void)
{
}
================

======== gipo_inline.h ========
static inline void gpio_output(int i, int dir)
{
if (dir)
pinMode (i, OUTPUT);
else
pinMode (i, INPUT);
}

static inline void gpio_set(int i, int val)
{
if (!val)
digitalWrite (i, 0) ; // Off
else
digitalWrite (i, 1) ; // On

}

static inline int gpio_get(int i)
{
return (digitalRead( i )!=0);
}
================

Tested with NetBeans IDE 8.1 + Raspberry Pi 1 & 2 + Xilinx XC3S400AN



2016年4月22日 星期五

NETBEANS 開發 RASPBERRY PI APP

使用 NETBEANS 開發 RASPBERRY PI APP
非常方便,可遠端開發、執行偵錯

請參考此篇…
http://www.raspberry-projects.com/pi/programming-in-c/compilers-and-ides/netbeans-windows/installing-netbeans-for-c-remote-development-on-a-raspberry-pi

主要需增加一個遠端 HOST 的設定

若有使用 WIRING PI 等 I/O 底層服務,則需以 ROOT 身份進行遠端操作
可參考此篇…
http://www.raspberry-projects.com/pi/programming-in-c/compilers-and-ides/netbeans-windows/creating-a-new-project

主要為了打開 ROOT 帳戶
sudo passwd root
sudo nano /etc/ssh/sshd_config
PermitRootLogin and change it to yes (the default "without-password" won't work – change it to "yes"
存檔後 reboot

2016年4月18日 星期一

這些年摸過的小玩意

記錄一下這些年摸過的小玩意…

RASPBERRY PI : 拿來開發較複雜的系統很好,Linux base 的核心基本上可以玩的東西就很多了,而且資源也很豐富。

Intel Galileo : 只稍微摸看看,基本上能玩的跟 PI 應該大同小意。

Arduino DUE : 32bit ARM 作出來的強化版 Arduino,可以開發 ADK( Android Open Accessory Development Kit) 不過現在都走無線的了吧?

Arduino UNO : 好用是無庸置疑的,拿來作快速開發,網路上還有一堆 lib 可以用。

TI MSP430 : Good

ESP2866 : 小型 wifi 嵌入式系統,腳位不多,可以拿來作 iot 之類的東西。

TI CC2541 : 藍牙模組,可以拿來作 iot 之類的東西,開發手機應用產品。

EN28j60 : 8bit 低階 MCU 上網功能,還算堪用,也因此學會了很多網路底層的東西。

STM32F030 : 便宜的 ARM,拿來當強化版的 8bit MCU 用。

Freescale FRDM KL-05 : 還 ok。

Freescale TWR-S12G128 : 還 ok。☆

Arduino W5100  Ethernet Shield : Arduino 要簡單上網就靠它了。

STM32 Demo Board : 拿來學習 ARM 的板子。

ST NUCLEO-F411RE : mbed 開發版。

STM32 Demo Board : 拿來學習 ARM 的板子。

還有其它數不清的小模組板…

2013年5月16日 星期四

Raspberry Pi + Cross Compiler + MySQL

要在 Cross Compiler 上建立 MySQL Connect API 的編譯環境
必須要有 .h include 檔及 mysqlclient lib 檔。

一、先在 Raspberry Pi 下載 MySql connector for C
 wget  http://lgallardo.com/wp-content/uploads/files/programming/mysql-connector-c-6.0.2.tar.gz

二、解壓縮
 tar xvzf mysql-connector-c-6.0.2.tar.gz
 cd mysql-connector-c-6.0.2
 
三、安裝 cmake
 sudo aptitude install cmake
 
四、產出 makefile 檔,其中「install_path」自定義
 cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=/install_path 
 
五、make 需要很久的時間
 
六、make install
 
七、確認是否正確安裝
 file /install_path/lib/libmysql.so.16.0.0 
 

八、將 /install_path 底下所有東西 copy 至 cross compiler host 機上。
 

九、範例程式…
    #include <mysql.h>
    MYSQL      *MySQLConRet;
    MYSQL      *MySQLConnection = NULL;
    MySQLConnection = mysql_init( NULL );

    MySQLConRet = mysql_real_connect( MySQLConnection,
                                          hostName,
                                          userId,
                                          password,
                                          db_name,
                                          0,
                                          "/var/run/mysqld/mysqld.sock",
                                          0 );
 
 注意:socket位置預設是 /tmp/mysql.sock,需按你系統所在位置填入正確值否則會出現…
 runtime error:Can't connect to local MySQL server through socket '/tmp/mysql.sock' 
 socket位置可以在 /etc/mysql/my.cnf 或 /etc/mysql/debian.cnf 查詢到。
九、編譯時引入 mysqlclient 函式庫並增加 include 及 lib patch
 gcc client.c -o client  -I/install_path/include -L/install_path/lib -lmysqlclient
 
 ext. links…
http://lgallardo.com/en/2011/07/14/conector-mysql-para-openwrt-mips/
 
=================================================================================
較簡單的方法…
1.安裝開發工具…
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install libmysqlclient-dev
 
2.從 pi copy header 檔到開發環境,Eclipse 下增加 include path…
/usr/include/mysql

3.從 pi copy lib 檔到開發環境,Eclipse 下增加 lib path
使用指令查出 lib 位置…
mysql_config --libs
 
查出放在「/usr/lib/arm-linux-gnueabihf」底下,並在 linker command 增加 -lmysqlclient
libmysqlclient.a
libmysqlclient.so 

4.若缺少 libz (compress、uncompress) 亦需一併 copy 過去開發環境,並在 linker command 增加 -lz
libz.a
libz.so




2013年4月30日 星期二

RaspberryPI 交叉編譯環境增加 wringPi 函式庫

需先設置好 RaspberryPI 交叉編譯環境
再進行底下步驟…

第一步,登入 RaspberryPI…
一、安裝 libi2c-dev ,要 lib 支援 i2c 的話,要先安裝好 wiringPi 才會編譯成支援 i2c。
sudo apt-get install libi2c-dev
二、安裝 git
sudo apt-get install git-core
三、下載 wiringPi source,並安裝
git clone git://git.drogon.net/wiringPi  
cd wiringPi
git pull origin
./build
四、想辦法把底下 lib 檔 copy 或 link 到交叉編譯 host 主機上,並重新命名為「libwiringPi.so」
/usr/local/lib/libwiringPi.so.1.0

第二步,到交叉編譯 host 主機上…
一、下載 wiringPi source,不需安裝,或想辦法把 RaspberryPI 上的 .h 檔 copy 到 host 主機上。
git clone git://git.drogon.net/wiringPi  
cd wiringPi
git pull origin
二、執行 Eclipse
三、至 Project Properties 
 --> GCC C++ Compiler 
 --> Includes 
 --> Include path TAB 增加 .h 所在的路徑…
/home/pi/wiringPi/wiringPi
四、至 Project Properties 
 --> GCC C++ Linker 
 --> Libraries 
 --> Libraries TAB 增加…
wiringPi
 --> Libraries search path TAB 增加「libwiringPi.so」目錄的位置…
/home/pi/wiringPi/wiringPi

done.
 
ext. links…
https://projects.drogon.net/raspberry-pi/wiringpi/
http://hertaville.com/2012/09/28/development-environment-raspberry-pi-cross-compiler/
 
 

2013年4月27日 星期六

Raspberry PI 交叉編譯環境配置…

http://hertaville.com/2012/09/28/development-environment-raspberry-pi-cross-compiler/

按步驟完成。

apt-get install git rsync cmake
mkdir rpi
cd rpi
git clone git://github.com/raspberrypi/tools.git
cd ~/
nano .bashrc
    ADD LINE : export PATH=$PATH:$HOME/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin
source .bashrc
arm-linux-gnueabihf-gcc -v
sudo apt-get install openjdk-7-jre
DOWNLOAD ECLIPSE FROM : http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers/keplerr
tar -xvzf eclipse-cpp-kepler-R-linux-gtk-x86_64.tar.gz -C ~/
~/eclipse/eclipse &

New project
Cross GCC
Cross compiler prefix : arm-linux-gnueabihf-
Cross compiler path : /home//rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/

新專案記得存檔

VirtualBox 空間減肥

sdelete64 -z c: VBoxManage  modifymedium  disk  "/Users/fellow/VirtualBox VMs/Win10/Win10.vdi"  --compact *.vdi 路徑可以在 VirtualBox 儲...