NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

#!/usr/bin/env python3
"""
BeeTwin Basit Arduino Bridge
Arduino'dan veri alır ve PC Backend'e gönderir
"""

import serial
import requests
import time
import json
from datetime import datetime

# Configuration - PC IP'nizi buraya yazın
PC_BACKEND_URL = 'http://192.168.1.100:5000/api/lora/data' # PC IP'nizi değiştirin
ARDUINO_PORT = '/dev/ttyUSB0'
ARDUINO_BAUD = 9600

def parse_arduino_data(line):
"""Arduino text verisi parse et: RID:107; SID:1013; WT: 25.83"""
try:
if 'RID:' in line and 'SID:' in line:
parts = line.strip().split(';')

# RID parse
router_id = parts[0].split(':')[1].strip()

# SID parse
sensor_id = parts[1].split(':')[1].strip()

# Data parse
data_part = parts[2].strip()
data_key = data_part.split(':')[0].strip()
data_value = float(data_part.split(':')[1].strip())

return {
'router_id': router_id,
'sensor_id': sensor_id,
'data_key': data_key,
'data_value': data_value
}
except Exception as e:
print(f"❌ Parse hatası: {e} - Line: {line}")
return None

def send_to_backend(payload):
"""PC Backend'e veri gönder"""
try:
device_id = f"BT{payload['router_id']}"

# Backend API formatı
api_data = {
"deviceId": device_id,
"routerId": payload['router_id'],
"sensorId": payload['sensor_id'],
"batteryLevel": 85,
"signalStrength": -65,
"timestamp": datetime.now().isoformat(),
"sensorData": {}
}

# Data mapping
data_mapping = {
"WT": "temperature",
"WH": "humidity",
"PR": "pressure",
"AL": "altitude",
"CO": "co",
"NO": "no2",
"WC": "weight",
"WG": "weight",
"HC": "hydrogen",
"LC": "lpg",
"CC": "carbon_monoxide",
"AC": "alcohol",
"PC": "propane"
}

backend_key = data_mapping.get(payload['data_key'], payload['data_key'].lower())
api_data["sensorData"][backend_key] = payload['data_value']

print(f"📤 Backend'e gönderiliyor: {device_id} {payload['data_key']}={payload['data_value']}")

response = requests.post(
PC_BACKEND_URL,
json=api_data,
headers={'Content-Type': 'application/json'},
timeout=5
)

if response.status_code == 200:
print(f"✅ PC Backend başarılı: {device_id}")
return True
else:
print(f"⚠️ PC Backend HTTP {response.status_code}: {response.text}")
return False

except requests.exceptions.ConnectionError:
print(f"❌ PC Backend bağlantı hatası: {PC_BACKEND_URL}")
print("💡 PC'de backend çalışıyor mu kontrol edin")
return False
except Exception as e:
print(f"❌ Backend gönderim hatası: {e}")
return False

def test_backend_connection():
"""PC Backend bağlantısını test et"""
try:
health_url = PC_BACKEND_URL.replace('/api/lora/data', '/api/health')
response = requests.get(health_url, timeout=5)
if response.status_code == 200:
print("✅ PC Backend erişilebilir")
return True
else:
print(f"⚠️ PC Backend HTTP {response.status_code}")
return False
except:
print("❌ PC Backend'e bağlanılamıyor")
print(f"💡 URL kontrol edin: {PC_BACKEND_URL}")
return False

def main():
"""Ana bridge fonksiyonu"""
print("🐝 BeeTwin Basit Arduino Bridge")
print("=" * 50)
print(f"📡 Arduino Port: {ARDUINO_PORT}")
print(f"🌐 PC Backend: {PC_BACKEND_URL}")
print("=" * 50)

# Backend test
print("🔍 PC Backend bağlantısı test ediliyor...")
if not test_backend_connection():
print("⚠️ Backend bağlantısı yok, sadece veri okuma modunda devam")
backend_available = False
else:
backend_available = True

# Arduino bağlantısı
try:
print(f"n🔌 Arduino bağlantısı kuruluyor: {ARDUINO_PORT}")
ser = serial.Serial(ARDUINO_PORT, ARDUINO_BAUD, timeout=1)
time.sleep(2)
print("✅ Arduino bağlantısı başarılı")

print("n👂 Arduino verilerini dinlemeye başlıyor...")
print("💡 Çıkmak için Ctrl+C tuşlayınn")

packet_count = 0

while True:
try:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8', errors='ignore').strip()

if line and "Coordinator ready" not in line:
print(f"📥 Arduino: {line}")

# Parse et
payload = parse_arduino_data(line)
if payload:
packet_count += 1
print(f"📦 Paket #{packet_count}")
print(f" Router: {payload['router_id']}")
print(f" Sensor: {payload['sensor_id']}")
print(f" Data: {payload['data_key']} = {payload['data_value']}")

# Backend'e gönder
if backend_available:
success = send_to_backend(payload)
if success:
print(" ✅ Backend'e gönderildi")
else:
print(" ❌ Backend gönderim başarısız")
else:
print(" ⚠️ Backend kapalı, sadece okuma modu")

print("-" * 40)

time.sleep(0.1)

except KeyboardInterrupt:
print("nn🛑 Bridge durduruluyor...")
break
except Exception as e:
print(f"❌ Okuma hatası: {e}")
time.sleep(1)

except serial.SerialException as e:
print(f"❌ Arduino port hatası: {e}")
print("💡 Arduino bağlı mı ve port doğru mu kontrol edin")
except Exception as e:
print(f"❌ Beklenmeyen hata: {e}")
finally:
if 'ser' in locals() and ser.is_open:
ser.close()
print("👋 Bridge kapatıldı!")

if __name__ == "__main__":
main()
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.