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



2018年3月20日 星期二

Make Raspberry pi as a Bluetooth Peripheral Device


install nodejs npm
sudo apt-get install nodejs npm

install nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
source ~/.bashrc
nvm install stable

install bleno
npm install bleno

example code…
http://www.skyrise.tech/blog/tech/bluetooth-raspberry-pi-bleno-part-1-ibeacon/
https://github.com/noble/bleno/blob/master/test.js

run…
node app.js

run BLE App @ ur phone

what's next ?

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日 星期四

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

2017年8月24日 星期四

Building BetaFlight

Building BetaFlight

@UBUNTU/WIN10-BASH


Toolchain
sudo add-apt-repository ppa:team-gcc-arm-embedded/ppa
sudo apt-get update
sudo apt-get install gcc-arm-embedded
sudo apt-get install build-essential   /// for gcc if needed

SSH Key
ssh-keygen -t rsa -b 4096 -C "youraccount@git.hub"
cat ~/.ssh/id_rsa.pub
ssh-add ~/.ssh/id_rsa

GitHub new ssh key

Make
sudo apt-get install git   /// if needed
git clone git@github.com:betaflight/betaflight.git
cd betaflight
sudo make TARGET=NAZE


Update
git reset --hard
git pull
sudo make clean TARGET=NAZE


VirtualBox 空間減肥

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