Micropython and Bluetooth on ESP32 - bluetooth

I know the support for bluetooth is still under development but it seems to cover everything I need at this point so I decided to give it a try.
I just want to simulate reading from a source of data (a EKG machine) so I came up with this code:
from ubluetooth import BLE
from ubluetooth import FLAG_READ, FLAG_NOTIFY, FLAG_WRITE
import time
ekg_data = [-305,-431,-131,440 ,1158,1424,1445,1623,1500,1018,142 ,-384,-324,-414,-77 ,334 ,-372,-154,366 ,7613,1461,1403,6133,-179,-381,-224,-135,-168,-208,-187,-181,-180,-160,-160,-151,-150,-151,-138,-141,-128,-118,-106,-798,-677,-430,-253,-122,98 ,133 ,281 ,354 ,390 ,519 ,475 ,558 ,565 ,533 ,593 ,458 ,377 ,107 ,-335,-719,-116,-129,-132,-131,-119,-122,-111,-106,-105,-935,-971,-877,-841,-841,-725,-757,-660,-641,-660,-554,-592,-496,-473,-486,-387,-431,-350,-364,-347,-208,-365,-362]
bt = BLE()
bt.active(True)
print('----')
print(bt.config('mac'))
print(bt.config('gap_name'))
HR_UUID = bluetooth.UUID(0x180D)
HR_CHAR = (bluetooth.UUID(0x2A37), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
HR_SERVICE = (HR_UUID, (HR_CHAR,),)
SERVICES = (HR_SERVICE,)
((ekg,),) = bt.gatts_register_services(SERVICES)
# bt.gap_advertise(100, 'MicroPython EKG')
count = 0
while True:
if count >= len(ekg_data):
count = 0
bt.gatts_write(ekg, ekg_data[count].to_bytes(2, 'big'))
print(ekg_data[count])
time.sleep_ms(1000)
count += 1
Now the code compiles and runs (I can see the output on the console) but I cannot find the device in my bluetooth app (I am using the nordic app)
Does anyone with more knowledge on that area can tell me if I am overlooking something? I tried to take the advertising off and on because I thought I might be overriding something with it but that didn't help too...

I think your code is missing multiple things.
First, you are not setting (irq) which is (Event Handling) for Micropython(As you can see from the docs or in their Github codes.
Also, I can't see you setting the buffer or any stuff like that, please revise the examples for what you asking here. Good job btw.

Related

STM32 SPDIFRX Peripheral problem (interupts not firing)

I am trying to make myself Digital audio to Analog audio converter
I have STM32F769i Discovery0: https://www.st.com/en/evaluation-tools/32f769idiscovery.html
Which has SPDIFRX and SPDIFTX ports
I found a fearly good starting point here: http://www.tjaekel.com/DiscoveryF7Audio/index.html
Also the guy posted here: https://www.openstm32.org/forumthread921
But the guy used STM32746G Discovery: https://www.st.com/en/evaluation-tools/32f746gdiscovery.html
Instead
So I went and tried to just get his SPDIF audio portion working on my board
My Project can be found here (I hope it compiles, with CubeIDE you never know what will happen :)): https://www.mediafire.com/file/n0s2z9p6nn735qg/SPDIF_Example.zip/file
I have no idea what I am doing wrong, but for some reason SPDIF_RX_IRQHandler (in stm32f7xx_it.c) is never called (LED never turns green, yea my debugging tehniques are primitive, but will explain why later)
So because of that HAL_SPDIFRX_ReceiveDataFlow_IT (in spdifrx.c) always returns HAL_TIMEOUNT, and of course no audio is ever played on the speakers
I am not sure what I am doing wrong
When I start MCU I call BSP_SPDIF_Init() (defined in spdifrx.c) in main.c right after I take care of the clock
if (BSP_SPDIFRX_Init() != HAL_OK)
{
Error_Handler();
}
And it appears it initializes all right, because I get HAL_OK back
Maybe I am not inializing GPIO properly from HAL_MspInit in stm32f7xx_hal_msp.c inproperly
I am realy out of ideas, what I am doing wrong, because the analog side of the audio does init, I can hear that as pop pop from the speakers when I power up my MCU, its just that SPDIF side has problems
I am is my setup crocked?
I am using this component radio as my SPDIF transmitter (Hama DIT2000M): https://de.hama.com/webresources/article-documents/00054/man/00054821man_en.pdf
It says it has SPDIF Audio out (it says its digital over coaxial)
I know its optical side is working fine because on my component receiver it plays just fine (it reports as 48khz Stereo)
Is my cable to long? I am using this cable: https://i.imgur.com/JqAxePF.jpg
(not sure who made it)
Now why do I debug with blinking leds, because where my test subject is (my Hama receiver), there is no computer so…. Blinking leds it is, I would like to avoid aditional libraries and have a minimum working example, because you never know what problems they could bring so that's why LCD is not used right now
I hope someone has any advice, eather how to get any data in to SPDIF port (because right now for some reason, I don't get anything) or what I am doing wrong for my audio not to play, the usage of STM32F769i Discovery0 instead of STM32746G Discovery is probably not responsible 
I hope that this is a proper place for this king of questions, because I did ask a question regarding SPDIF on the STM forum: https://community.st.com/s/feed/0D53W00001z0RaqSAE
But didn't get any usefull advice there
Now SPDIF realy does not have much examples, there is only a polling example which does work (with the same cable), there is no interupt example, my interupt example (you can read the post on the STM forum post I linked) is not working as well (interupts are probably not broken right?)
So yea, I am lost a bit not sure what to do, and who to ask, so I tried here
PS: I know stackvoverflow does not like links to code, but I believe something is wrong with my project (interupts don't fire for some reason), and its realy hard to put this all into the question
Thanks for Anwsering and Best Regards
I managed to solve this, I guess I did not initialize SPDIF GPIO properly
after setting this
GPIO_InitStructure.Pin = GPIO_PIN_7;
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
GPIO_InitStructure.Alternate = DISCOVERY_SPDIFRX_AF;
HAL_GPIO_Init(GPIOD, &GPIO_InitStructure);
to this
GPIO_InitStructure.Pin = GPIO_PIN_12;
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
GPIO_InitStructure.Alternate = GPIO_AF7_SPDIFRX;
HAL_GPIO_Init(GPIOG, &GPIO_InitStructure);
interupts started to fire

How to use pystemd to control systemd timedated ntp service?

I'm working on a python app that needs to get the NTPSynchronized parameter from system-timedated. I'd also like to be able to start and stop the NTP service by using the SetNTP method.
To communicate with timedated over d-bus I have been using this as reference: https://www.freedesktop.org/wiki/Software/systemd/timedated/
I previously got this working with dbus-python, but have since learned that this library has been deprecated. I tried the dbus_next package, but that does not have support for Python 3.5, which I need.
I came across the pystemd package, but I am unsure if this can be used to do what I want. The only documentation I have been able to find is this example (https://github.com/facebookincubator/pystemd), but I can not figure out how to use this to work with system-timedated.
Here is the code I have that works with dbus-python:
import dbus
BUS_NAME = 'org.freedesktop.timedate1`
IFACE = 'org.freedesktop.timedate1`
bus = dbus.SystemBus()
timedate_obj = bus.get_object(BUS_NAME, '/org/freedesktop/timedate1')
# Get synchronization value
is_sync = timedate_obj.Get(BUS_NAME, 'NTPSynchronized', dbus_interface=dbus.PROPERTIES_IFACE)
# Turn off NTP
timedate_obj.SetNTP(False,False, dbus_interface=IFACE)
Here's what I have so far with pystemd, but I don't think I'm accessing it in the right way:
from pystemd.systemd1 import Unit
unit = Unit(b'systemd-timesyncd.service')
unit.load()
# Try to access properties
prop = unit.Properties
prop.NTPSynchronized
Running that I get:
Attribute Error: 'SDInterface' object has no attribute 'NTPSynchronized'
I have a feeling that either the service I entered is wrong, or the way I'm accessing properties is wrong, or even both are wrong.
Any help or advice is appreciated.
Looking at the source code, it appears that using the pystemd.systemd1 Unit object has a default destination of "org.freedesktop.systemd1" + the service name (https://github.com/facebookincubator/pystemd/blob/master/pystemd/systemd1/unit.py)
This is not what I want because I am trying to access "org.freedesktop.timedate1"
So instead I instantiated it's base class SDObject from pystemd.base (https://github.com/facebookincubator/pystemd/blob/master/pystemd/base.py)
The following code allowed me to get the sync status of NTP
from pystemd.base import SDObject
obj = SDObject(
destination=b'org.freedesktop.timedate1',
path=b'/org/freedesktop/timedate1',
bus=None,
_autoload=False
)
obj.load()
is_sync = obj.Properties.Get('org.freedesktop.timedate1','NTPSynchronized')
print(is_sync)
Not sure if this is what the library author intended, but hey it works!

Bluetoothctl or gatttool for BLE notifications from multiple devices

I have read many questions on the topic but found no information on how to best (or if it is even possible) to receive notifications from more than 1 device at a time using any library or API (preferably command line or Python library).
After connecting to different devices e.g. Heart Rate monitor and Phone, or two HR monitors, is there a way to receive data from 1 service from each device at the same time?
EDIT:
I have managed to connect different devices of the same characteristics and been able to get notifications from them using Bluetoothctl (part of Bluez) so long as I don't request the same service, which answers my question partially; still, does anyone know of a better way to do this?
1) First of all there is a github python project that does just that in Linux on Raspberry Pi: https://github.com/IanHarvey/bluepy
2) Second this snipet from Anthony Chiu uses that API to communicate with multiple devices using notifications:
from bluepy.btle import Scanner, DefaultDelegate, Peripheral
import threading
class NotificationDelegate(DefaultDelegate):
def __init__(self, number):
DefaultDelegate.__init__(self)
self.number = number
def handleNotification(self, cHandle, data):
print 'Notification:\nConnection:'+str(self.number)+ \nHandler:'+str(cHandle)+'\nMsg:'+data
bt_addrs = ['00:15:83:00:45:98', '00:15:83:00:86:72']
connections = []
connection_threads = []
scanner = Scanner(0)
class ConnectionHandlerThread (threading.Thread):
def __init__(self, connection_index):
threading.Thread.__init__(self)
self.connection_index = connection_index
def run(self):
connection = connections[self.connection_index]
connection.setDelegate(NotificationDelegate(self.connection_index))
while True:
if connection.waitForNotifications(1):
connection.writeCharacteristic(37, 'Thank you for the notification!')
while True:
print'Connected: '+str(len(connection_threads))
print 'Scanning...'
devices = scanner.scan(2)
for d in devices:
print(d.addr)
if d.addr in bt_addrs:
p = Peripheral(d)
connections.append(p)
t = ConnectionHandlerThread(len(connections)-1)
t.start()
connection_threads.append(t)
3) I will just write the manual connection option with bluetoothctl that you probably tried. Since it wasn't listed here, I will add that too:
**Manual connection with bluetoothctl: ** To get the list of characteristics you can use the “list-attributes” command after establing connection and entering Generic Attribute Submenu through menu gatt in bluetoothctl, which should print the same list as above:
list-attributes 00:61:61:15:8D:60
To read an attribute you first select it, with the -you guessed it- “select-attribute” command:
select-attribute /org/bluez/hci0/dev_00_61_61_15_8D_60/service000a/char000b
After that you can issue the “read” command, without any parameters.
To read a characteristic continuously (if characteristic supports it) , use the “notify” command:
notify on
PS: This is my first answer on stackoverflow :)
I am also new to BLE, so bear with me. Am interested in your project, any links / contact are appreciated :)
You can find me on alexandrudancu.com

Playing Music on Roblox locally

I'm a tad stuck with local music playing on my Roblox game.
I've got a setup on my game where a script inserts five sound files into a player's GUI. When a sever is made these sounds do make it to the players gui.
To play the sounds there are parts setup that check for collisions with players and when they detect a player they will start one of the five sounds in the player's GUI.
This is what the code in one of the parts looks like:
script.Parent.Touched:connect(function(hit)
if hit.Parent:FindFirstChild('Humanoid') then
if game.Players[hit.Parent.Name].PlayerGui.Sound2.TimePosition < 1 then
game.Players[hit.Parent.Name].PlayerGui.Sound2.Volume = 1
game.Players[hit.Parent.Name].PlayerGui.Sound2:Play()
game.Players[hit.Parent.Name].PlayerGui.Sound1:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound4:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound3:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound5:Stop()
end
end
end)
This script does detect players just fine as I have tested it. The system does work in the Roblox Studio testing area however when a server is launched with it none of the sounds are played.
The server does in fact set the sounds to playing and they appear as playing on the client side from the server side however the client side does not see them as playing and they do not play.
I do have filtering enabled turned on but this shouldn't effect it...
I believe it is something quite simple. I think it is a function of the SoundService. Correct me if this doesnt work, but i believe this is it
soundobj = game.Players[hit.Parent.Name].PlayerGui.Sound2
game:GetService('SoundService'):PlayLocalSound(soundobj)
see https://wiki.roblox.com/index.php?title=API:Class/SoundService/PlayLocalSound for more info
A way to do that is parenting the sounds to PlayerGui (I think you needed a ScreenGui) and then :Play() them.
Filtering enabled is the reason this doesn't work.
To solve this you can use a RemoteEvent located in the ReplicatedStorage of your game.
The sounds must be placed in the StarterGUI and there should be a localscript with this code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local event = ReplicatedStorage:WaitForChild("REMOTE EVENT NAME")
script.Parent.Sound2.Playing = true
local function onNewPlayerFired(sound)
script.Parent.Sound1.Playing = false
script.Parent.Sound2.Playing = false
script.Parent.Sound3.Playing = false
script.Parent.Sound4.Playing = false
script.Parent.Sound5.Playing = false
script.Parent[sound].Playing = true
end
event.OnClientEvent:Connect(onNewPlayerFired)
and in the part for each sound trigger part there should be this code:
local debounce = false
script.Parent.Touched:connect(function(hit)
if debounce == true then return end
debounce = true
if hit.Parent:FindFirstChild('Humanoid') then
local plr = game.Players:FindFirstChild(hit.Parent.Name)
game.ReplicatedStorage.REMOTE EVENT NAME:FireClient(plr,"SOUND NAME")
end
wait(2)
debounce = false
end)
I recently ran into this issue while making a music player. It ended up being the silliest thing and had everything to do with FE. My player worked in Test Studio, but gave me a whole laundry list of error codes that I was able to fix simply by changing the script to a local script. Literally all the same code worked as it did in studio but client side. It took me a entire day of head scratching and wiki searching to figure out my mistake. FE was initially a nightmare for me, but I have come to love the security it provides my games. :)

Graphics Server Documentation or User Guide

I got a very old Classic ASP code which is running on windows server 2003 the code has lines something like GSDSVR.GSServerProp and GSSERVER.GSServerProp. After some research I found that this is some kind of Graphic Server Component to generate chats or graphics, but I am unable to find any example on how to use it.
Block of code I have-
Set GSObject("Bar") = Server.CreateObject("GSDSVR.GSServerProp")
GSObject("Bar").URL = Graphics_URL
... more stuff ...
GSObject("Bar").Height = 291
GSObject("Bar").ClipGraph = 1
Tmp_FileName = GSObject("Bar").DrawGraph()
The code generates chart(s) based on some data, Now I want to achieve this using .net.
The problem I am facing is I don't know what is happening in code I just know the out of the code.
Can anyone please help me with documentation or few examples for this graphic server component?

Resources